initial commit
authorvb
Wed, 25 Jun 2014 18:44:58 +0200
changeset 016f27efbef98
child 1 06e02338bdd8
initial commit
pEpEngine.vcxproj
pEpEngine.vcxproj.filters
src/keymanagement.c
src/keymanagement.h
src/pEpEngine.c
src/pEpEngine.h
src/platform_windows.cpp
src/platform_windows.h
src/sqlite3.c
src/sqlite3.h
test/pEpEngineTest.cc
test/pEpEngineTest.vcxproj
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/pEpEngine.vcxproj	Wed Jun 25 18:44:58 2014 +0200
     1.3 @@ -0,0 +1,98 @@
     1.4 +<?xml version="1.0" encoding="utf-8"?>
     1.5 +<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
     1.6 +  <ItemGroup Label="ProjectConfigurations">
     1.7 +    <ProjectConfiguration Include="Debug|Win32">
     1.8 +      <Configuration>Debug</Configuration>
     1.9 +      <Platform>Win32</Platform>
    1.10 +    </ProjectConfiguration>
    1.11 +    <ProjectConfiguration Include="Release|Win32">
    1.12 +      <Configuration>Release</Configuration>
    1.13 +      <Platform>Win32</Platform>
    1.14 +    </ProjectConfiguration>
    1.15 +  </ItemGroup>
    1.16 +  <PropertyGroup Label="Globals">
    1.17 +    <ProjectGuid>{146E69F8-E1DA-456A-B048-6DD29D9ACF6B}</ProjectGuid>
    1.18 +    <Keyword>Win32Proj</Keyword>
    1.19 +    <RootNamespace>pEpEngine</RootNamespace>
    1.20 +  </PropertyGroup>
    1.21 +  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
    1.22 +  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    1.23 +    <ConfigurationType>DynamicLibrary</ConfigurationType>
    1.24 +    <UseDebugLibraries>true</UseDebugLibraries>
    1.25 +    <PlatformToolset>v120</PlatformToolset>
    1.26 +    <CharacterSet>Unicode</CharacterSet>
    1.27 +  </PropertyGroup>
    1.28 +  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    1.29 +    <ConfigurationType>DynamicLibrary</ConfigurationType>
    1.30 +    <UseDebugLibraries>false</UseDebugLibraries>
    1.31 +    <PlatformToolset>v120</PlatformToolset>
    1.32 +    <WholeProgramOptimization>true</WholeProgramOptimization>
    1.33 +    <CharacterSet>Unicode</CharacterSet>
    1.34 +  </PropertyGroup>
    1.35 +  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
    1.36 +  <ImportGroup Label="ExtensionSettings">
    1.37 +  </ImportGroup>
    1.38 +  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    1.39 +    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
    1.40 +  </ImportGroup>
    1.41 +  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    1.42 +    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
    1.43 +  </ImportGroup>
    1.44 +  <PropertyGroup Label="UserMacros" />
    1.45 +  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    1.46 +    <LinkIncremental>true</LinkIncremental>
    1.47 +    <IncludePath>C:\Program Files %28x86%29\GNU\GnuPG\include;$(IncludePath)</IncludePath>
    1.48 +    <RunCodeAnalysis>true</RunCodeAnalysis>
    1.49 +  </PropertyGroup>
    1.50 +  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    1.51 +    <LinkIncremental>false</LinkIncremental>
    1.52 +    <IncludePath>C:\Program Files %28x86%29\GNU\GnuPG\include;$(IncludePath)</IncludePath>
    1.53 +  </PropertyGroup>
    1.54 +  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    1.55 +    <ClCompile>
    1.56 +      <PrecompiledHeader>NotUsing</PrecompiledHeader>
    1.57 +      <WarningLevel>Level3</WarningLevel>
    1.58 +      <Optimization>Disabled</Optimization>
    1.59 +      <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;PEPENGINE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    1.60 +      <SDLCheck>true</SDLCheck>
    1.61 +      <EnablePREfast>true</EnablePREfast>
    1.62 +    </ClCompile>
    1.63 +    <Link>
    1.64 +      <SubSystem>Windows</SubSystem>
    1.65 +      <GenerateDebugInformation>true</GenerateDebugInformation>
    1.66 +    </Link>
    1.67 +  </ItemDefinitionGroup>
    1.68 +  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    1.69 +    <ClCompile>
    1.70 +      <WarningLevel>Level3</WarningLevel>
    1.71 +      <PrecompiledHeader>NotUsing</PrecompiledHeader>
    1.72 +      <Optimization>MaxSpeed</Optimization>
    1.73 +      <FunctionLevelLinking>true</FunctionLevelLinking>
    1.74 +      <IntrinsicFunctions>true</IntrinsicFunctions>
    1.75 +      <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;PEPENGINE_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    1.76 +      <SDLCheck>false</SDLCheck>
    1.77 +      <TreatWarningAsError>false</TreatWarningAsError>
    1.78 +    </ClCompile>
    1.79 +    <Link>
    1.80 +      <SubSystem>Windows</SubSystem>
    1.81 +      <GenerateDebugInformation>true</GenerateDebugInformation>
    1.82 +      <EnableCOMDATFolding>true</EnableCOMDATFolding>
    1.83 +      <OptimizeReferences>true</OptimizeReferences>
    1.84 +    </Link>
    1.85 +  </ItemDefinitionGroup>
    1.86 +  <ItemGroup>
    1.87 +    <ClCompile Include="src\keymanagement.c" />
    1.88 +    <ClCompile Include="src\pEpEngine.c" />
    1.89 +    <ClCompile Include="src\platform_windows.cpp" />
    1.90 +    <ClCompile Include="src\sqlite3.c" />
    1.91 +  </ItemGroup>
    1.92 +  <ItemGroup>
    1.93 +    <ClInclude Include="src\keymanagement.h" />
    1.94 +    <ClInclude Include="src\pEpEngine.h" />
    1.95 +    <ClInclude Include="src\platform_windows.h" />
    1.96 +    <ClInclude Include="src\sqlite3.h" />
    1.97 +  </ItemGroup>
    1.98 +  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
    1.99 +  <ImportGroup Label="ExtensionTargets">
   1.100 +  </ImportGroup>
   1.101 +</Project>
   1.102 \ No newline at end of file
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/pEpEngine.vcxproj.filters	Wed Jun 25 18:44:58 2014 +0200
     2.3 @@ -0,0 +1,45 @@
     2.4 +<?xml version="1.0" encoding="utf-8"?>
     2.5 +<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
     2.6 +  <ItemGroup>
     2.7 +    <Filter Include="Quelldateien">
     2.8 +      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
     2.9 +      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
    2.10 +    </Filter>
    2.11 +    <Filter Include="Headerdateien">
    2.12 +      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
    2.13 +      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
    2.14 +    </Filter>
    2.15 +    <Filter Include="Ressourcendateien">
    2.16 +      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
    2.17 +      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
    2.18 +    </Filter>
    2.19 +  </ItemGroup>
    2.20 +  <ItemGroup>
    2.21 +    <ClCompile Include="src\keymanagement.c">
    2.22 +      <Filter>Quelldateien</Filter>
    2.23 +    </ClCompile>
    2.24 +    <ClCompile Include="src\pEpEngine.c">
    2.25 +      <Filter>Quelldateien</Filter>
    2.26 +    </ClCompile>
    2.27 +    <ClCompile Include="src\platform_windows.cpp">
    2.28 +      <Filter>Quelldateien</Filter>
    2.29 +    </ClCompile>
    2.30 +    <ClCompile Include="src\sqlite3.c">
    2.31 +      <Filter>Quelldateien</Filter>
    2.32 +    </ClCompile>
    2.33 +  </ItemGroup>
    2.34 +  <ItemGroup>
    2.35 +    <ClInclude Include="src\keymanagement.h">
    2.36 +      <Filter>Headerdateien</Filter>
    2.37 +    </ClInclude>
    2.38 +    <ClInclude Include="src\pEpEngine.h">
    2.39 +      <Filter>Headerdateien</Filter>
    2.40 +    </ClInclude>
    2.41 +    <ClInclude Include="src\platform_windows.h">
    2.42 +      <Filter>Headerdateien</Filter>
    2.43 +    </ClInclude>
    2.44 +    <ClInclude Include="src\sqlite3.h">
    2.45 +      <Filter>Headerdateien</Filter>
    2.46 +    </ClInclude>
    2.47 +  </ItemGroup>
    2.48 +</Project>
    2.49 \ No newline at end of file
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/src/keymanagement.c	Wed Jun 25 18:44:58 2014 +0200
     3.3 @@ -0,0 +1,210 @@
     3.4 +#ifndef WIN32 // UNIX
     3.5 +#define _POSIX_C_SOURCE 200809L
     3.6 +#else
     3.7 +#include "platform_windows.h"
     3.8 +#endif
     3.9 +
    3.10 +#include <string.h>
    3.11 +#include <stdio.h>
    3.12 +#include <stdlib.h>
    3.13 +#include <assert.h>
    3.14 +
    3.15 +#define _EXPORT_PEP_ENGINE_DLL
    3.16 +#include "pEpEngine.h"
    3.17 +#include "keymanagement.h"
    3.18 +
    3.19 +#ifndef MIN
    3.20 +#define MIN(A, B) ((B) > (A) ? (A) : (B))
    3.21 +#endif
    3.22 +
    3.23 +DYNAMIC_API PEP_STATUS update_identity(
    3.24 +        PEP_SESSION session, pEp_identity * identity
    3.25 +    )
    3.26 +{
    3.27 +    pEp_identity *stored_identity;
    3.28 +    PEP_STATUS status;
    3.29 +    bool bDirty;
    3.30 +
    3.31 +    assert(session);
    3.32 +    assert(identity);
    3.33 +    assert(identity->address);
    3.34 +
    3.35 +    status = get_identity(session, identity->address, &stored_identity);
    3.36 +    assert(status != PEP_OUT_OF_MEMORY);
    3.37 +    if (status == PEP_OUT_OF_MEMORY)
    3.38 +        return PEP_OUT_OF_MEMORY;
    3.39 +
    3.40 +    if (stored_identity) {
    3.41 +        if (identity->username == NULL || identity->username[0] == 0) {
    3.42 +            free(identity->username);
    3.43 +            identity->username = strdup(stored_identity->username);
    3.44 +        }
    3.45 +        if (identity->user_id == NULL || identity->user_id[0] == 0) {
    3.46 +            free(identity->user_id);
    3.47 +            identity->user_id = strdup(stored_identity->user_id);
    3.48 +        }
    3.49 +        if (identity->fpr != NULL && identity->fpr[0] != 0) {
    3.50 +            if (strcmp(identity->fpr, stored_identity->fpr) != 0)
    3.51 +                identity->comm_type = PEP_ct_unknown;
    3.52 +        }
    3.53 +    }
    3.54 +    else
    3.55 +        identity->comm_type = PEP_ct_unknown;
    3.56 +
    3.57 +    status = set_identity(session, identity);
    3.58 +
    3.59 +    return PEP_STATUS_OK;
    3.60 +}
    3.61 +
    3.62 +DYNAMIC_API PEP_STATUS outgoing_comm_type(
    3.63 +        PEP_SESSION session,
    3.64 +        const stringlist_t *addresses,
    3.65 +        PEP_comm_type *comm_type
    3.66 +    )
    3.67 +{
    3.68 +    int i;
    3.69 +    const stringlist_t *l;
    3.70 +
    3.71 +    assert(session);
    3.72 +    assert(addresses);
    3.73 +    assert(addresses->value);
    3.74 +    assert(comm_type);
    3.75 +
    3.76 +    *comm_type = PEP_ct_unknown;
    3.77 +
    3.78 +    for (l=addresses; l && l->value; l = l->next) {
    3.79 +        PEP_STATUS _status;
    3.80 +        pEp_identity *identity;
    3.81 +
    3.82 +        _status = get_identity(session, l->value, &identity);
    3.83 +        assert(_status != PEP_OUT_OF_MEMORY);
    3.84 +
    3.85 +        if (identity == NULL) {
    3.86 +            *comm_type = PEP_ct_no_encryption;
    3.87 +            return PEP_STATUS_OK;
    3.88 +        }
    3.89 +        else if (identity->comm_type == PEP_ct_unknown) {
    3.90 +            *comm_type = PEP_ct_no_encryption;
    3.91 +            free_identity(identity);
    3.92 +            return PEP_STATUS_OK;
    3.93 +        }
    3.94 +        else if (*comm_type == PEP_ct_unknown) {
    3.95 +            *comm_type = identity->comm_type;
    3.96 +        }
    3.97 +        else if (*comm_type != identity->comm_type) {
    3.98 +            PEP_comm_type min = MIN(*comm_type, identity->comm_type);
    3.99 +            if (min < PEP_ct_unconfirmed_encryption) {
   3.100 +                *comm_type = PEP_ct_no_encryption;
   3.101 +                free_identity(identity);
   3.102 +                return PEP_STATUS_OK;
   3.103 +            }
   3.104 +            else if (min < PEP_ct_unconfirmed_enc_anon)
   3.105 +                *comm_type = PEP_ct_unconfirmed_encryption;
   3.106 +            else if (min < PEP_ct_confirmed_encryption)
   3.107 +                *comm_type = PEP_ct_unconfirmed_enc_anon;
   3.108 +            else if (min < PEP_ct_confirmed_enc_anon)
   3.109 +                *comm_type = PEP_ct_confirmed_encryption;
   3.110 +            else
   3.111 +                *comm_type = PEP_ct_confirmed_enc_anon;
   3.112 +        }
   3.113 +
   3.114 +        free_identity(identity);
   3.115 +    }
   3.116 +
   3.117 +    return PEP_STATUS_OK;
   3.118 +}
   3.119 +
   3.120 +DYNAMIC_API PEP_STATUS myself(PEP_SESSION session, pEp_identity * identity)
   3.121 +{
   3.122 +    PEP_STATUS status;
   3.123 +    stringlist_t *keylist;
   3.124 +
   3.125 +    assert(session);
   3.126 +    assert(identity);
   3.127 +    assert(identity->address);
   3.128 +    assert(identity->username);
   3.129 +    assert(identity->user_id);
   3.130 +
   3.131 +    identity->comm_type = PEP_ct_pEp;
   3.132 +    identity->me = true;
   3.133 +
   3.134 +    pEp_identity *_identity;
   3.135 +
   3.136 +    log_event(session, "myself", "debug", identity->address, NULL);
   3.137 +    status = get_identity(session, identity->address, &_identity);
   3.138 +    assert(status != PEP_OUT_OF_MEMORY);
   3.139 +    if (status == PEP_OUT_OF_MEMORY)
   3.140 +        return PEP_OUT_OF_MEMORY;
   3.141 +
   3.142 +    status = find_keys(session, identity->address, &keylist);
   3.143 +    assert(status != PEP_OUT_OF_MEMORY);
   3.144 +    if (status == PEP_OUT_OF_MEMORY)
   3.145 +        return PEP_OUT_OF_MEMORY;
   3.146 +
   3.147 +    if (keylist == NULL || keylist->value == NULL) {
   3.148 +        log_event(session, "generating key pair", "debug", identity->address, NULL);
   3.149 +        status = generate_keypair(session, identity);
   3.150 +        assert(status != PEP_OUT_OF_MEMORY);
   3.151 +        if (status != PEP_STATUS_OK) {
   3.152 +            char buf[11];
   3.153 +            snprintf(buf, 11, "%d", status);
   3.154 +            log_event(session, "generating key pair failed", "debug", buf, NULL);
   3.155 +            return status;
   3.156 +        }
   3.157 +
   3.158 +        status = find_keys(session, identity->address, &keylist);
   3.159 +        assert(status != PEP_OUT_OF_MEMORY);
   3.160 +        if (status == PEP_OUT_OF_MEMORY)
   3.161 +            return PEP_OUT_OF_MEMORY;
   3.162 +
   3.163 +        assert(keylist);
   3.164 +    }
   3.165 +
   3.166 +    if (identity->fpr)
   3.167 +        free(identity->fpr);
   3.168 +    identity->fpr = strdup(keylist->value);
   3.169 +    assert(identity->fpr);
   3.170 +    free_stringlist(keylist);
   3.171 +    if (identity->fpr == NULL)
   3.172 +        return PEP_OUT_OF_MEMORY;
   3.173 +
   3.174 +    status = set_identity(session, identity);
   3.175 +    assert(status == PEP_STATUS_OK);
   3.176 +
   3.177 +    return PEP_STATUS_OK;
   3.178 +}
   3.179 +
   3.180 +DYNAMIC_API PEP_STATUS do_keymanagement(
   3.181 +        retrieve_next_identity_t retrieve_next_identity,
   3.182 +        void *management
   3.183 +    )
   3.184 +{
   3.185 +    PEP_SESSION session;
   3.186 +    pEp_identity *identity;
   3.187 +    PEP_STATUS status = init(&session);
   3.188 +
   3.189 +    assert(status == PEP_STATUS_OK);
   3.190 +    if (status != PEP_STATUS_OK)
   3.191 +        return status;
   3.192 +
   3.193 +    log_event(session, "keymanagement thread started", "pEp engine", NULL, NULL);
   3.194 +
   3.195 +    while (identity = retrieve_next_identity(management)) {
   3.196 +        assert(identity->address);
   3.197 +        log_event(session, "do_keymanagement", "debug", identity->address, NULL);
   3.198 +        if (identity->me) {
   3.199 +            status = myself(session, identity);
   3.200 +            assert(status != PEP_OUT_OF_MEMORY);
   3.201 +        } else {
   3.202 +            status = recv_key(session, identity->address);
   3.203 +            assert(status != PEP_OUT_OF_MEMORY);
   3.204 +        }
   3.205 +        free_identity(identity);
   3.206 +    }
   3.207 +
   3.208 +    log_event(session, "keymanagement thread shutdown", "pEp engine", NULL, NULL);
   3.209 +
   3.210 +    release(session);
   3.211 +    return PEP_STATUS_OK;
   3.212 +}
   3.213 +
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/src/keymanagement.h	Wed Jun 25 18:44:58 2014 +0200
     4.3 @@ -0,0 +1,103 @@
     4.4 +#ifdef __cplusplus
     4.5 +extern "C" {
     4.6 +#endif
     4.7 +
     4.8 +// update_identity() - update identity information
     4.9 +//
    4.10 +//  parameters:
    4.11 +//      session (in)        session to use
    4.12 +//      identity (inout)    identity information of communication partner
    4.13 +//
    4.14 +//  caveat:
    4.15 +//      if this function returns PEP_ct_unknown in identity->comm_type, the
    4.16 +//      caller must insert the identity into the asynchronous management
    4.17 +//      implementation, so retrieve_next_identity() will return this identity
    4.18 +//      later
    4.19 +//      at least identity->address must be a valid C string as input
    4.20 +
    4.21 +DYNAMIC_API PEP_STATUS update_identity(
    4.22 +        PEP_SESSION session, pEp_identity * identity
    4.23 +    );
    4.24 +
    4.25 +
    4.26 +// outgoing_comm_type() - minimum comm_type for a list of addresses
    4.27 +//
    4.28 +//  parameters:
    4.29 +//      session (in)        session to use
    4.30 +//      addresses (in)      list of addresses
    4.31 +//      comm_type (out)     comm_type which can be used to communicate with
    4.32 +//                          addresses
    4.33 +
    4.34 +DYNAMIC_API PEP_STATUS outgoing_comm_type(
    4.35 +        PEP_SESSION session,
    4.36 +        const stringlist_t *addresses,
    4.37 +        PEP_comm_type *comm_type
    4.38 +    );
    4.39 +
    4.40 +
    4.41 +// myself() - ensures that the own identity is being complete
    4.42 +//
    4.43 +//  parameters:
    4.44 +//      session (in)        session to use
    4.45 +//      identity (inout)    identity of local user
    4.46 +//                          at least .address, .username, .user_id must be set
    4.47 +//
    4.48 +//  return value:
    4.49 +//      PEP_STATUS_OK if identity could be completed or was already complete,
    4.50 +//      any other value on error
    4.51 +//
    4.52 +//  caveat:
    4.53 +//      this function generates a keypair on demand; because it's synchronous
    4.54 +//      it can need a decent amount of time to return
    4.55 +//      if you need to do this asynchronous, you need to return an identity
    4.56 +//      with retrieve_next_identity() where pEp_identity.me is true
    4.57 +
    4.58 +DYNAMIC_API PEP_STATUS myself(PEP_SESSION session, pEp_identity * identity);
    4.59 +
    4.60 +
    4.61 +// retrieve_next_identity() - callback being called by do_keymanagement()
    4.62 +//
    4.63 +//  parameters:
    4.64 +//      management (in)     data structure to deliver (implementation defined)
    4.65 +//
    4.66 +//  return value:
    4.67 +//      identity to check or NULL to terminate do_keymanagement()
    4.68 +//      if given identity must be created with new_identity()
    4.69 +//      the identity struct is going to the ownership of this library
    4.70 +//      it must not be freed by the callee
    4.71 +//
    4.72 +//  caveat:
    4.73 +//      this callback has to block until an identity or NULL can be returned
    4.74 +//      an implementation is not provided by this library; instead it has to be
    4.75 +//      implemented by the user of this library
    4.76 +
    4.77 +typedef pEp_identity *(*retrieve_next_identity_t)(void *management);
    4.78 +
    4.79 +
    4.80 +// do_keymanagement() - function to be run on an extra thread
    4.81 +//
    4.82 +//  parameters:
    4.83 +//      retrieve_next_identity  pointer to retrieve_next_identity() callback
    4.84 +//                              which returns at least a valid address field in
    4.85 +//                              the identity struct
    4.86 +//      management              management data to give to keymanagement
    4.87 +//                              (implementation defined)
    4.88 +//
    4.89 +//  return value:
    4.90 +//      PEP_STATUS_OK if thread has to terminate successfully or any other
    4.91 +//      value on failure
    4.92 +//
    4.93 +//  caveat:
    4.94 +//      to ensure proper working of this library, a thread has to be started
    4.95 +//      with this function immediately after initialization
    4.96 +//      do_keymanagement() calls retrieve_next_identity(management)
    4.97 +
    4.98 +DYNAMIC_API PEP_STATUS do_keymanagement(
    4.99 +        retrieve_next_identity_t retrieve_next_identity,
   4.100 +        void *management
   4.101 +    );
   4.102 +
   4.103 +#ifdef __cplusplus
   4.104 +}
   4.105 +#endif
   4.106 +
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/src/pEpEngine.c	Wed Jun 25 18:44:58 2014 +0200
     5.3 @@ -0,0 +1,1869 @@
     5.4 +#define PEP_ENGINE_VERSION "0.4.0"
     5.5 +
     5.6 +// this is 20 safewords with 79 chars max
     5.7 +#define MAX_SAFEWORDS_SPACE (20 * 80)
     5.8 +
     5.9 +// XML parameters string
    5.10 +#define PARMS_MAX 32768
    5.11 +
    5.12 +// maximum busy wait time in ms
    5.13 +#define BUSY_WAIT_TIME 5000
    5.14 +
    5.15 +// maximum line length for reading gpg.conf
    5.16 +#define MAX_LINELENGTH 1024
    5.17 +
    5.18 +// default keyserver
    5.19 +#define DEFAULT_KEYSERVER "hkp://keys.gnupg.net"
    5.20 +
    5.21 +#ifdef WIN32
    5.22 +#include "platform_windows.h"
    5.23 +#define LOCAL_DB windoze_local_db()
    5.24 +#define SYSTEM_DB windoze_system_db()
    5.25 +#define LIBGPGME "libgpgme-11.dll"
    5.26 +#else // UNIX
    5.27 +#define _POSIX_C_SOURCE 200809L
    5.28 +#include <dlfcn.h>
    5.29 +#include "platform_unix.h"
    5.30 +#define LOCAL_DB unix_local_db()
    5.31 +#ifndef SYSTEM_DB
    5.32 +#define SYSTEM_DB "/usr/share/pEp/system.db"
    5.33 +#endif
    5.34 +#ifndef LIBGPGME
    5.35 +#define LIBGPGME "libgpgme-pthread.so"
    5.36 +#endif
    5.37 +#endif
    5.38 +
    5.39 +#include <locale.h>
    5.40 +#include <stdlib.h>
    5.41 +#include <string.h>
    5.42 +#include <assert.h>
    5.43 +#include <stdio.h>
    5.44 +
    5.45 +#ifndef NDEBUG
    5.46 +#include <stdio.h>
    5.47 +#endif
    5.48 +
    5.49 +#include <gpgme.h>
    5.50 +#include "sqlite3.h"
    5.51 +
    5.52 +#define _EXPORT_PEP_ENGINE_DLL
    5.53 +#include "pEpEngine.h"
    5.54 +
    5.55 +#define NOT_IMPLEMENTED assert(0)
    5.56 +
    5.57 +// init
    5.58 +
    5.59 +typedef const char * (*gpgme_check_version_t)(const char*);
    5.60 +typedef gpgme_error_t (*gpgme_set_locale_t)(gpgme_ctx_t CTX, int CATEGORY,
    5.61 +        const char *VALUE);
    5.62 +typedef gpgme_error_t (*gpgme_new_t)(gpgme_ctx_t *CTX);
    5.63 +typedef void (*gpgme_release_t)(gpgme_ctx_t CTX);
    5.64 +typedef gpgme_error_t (*gpgme_set_protocol_t)(gpgme_ctx_t CTX,
    5.65 +        gpgme_protocol_t PROTO);
    5.66 +typedef void (*gpgme_set_armor_t)(gpgme_ctx_t CTX, int YES);
    5.67 +
    5.68 +// data
    5.69 +
    5.70 +typedef gpgme_error_t (*gpgme_data_new_t)(gpgme_data_t *DH);
    5.71 +typedef gpgme_error_t (*gpgme_data_new_from_mem_t)(gpgme_data_t *DH,
    5.72 +        const char *BUFFER, size_t SIZE, int COPY);
    5.73 +typedef void (*gpgme_data_release_t)(gpgme_data_t DH);
    5.74 +typedef gpgme_data_type_t (*gpgme_data_identify_t)(gpgme_data_t DH);
    5.75 +typedef size_t (*gpgme_data_seek_t)(gpgme_data_t DH, size_t OFFSET,
    5.76 +        int WHENCE);
    5.77 +typedef size_t (*gpgme_data_read_t)(gpgme_data_t DH, void *BUFFER,
    5.78 +        size_t LENGTH);
    5.79 +
    5.80 +// encrypt and decrypt
    5.81 +
    5.82 +typedef gpgme_error_t (*gpgme_op_decrypt_t)(gpgme_ctx_t CTX,
    5.83 +        gpgme_data_t CIPHER, gpgme_data_t PLAIN);
    5.84 +typedef gpgme_error_t (*gpgme_op_verify_t)(gpgme_ctx_t CTX, gpgme_data_t SIG,
    5.85 +        gpgme_data_t SIGNED_TEXT, gpgme_data_t PLAIN);
    5.86 +typedef gpgme_error_t (*gpgme_op_decrypt_verify_t)(gpgme_ctx_t CTX,
    5.87 +        gpgme_data_t CIPHER, gpgme_data_t PLAIN);
    5.88 +typedef gpgme_decrypt_result_t (*gpgme_op_decrypt_result_t)(gpgme_ctx_t CTX);
    5.89 +typedef gpgme_error_t (*gpgme_op_encrypt_sign_t)(gpgme_ctx_t CTX,
    5.90 +        gpgme_key_t RECP[], gpgme_encrypt_flags_t FLAGS, gpgme_data_t PLAIN,
    5.91 +        gpgme_data_t CIPHER);
    5.92 +typedef gpgme_verify_result_t (*gpgme_op_verify_result_t)(gpgme_ctx_t CTX);
    5.93 +
    5.94 +// keys
    5.95 +
    5.96 +typedef gpgme_error_t (*gpgme_get_key_t)(gpgme_ctx_t CTX, const char *FPR,
    5.97 +        gpgme_key_t *R_KEY, int SECRET);
    5.98 +typedef gpgme_error_t (*gpgme_op_genkey_t)(gpgme_ctx_t CTX, const char *PARMS,
    5.99 +        gpgme_data_t PUBLIC, gpgme_data_t SECRET);
   5.100 +typedef gpgme_genkey_result_t (*gpgme_op_genkey_result_t)(gpgme_ctx_t CTX);
   5.101 +typedef gpgme_error_t (*gpgme_op_delete_t)(gpgme_ctx_t CTX,
   5.102 +        const gpgme_key_t KEY, int ALLOW_SECRET);
   5.103 +typedef gpgme_error_t (*gpgme_op_import_t)(gpgme_ctx_t CTX,
   5.104 +        gpgme_data_t KEYDATA);
   5.105 +typedef gpgme_error_t (*gpgme_op_export_t)(gpgme_ctx_t CTX,
   5.106 +        const char *PATTERN, gpgme_export_mode_t MODE, gpgme_data_t KEYDATA);
   5.107 +typedef gpgme_error_t (*gpgme_set_keylist_mode_t)(gpgme_ctx_t CTX,
   5.108 +        gpgme_keylist_mode_t MODE);
   5.109 +typedef gpgme_keylist_mode_t (*gpgme_get_keylist_mode_t)(gpgme_ctx_t CTX);
   5.110 +typedef gpgme_error_t (*gpgme_op_keylist_start_t)(gpgme_ctx_t CTX,
   5.111 +        const char *PATTERN, int SECRET_ONLY);
   5.112 +typedef gpgme_error_t (*gpgme_op_keylist_next_t)(gpgme_ctx_t CTX,
   5.113 +        gpgme_key_t *R_KEY);
   5.114 +typedef gpgme_error_t (*gpgme_op_keylist_end_t)(gpgme_ctx_t CTX);
   5.115 +typedef gpgme_error_t (*gpgme_op_import_keys_t)(gpgme_ctx_t CTX,
   5.116 +        gpgme_key_t *KEYS);
   5.117 +typedef void (*gpgme_key_ref_t)(gpgme_key_t KEY);
   5.118 +typedef void (*gpgme_key_unref_t)(gpgme_key_t KEY);
   5.119 +
   5.120 +typedef struct {
   5.121 +	const char *version;
   5.122 +    const char *passphrase;
   5.123 +	void * gpgme;
   5.124 +	gpgme_ctx_t ctx;
   5.125 +
   5.126 +	sqlite3 *db;
   5.127 +	sqlite3 *system_db;
   5.128 +
   5.129 +	sqlite3_stmt *log;
   5.130 +	sqlite3_stmt *safeword;
   5.131 +	sqlite3_stmt *get_identity;
   5.132 +	sqlite3_stmt *set_person;
   5.133 +	sqlite3_stmt *set_pgp_keypair;
   5.134 +	sqlite3_stmt *set_identity;
   5.135 +	sqlite3_stmt *set_trust;
   5.136 +
   5.137 +	gpgme_check_version_t gpgme_check;
   5.138 +	gpgme_set_locale_t gpgme_set_locale;
   5.139 +	gpgme_new_t gpgme_new;
   5.140 +	gpgme_release_t gpgme_release;
   5.141 +	gpgme_set_protocol_t gpgme_set_protocol;
   5.142 +	gpgme_set_armor_t gpgme_set_armor;
   5.143 +
   5.144 +	gpgme_data_new_t gpgme_data_new;
   5.145 +	gpgme_data_new_from_mem_t gpgme_data_new_from_mem;
   5.146 +	gpgme_data_release_t gpgme_data_release;
   5.147 +	gpgme_data_identify_t gpgme_data_identify;
   5.148 +	gpgme_data_seek_t gpgme_data_seek;
   5.149 +	gpgme_data_read_t gpgme_data_read;
   5.150 +
   5.151 +	gpgme_op_decrypt_t gpgme_op_decrypt;
   5.152 +	gpgme_op_verify_t gpgme_op_verify;
   5.153 +	gpgme_op_decrypt_verify_t gpgme_op_decrypt_verify;
   5.154 +	gpgme_op_decrypt_result_t gpgme_op_decrypt_result;
   5.155 +	gpgme_op_encrypt_sign_t gpgme_op_encrypt_sign;
   5.156 +	gpgme_op_verify_result_t gpgme_op_verify_result;
   5.157 +
   5.158 +	gpgme_get_key_t gpgme_get_key;
   5.159 +	gpgme_op_genkey_t gpgme_op_genkey;
   5.160 +    gpgme_op_genkey_result_t gpgme_op_genkey_result;
   5.161 +    gpgme_op_delete_t gpgme_op_delete;
   5.162 +    gpgme_op_import_t gpgme_op_import;
   5.163 +    gpgme_op_export_t gpgme_op_export;
   5.164 +    gpgme_set_keylist_mode_t gpgme_set_keylist_mode;
   5.165 +    gpgme_get_keylist_mode_t gpgme_get_keylist_mode;
   5.166 +    gpgme_op_keylist_start_t gpgme_op_keylist_start;
   5.167 +    gpgme_op_keylist_next_t gpgme_op_keylist_next;
   5.168 +    gpgme_op_keylist_end_t gpgme_op_keylist_end;
   5.169 +    gpgme_op_import_keys_t gpgme_op_import_keys;
   5.170 +    gpgme_key_ref_t gpgme_key_ref;
   5.171 +    gpgme_key_unref_t gpgme_key_unref;
   5.172 +} pEpSession;
   5.173 +
   5.174 +static bool ensure_keyserver()
   5.175 +{
   5.176 +    static char buf[MAX_LINELENGTH];
   5.177 +    int n;
   5.178 +    FILE *f = fopen(gpg_conf(), "r");
   5.179 +
   5.180 +    if (f != NULL) {
   5.181 +        while (!feof(f)) {
   5.182 +            char * s = fgets(buf, MAX_LINELENGTH, f);
   5.183 +            if (s && !feof(f)) {
   5.184 +                char * t = strtok(s, " ");
   5.185 +                if (t && strcmp(t, "keyserver") == 0)
   5.186 +                {
   5.187 +                    fclose(f);
   5.188 +                    return true;
   5.189 +                }
   5.190 +            }
   5.191 +        }
   5.192 +        f = freopen(gpg_conf(), "a", f);
   5.193 +    }
   5.194 +    else {
   5.195 +        f = fopen(gpg_conf(), "w");
   5.196 +    }
   5.197 +
   5.198 +    assert(f);
   5.199 +    if (f == NULL)
   5.200 +        return false;
   5.201 +
   5.202 +    n = fprintf(f, "keyserver %s\n", DEFAULT_KEYSERVER);
   5.203 +    assert(n >= 0);
   5.204 +    fclose(f);
   5.205 +
   5.206 +    return true;
   5.207 +}
   5.208 +
   5.209 +DYNAMIC_API PEP_STATUS init(PEP_SESSION *session)
   5.210 +{
   5.211 +	gpgme_error_t gpgme_error;
   5.212 +	int int_result;
   5.213 +	const char *sql_log;
   5.214 +	const char *sql_safeword;
   5.215 +	const char *sql_get_identity;
   5.216 +	const char *sql_set_person;
   5.217 +	const char *sql_set_pgp_keypair;
   5.218 +	const char *sql_set_identity;
   5.219 +	const char *sql_set_trust;
   5.220 +    bool bResult;
   5.221 +
   5.222 +	assert(sqlite3_threadsafe());
   5.223 +	if (!sqlite3_threadsafe())
   5.224 +		return PEP_INIT_SQLITE3_WITHOUT_MUTEX;
   5.225 +
   5.226 +	assert(session);
   5.227 +	*session = NULL;
   5.228 +
   5.229 +    pEpSession *_session = (pEpSession *) calloc(1, sizeof(pEpSession));
   5.230 +	assert(_session);
   5.231 +	if (_session == NULL)
   5.232 +		return PEP_OUT_OF_MEMORY;
   5.233 +	
   5.234 +	_session->version = PEP_ENGINE_VERSION;
   5.235 +
   5.236 +    bResult = ensure_keyserver();
   5.237 +    assert(bResult);
   5.238 +
   5.239 +    // to do: implement something useful
   5.240 +    _session->passphrase = "";
   5.241 +
   5.242 +	_session->gpgme = dlopen(LIBGPGME, RTLD_LAZY);
   5.243 +	if (_session->gpgme == NULL) {
   5.244 +		free(_session);
   5.245 +		return PEP_INIT_CANNOT_LOAD_GPGME;
   5.246 +	}
   5.247 +
   5.248 +	_session->gpgme_set_locale
   5.249 +        = (gpgme_set_locale_t) (intptr_t) dlsym(_session->gpgme,
   5.250 +                "gpgme_set_locale");
   5.251 +	assert(_session->gpgme_set_locale);
   5.252 +
   5.253 +	_session->gpgme_check
   5.254 +        = (gpgme_check_version_t) (intptr_t) dlsym(_session->gpgme,
   5.255 +                "gpgme_check_version");
   5.256 +	assert(_session->gpgme_check);
   5.257 +
   5.258 +	_session->gpgme_new
   5.259 +        = (gpgme_new_t) (intptr_t) dlsym(_session->gpgme, "gpgme_new");
   5.260 +	assert(_session->gpgme_new);
   5.261 +
   5.262 +	_session->gpgme_release
   5.263 +        = (gpgme_release_t) (intptr_t) dlsym(_session->gpgme, "gpgme_release");
   5.264 +	assert(_session->gpgme_release);
   5.265 +
   5.266 +	_session->gpgme_set_protocol
   5.267 +        = (gpgme_set_protocol_t) (intptr_t) dlsym(_session->gpgme,
   5.268 +                "gpgme_set_protocol");
   5.269 +	assert(_session->gpgme_set_protocol);
   5.270 +
   5.271 +	_session->gpgme_set_armor
   5.272 +        = (gpgme_set_armor_t) (intptr_t) dlsym(_session->gpgme,
   5.273 +                "gpgme_set_armor");
   5.274 +	assert(_session->gpgme_set_armor);
   5.275 +
   5.276 +	_session->gpgme_data_new
   5.277 +        = (gpgme_data_new_t) (intptr_t) dlsym(_session->gpgme,
   5.278 +                "gpgme_data_new");
   5.279 +	assert(_session->gpgme_data_new);
   5.280 +
   5.281 +	_session->gpgme_data_new_from_mem
   5.282 +        = (gpgme_data_new_from_mem_t) (intptr_t) dlsym(_session->gpgme,
   5.283 +                "gpgme_data_new_from_mem");
   5.284 +	assert(_session->gpgme_data_new_from_mem);
   5.285 +
   5.286 +	_session->gpgme_data_release
   5.287 +        = (gpgme_data_release_t) (intptr_t) dlsym(_session->gpgme,
   5.288 +                "gpgme_data_release");
   5.289 +	assert(_session->gpgme_data_release);
   5.290 +
   5.291 +	_session->gpgme_data_identify
   5.292 +        = (gpgme_data_identify_t) (intptr_t) dlsym(_session->gpgme,
   5.293 +                "gpgme_data_identify");
   5.294 +	assert(_session->gpgme_data_identify);
   5.295 +
   5.296 +	_session->gpgme_data_seek
   5.297 +        = (gpgme_data_seek_t) (intptr_t) dlsym(_session->gpgme,
   5.298 +                "gpgme_data_seek");
   5.299 +	assert(_session->gpgme_data_seek);
   5.300 +
   5.301 +	_session->gpgme_data_read
   5.302 +        = (gpgme_data_read_t) (intptr_t) dlsym(_session->gpgme,
   5.303 +                "gpgme_data_read");
   5.304 +	assert(_session->gpgme_data_read);
   5.305 +
   5.306 +	_session->gpgme_op_decrypt
   5.307 +        = (gpgme_op_decrypt_t) (intptr_t) dlsym(_session->gpgme,
   5.308 +                "gpgme_op_decrypt");
   5.309 +	assert(_session->gpgme_op_decrypt);
   5.310 +
   5.311 +	_session->gpgme_op_verify
   5.312 +        = (gpgme_op_verify_t) (intptr_t) dlsym(_session->gpgme,
   5.313 +                "gpgme_op_verify");
   5.314 +	assert(_session->gpgme_op_verify);
   5.315 +
   5.316 +	_session->gpgme_op_decrypt_verify
   5.317 +        = (gpgme_op_decrypt_verify_t) (intptr_t) dlsym(_session->gpgme,
   5.318 +                "gpgme_op_decrypt_verify");
   5.319 +	assert(_session->gpgme_op_decrypt_verify);
   5.320 +
   5.321 +	_session->gpgme_op_decrypt_result
   5.322 +        = (gpgme_op_decrypt_result_t) (intptr_t) dlsym(_session->gpgme,
   5.323 +                "gpgme_op_decrypt_result");
   5.324 +	assert(_session->gpgme_op_decrypt_result);
   5.325 +
   5.326 +	_session->gpgme_op_encrypt_sign
   5.327 +        = (gpgme_op_encrypt_sign_t) (intptr_t) dlsym(_session->gpgme,
   5.328 +                "gpgme_op_encrypt_sign");
   5.329 +	assert(_session->gpgme_op_encrypt_sign);
   5.330 +
   5.331 +	_session->gpgme_op_verify_result
   5.332 +        = (gpgme_op_verify_result_t) (intptr_t) dlsym(_session->gpgme,
   5.333 +                "gpgme_op_verify_result");
   5.334 +	assert(_session->gpgme_op_verify_result);
   5.335 +	
   5.336 +	_session->gpgme_get_key
   5.337 +        = (gpgme_get_key_t) (intptr_t) dlsym(_session->gpgme, "gpgme_get_key");
   5.338 +	assert(_session->gpgme_get_key);
   5.339 +
   5.340 +	_session->gpgme_op_genkey
   5.341 +        = (gpgme_op_genkey_t) (intptr_t) dlsym(_session->gpgme,
   5.342 +                "gpgme_op_genkey");
   5.343 +	assert(_session->gpgme_op_genkey);
   5.344 +
   5.345 +	_session->gpgme_op_genkey_result
   5.346 +        = (gpgme_op_genkey_result_t) (intptr_t) dlsym(_session->gpgme,
   5.347 +                "gpgme_op_genkey_result");
   5.348 +	assert(_session->gpgme_op_genkey_result);
   5.349 +
   5.350 +    _session->gpgme_op_delete = (gpgme_op_delete_t) (intptr_t)
   5.351 +        dlsym(_session->gpgme, "gpgme_op_delete");
   5.352 +	assert(_session->gpgme_op_delete);
   5.353 +
   5.354 +    _session->gpgme_op_import = (gpgme_op_import_t) (intptr_t)
   5.355 +        dlsym(_session->gpgme, "gpgme_op_import");
   5.356 +	assert(_session->gpgme_op_import);
   5.357 +
   5.358 +    _session->gpgme_op_export = (gpgme_op_export_t) (intptr_t)
   5.359 +        dlsym(_session->gpgme, "gpgme_op_export");
   5.360 +	assert(_session->gpgme_op_export);
   5.361 +
   5.362 +    _session->gpgme_set_keylist_mode = (gpgme_set_keylist_mode_t) (intptr_t)
   5.363 +        dlsym(_session->gpgme, "gpgme_set_keylist_mode");
   5.364 +	assert(_session->gpgme_set_keylist_mode);
   5.365 +
   5.366 +    _session->gpgme_get_keylist_mode = (gpgme_get_keylist_mode_t) (intptr_t)
   5.367 +        dlsym(_session->gpgme, "gpgme_get_keylist_mode");
   5.368 +	assert(_session->gpgme_get_keylist_mode);
   5.369 +
   5.370 +    _session->gpgme_op_keylist_start = (gpgme_op_keylist_start_t) (intptr_t)
   5.371 +        dlsym(_session->gpgme, "gpgme_op_keylist_start");
   5.372 +	assert(_session->gpgme_op_keylist_start);
   5.373 +
   5.374 +    _session->gpgme_op_keylist_next = (gpgme_op_keylist_next_t) (intptr_t)
   5.375 +        dlsym(_session->gpgme, "gpgme_op_keylist_next");
   5.376 +	assert(_session->gpgme_op_keylist_next);
   5.377 +
   5.378 +    _session->gpgme_op_keylist_end = (gpgme_op_keylist_end_t) (intptr_t)
   5.379 +        dlsym(_session->gpgme, "gpgme_op_keylist_end");
   5.380 +	assert(_session->gpgme_op_keylist_end);
   5.381 +
   5.382 +    _session->gpgme_op_import_keys = (gpgme_op_import_keys_t) (intptr_t)
   5.383 +        dlsym(_session->gpgme, "gpgme_op_import_keys");
   5.384 +	assert(_session->gpgme_op_import_keys);
   5.385 +
   5.386 +    _session->gpgme_key_ref = (gpgme_key_ref_t) (intptr_t)
   5.387 +        dlsym(_session->gpgme, "gpgme_key_ref");
   5.388 +	assert(_session->gpgme_key_ref);
   5.389 +
   5.390 +    _session->gpgme_key_unref = (gpgme_key_unref_t) (intptr_t)
   5.391 +        dlsym(_session->gpgme, "gpgme_key_unref");
   5.392 +	assert(_session->gpgme_key_unref);
   5.393 +
   5.394 +	setlocale(LC_ALL, "");
   5.395 +	_session->version = _session->gpgme_check(NULL);
   5.396 +	_session->gpgme_set_locale(NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
   5.397 +
   5.398 +	gpgme_error = _session->gpgme_new(&_session->ctx);
   5.399 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
   5.400 +		dlclose(_session->gpgme);
   5.401 +		free(_session);
   5.402 +		return PEP_INIT_GPGME_INIT_FAILED;
   5.403 +	}
   5.404 +
   5.405 +    gpgme_error = _session->gpgme_set_protocol(_session->ctx,
   5.406 +            GPGME_PROTOCOL_OpenPGP);
   5.407 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
   5.408 +
   5.409 +	_session->gpgme_set_armor(_session->ctx, 1);
   5.410 +
   5.411 +    assert(LOCAL_DB);
   5.412 +    if (LOCAL_DB == NULL) {
   5.413 +		_session->gpgme_release(_session->ctx);
   5.414 +		dlclose(_session->gpgme);
   5.415 +        free(_session);
   5.416 +        return PEP_INIT_CANNOT_OPEN_DB;
   5.417 +    }
   5.418 +
   5.419 +	int_result = sqlite3_open_v2(
   5.420 +			LOCAL_DB,
   5.421 +			&_session->db,
   5.422 +			SQLITE_OPEN_READWRITE
   5.423 +				| SQLITE_OPEN_CREATE
   5.424 +				| SQLITE_OPEN_FULLMUTEX
   5.425 +				| SQLITE_OPEN_PRIVATECACHE,
   5.426 +			NULL 
   5.427 +		);
   5.428 +
   5.429 +	if (int_result != SQLITE_OK) {
   5.430 +		sqlite3_close_v2(_session->db);
   5.431 +		_session->gpgme_release(_session->ctx);
   5.432 +		dlclose(_session->gpgme);
   5.433 +		free(_session);
   5.434 +		return PEP_INIT_CANNOT_OPEN_DB;
   5.435 +	}
   5.436 +
   5.437 +	sqlite3_busy_timeout(_session->db, BUSY_WAIT_TIME);
   5.438 +
   5.439 +    assert(SYSTEM_DB);
   5.440 +    if (SYSTEM_DB == NULL) {
   5.441 +		sqlite3_close_v2(_session->db);
   5.442 +		_session->gpgme_release(_session->ctx);
   5.443 +		dlclose(_session->gpgme);
   5.444 +		free(_session);
   5.445 +		return PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   5.446 +    }
   5.447 +
   5.448 +	int_result = sqlite3_open_v2(
   5.449 +			SYSTEM_DB, &_session->system_db,
   5.450 +			SQLITE_OPEN_READONLY
   5.451 +				| SQLITE_OPEN_FULLMUTEX
   5.452 +				| SQLITE_OPEN_SHAREDCACHE,
   5.453 +			NULL
   5.454 +		);
   5.455 +
   5.456 +	if (int_result != SQLITE_OK) {
   5.457 +		sqlite3_close_v2(_session->system_db);
   5.458 +		sqlite3_close_v2(_session->db);
   5.459 +		_session->gpgme_release(_session->ctx);
   5.460 +		dlclose(_session->gpgme);
   5.461 +		free(_session);
   5.462 +		return PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   5.463 +	}
   5.464 +
   5.465 +	sqlite3_busy_timeout(_session->system_db, 1000);
   5.466 +
   5.467 +	int_result = sqlite3_exec(
   5.468 +		_session->db,
   5.469 +			"create table if not exists version_info ("
   5.470 +			"	id integer primary key,"
   5.471 +			"	timestamp integer default (datetime('now')) ,"
   5.472 +			"	version text,"
   5.473 +			"	comment text"
   5.474 +			");"
   5.475 +			"create table if not exists log ("
   5.476 +			"	timestamp integer default (datetime('now')) ,"
   5.477 +			"	title text not null,"
   5.478 +			"	entity text not null,"
   5.479 +			"	description text,"
   5.480 +			"	comment text"
   5.481 +			");"
   5.482 +			"create index if not exists log_timestamp on log ("
   5.483 +			"	timestamp"
   5.484 +			");"
   5.485 +			"create table if not exists pgp_keypair ("
   5.486 +			"	fpr text primary key,"
   5.487 +			"	public_id text unique,"
   5.488 +			"   private_id text,"
   5.489 +			"	created integer,"
   5.490 +			"	expires integer,"
   5.491 +			"	comment text"
   5.492 +			");"
   5.493 +            "create index if not exists pgp_keypair_expires on pgp_keypair ("
   5.494 +			"	expires"
   5.495 +			");"
   5.496 +			"create table if not exists person ("
   5.497 +			"	id text primary key,"
   5.498 +			"	username text not null,"
   5.499 +			"	main_key_id text"
   5.500 +			"		references pgp_keypair (fpr)"
   5.501 +			"		on delete set null,"
   5.502 +			"   lang text,"
   5.503 +			"	comment text"
   5.504 +			");"
   5.505 +			"create table if not exists identity ("
   5.506 +			"	address text primary key,"
   5.507 +			"	user_id text"
   5.508 +			"		references person (id)"
   5.509 +			"		on delete cascade,"
   5.510 +			"	main_key_id text"
   5.511 +			"		references pgp_keypair (fpr)"
   5.512 +			"		on delete set null,"
   5.513 +			"	comment text"
   5.514 +			");"
   5.515 +            "create table if not exists trust ("
   5.516 +            "   user_id text not null"
   5.517 +            "       references person (id)"
   5.518 +			"		on delete cascade,"
   5.519 +            "   pgp_keypair_fpr text not null"
   5.520 +            "       references pgp_keypair (fpr)"
   5.521 +            "       on delete cascade,"
   5.522 +            "   comm_type integer not null,"
   5.523 +			"	comment text"
   5.524 +            ");"
   5.525 +            "create unique index if not exists trust_index on trust ("
   5.526 +            "   user_id,"
   5.527 +            "   pgp_keypair_fpr"
   5.528 +            ");",
   5.529 +		NULL,
   5.530 +		NULL,
   5.531 +		NULL
   5.532 +	);
   5.533 +	assert(int_result == SQLITE_OK);
   5.534 +
   5.535 +	int_result = sqlite3_exec(
   5.536 +		_session->db,
   5.537 +        "insert or replace into version_info (id, version) values (1, '1.0');",
   5.538 +		NULL,
   5.539 +		NULL,
   5.540 +		NULL
   5.541 +	);
   5.542 +	assert(int_result == SQLITE_OK);
   5.543 +
   5.544 +	sql_log = "insert into log (title, entity, description, comment)"
   5.545 +			  "values (?1, ?2, ?3, ?4);";
   5.546 +    int_result = sqlite3_prepare_v2(_session->db, sql_log, strlen(sql_log),
   5.547 +            &_session->log, NULL);
   5.548 +	assert(int_result == SQLITE_OK);
   5.549 +
   5.550 +	sql_safeword = "select id, word from wordlist where lang = lower(?1)"
   5.551 +                   "and id = ?2 ;";
   5.552 +    int_result = sqlite3_prepare_v2(_session->system_db, sql_safeword,
   5.553 +            strlen(sql_safeword), &_session->safeword, NULL);
   5.554 +	assert(int_result == SQLITE_OK);
   5.555 +
   5.556 +	sql_get_identity =	"select fpr, identity.user_id, username, comm_type, lang"
   5.557 +                        "   from identity"
   5.558 +						"   join person on id = identity.user_id"
   5.559 +						"   join pgp_keypair on fpr = identity.main_key_id"
   5.560 +                        "   join trust on id = trust.user_id"
   5.561 +                        "       and pgp_keypair_fpr = identity.main_key_id"
   5.562 +						"   where address = ?1 ;";
   5.563 +
   5.564 +    int_result = sqlite3_prepare_v2(_session->db, sql_get_identity,
   5.565 +            strlen(sql_get_identity), &_session->get_identity, NULL);
   5.566 +	assert(int_result == SQLITE_OK);
   5.567 +
   5.568 +	sql_set_person = "insert or replace into person (id, username, lang)"
   5.569 +                     "values (?1, ?2, ?3) ;";
   5.570 +	sql_set_pgp_keypair = "insert or replace into pgp_keypair (fpr)"
   5.571 +                          "values (?1) ;";
   5.572 +    sql_set_identity = "insert or replace into identity (address, main_key_id,"
   5.573 +                       "user_id) values (?1, ?2, ?3) ;";
   5.574 +    sql_set_trust = "insert or replace into trust (user_id, pgp_keypair_fpr, comm_type)"
   5.575 +                        "values (?1, ?2, ?3) ;";
   5.576 +	
   5.577 +    int_result = sqlite3_prepare_v2(_session->db, sql_set_person,
   5.578 +            strlen(sql_set_person), &_session->set_person, NULL);
   5.579 +    assert(int_result == SQLITE_OK);
   5.580 +    int_result = sqlite3_prepare_v2(_session->db, sql_set_pgp_keypair,
   5.581 +            strlen(sql_set_pgp_keypair), &_session->set_pgp_keypair, NULL);
   5.582 +	assert(int_result == SQLITE_OK);
   5.583 +    int_result = sqlite3_prepare_v2(_session->db, sql_set_identity,
   5.584 +            strlen(sql_set_identity), &_session->set_identity, NULL);
   5.585 +	assert(int_result == SQLITE_OK);
   5.586 +    int_result = sqlite3_prepare_v2(_session->db, sql_set_trust,
   5.587 +            strlen(sql_set_trust), &_session->set_trust, NULL);
   5.588 +	assert(int_result == SQLITE_OK);
   5.589 +
   5.590 +	sqlite3_reset(_session->log);
   5.591 +    sqlite3_bind_text(_session->log, 1, "init", -1, SQLITE_STATIC);
   5.592 +    sqlite3_bind_text(_session->log, 2, "pEp " PEP_ENGINE_VERSION, -1,
   5.593 +            SQLITE_STATIC);
   5.594 +	do {
   5.595 +		int_result = sqlite3_step(_session->log);
   5.596 +		assert(int_result == SQLITE_DONE || int_result == SQLITE_BUSY);
   5.597 +	} while (int_result == SQLITE_BUSY);
   5.598 +    sqlite3_reset(_session->log);
   5.599 +
   5.600 +	*session = (void *) _session;
   5.601 +	return PEP_STATUS_OK;
   5.602 +}
   5.603 +
   5.604 +DYNAMIC_API void release(PEP_SESSION session)
   5.605 +{
   5.606 +	assert(session);
   5.607 +	pEpSession *_session = (pEpSession *) session;
   5.608 +
   5.609 +	if (_session) {
   5.610 +		if (_session->db) {
   5.611 +			sqlite3_finalize(_session->safeword);
   5.612 +			sqlite3_finalize(_session->log);
   5.613 +			sqlite3_finalize(_session->get_identity);
   5.614 +			sqlite3_finalize(_session->set_identity);
   5.615 +			sqlite3_close_v2(_session->db);
   5.616 +			sqlite3_close_v2(_session->system_db);
   5.617 +		}
   5.618 +		if (_session->ctx)
   5.619 +			_session->gpgme_release(_session->ctx);
   5.620 +		dlclose(_session->gpgme);
   5.621 +	}
   5.622 +	free(_session);
   5.623 +}
   5.624 +
   5.625 +stringlist_t *new_stringlist(const char *value)
   5.626 +{
   5.627 +    stringlist_t *result = (stringlist_t *) calloc(1, sizeof(stringlist_t));
   5.628 +    if (result && value) {
   5.629 +        result->value = strdup(value);
   5.630 +        assert(result->value);
   5.631 +        if (result->value == 0) {
   5.632 +            free(result);
   5.633 +            return NULL;
   5.634 +        }
   5.635 +    }
   5.636 +    return result;
   5.637 +}
   5.638 +
   5.639 +stringlist_t *stringlist_add(stringlist_t *stringlist, const char *value)
   5.640 +{
   5.641 +    assert(value);
   5.642 +
   5.643 +    if (stringlist == NULL)
   5.644 +        return new_stringlist(value);
   5.645 +
   5.646 +    if (stringlist->next != NULL)
   5.647 +        return stringlist_add(stringlist->next, value);
   5.648 +
   5.649 +    if (stringlist->value == NULL) {
   5.650 +        stringlist->value = strdup(value);
   5.651 +        assert(stringlist->value);
   5.652 +        if (stringlist->value == NULL)
   5.653 +            return NULL;
   5.654 +        return stringlist;
   5.655 +    }
   5.656 +
   5.657 +    stringlist->next = new_stringlist(value);
   5.658 +    assert(stringlist->next);
   5.659 +    if (stringlist->next == NULL)
   5.660 +        return NULL;
   5.661 +
   5.662 +    return stringlist->next;
   5.663 +}
   5.664 +
   5.665 +int stringlist_length(const stringlist_t *stringlist)
   5.666 +{
   5.667 +    int len = 1;
   5.668 +    stringlist_t *_stringlist;
   5.669 +
   5.670 +    assert(stringlist);
   5.671 +
   5.672 +    if (stringlist->value == NULL)
   5.673 +        return 0;
   5.674 +
   5.675 +    for (_stringlist=stringlist->next; _stringlist!=NULL; _stringlist=_stringlist->next)
   5.676 +        len += 1;
   5.677 +
   5.678 +    return len;
   5.679 +}
   5.680 +
   5.681 +void free_stringlist(stringlist_t *stringlist)
   5.682 +{
   5.683 +    if (stringlist) {
   5.684 +        free_stringlist(stringlist->next);
   5.685 +        free(stringlist->value);
   5.686 +        free(stringlist);
   5.687 +    }
   5.688 +}
   5.689 +
   5.690 +DYNAMIC_API PEP_STATUS decrypt_and_verify(
   5.691 +        PEP_SESSION session, const char *ctext, size_t csize,
   5.692 +        char **ptext, size_t *psize, stringlist_t **keylist
   5.693 +    )
   5.694 +{
   5.695 +	pEpSession *_session = (pEpSession *) session;
   5.696 +
   5.697 +	PEP_STATUS result;
   5.698 +	gpgme_error_t gpgme_error;
   5.699 +	gpgme_data_t cipher, plain;
   5.700 +	gpgme_data_type_t dt;
   5.701 +
   5.702 +	stringlist_t *_keylist = NULL;
   5.703 +	int i_key = 0;
   5.704 +
   5.705 +	assert(_session);
   5.706 +	assert(ctext);
   5.707 +	assert(csize);
   5.708 +	assert(ptext);
   5.709 +	assert(psize);
   5.710 +	assert(keylist);
   5.711 +
   5.712 +	*ptext = NULL;
   5.713 +	*psize = 0;
   5.714 +	*keylist = NULL;
   5.715 +
   5.716 +    gpgme_error = _session->gpgme_data_new_from_mem(&cipher, ctext, csize, 0);
   5.717 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
   5.718 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
   5.719 +		if (gpgme_error == GPG_ERR_ENOMEM)
   5.720 +			return PEP_OUT_OF_MEMORY;
   5.721 +		else
   5.722 +			return PEP_UNKNOWN_ERROR;
   5.723 +	}
   5.724 +
   5.725 +	gpgme_error = _session->gpgme_data_new(&plain);
   5.726 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
   5.727 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
   5.728 +		_session->gpgme_data_release(cipher);
   5.729 +		if (gpgme_error == GPG_ERR_ENOMEM)
   5.730 +			return PEP_OUT_OF_MEMORY;
   5.731 +		else
   5.732 +			return PEP_UNKNOWN_ERROR;
   5.733 +	}
   5.734 +
   5.735 +	dt = _session->gpgme_data_identify(cipher);
   5.736 +	switch (dt) {
   5.737 +	case GPGME_DATA_TYPE_PGP_SIGNED:
   5.738 +	case GPGME_DATA_TYPE_PGP_OTHER:
   5.739 +        gpgme_error = _session->gpgme_op_decrypt_verify(_session->ctx, cipher,
   5.740 +                plain);
   5.741 +		assert(gpgme_error != GPG_ERR_INV_VALUE);
   5.742 +		assert(gpgme_error != GPG_ERR_NO_DATA);
   5.743 +
   5.744 +		switch (gpgme_error) {
   5.745 +		case GPG_ERR_NO_ERROR:
   5.746 +			{
   5.747 +				gpgme_verify_result_t gpgme_verify_result;
   5.748 +                char *_buffer = NULL;
   5.749 +				size_t reading;
   5.750 +                size_t length = _session->gpgme_data_seek(plain, 0, SEEK_END);
   5.751 +                gpgme_signature_t gpgme_signature;
   5.752 +
   5.753 +				assert(length != -1);
   5.754 +				_session->gpgme_data_seek(plain, 0, SEEK_SET);
   5.755 +
   5.756 +				// TODO: make things less memory consuming
   5.757 +                // the following algorithm allocates memory for the complete
   5.758 +                // text
   5.759 +
   5.760 +                _buffer = malloc(length + 1);
   5.761 +                assert(_buffer);
   5.762 +                if (_buffer == NULL) {
   5.763 +                    _session->gpgme_data_release(plain);
   5.764 +                    _session->gpgme_data_release(cipher);
   5.765 +                    return PEP_OUT_OF_MEMORY;
   5.766 +                }
   5.767 +
   5.768 +                reading = _session->gpgme_data_read(plain, _buffer, length);
   5.769 +				assert(length == reading);
   5.770 +
   5.771 +                gpgme_verify_result =
   5.772 +                    _session->gpgme_op_verify_result(_session->ctx);
   5.773 +				assert(gpgme_verify_result);
   5.774 +                gpgme_signature = gpgme_verify_result->signatures;
   5.775 +
   5.776 +				if (gpgme_signature) {
   5.777 +                    stringlist_t *k;
   5.778 +                    _keylist = new_stringlist(NULL);
   5.779 +                    assert(_keylist);
   5.780 +                    if (_keylist == NULL) {
   5.781 +						_session->gpgme_data_release(plain);
   5.782 +						_session->gpgme_data_release(cipher);
   5.783 +                        free(_buffer);
   5.784 +                        return PEP_OUT_OF_MEMORY;
   5.785 +                    }
   5.786 +                    k = _keylist;
   5.787 +
   5.788 +                    result = PEP_DECRYPTED_AND_VERIFIED;
   5.789 +					do {
   5.790 +                        switch (gpgme_signature->status) {
   5.791 +                        case GPG_ERR_NO_ERROR:
   5.792 +                            k = stringlist_add(k, gpgme_signature->fpr);
   5.793 +                            break;
   5.794 +                        case GPG_ERR_CERT_REVOKED:
   5.795 +                        case GPG_ERR_BAD_SIGNATURE:
   5.796 +                            result = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
   5.797 +                            break;
   5.798 +                        case GPG_ERR_SIG_EXPIRED:
   5.799 +                        case GPG_ERR_KEY_EXPIRED:
   5.800 +                        case GPG_ERR_NO_PUBKEY:
   5.801 +                            k = stringlist_add(k, gpgme_signature->fpr);
   5.802 +                            if (result == PEP_DECRYPTED_AND_VERIFIED)
   5.803 +                                result = PEP_DECRYPTED;
   5.804 +                            break;
   5.805 +                        case GPG_ERR_GENERAL:
   5.806 +                            break;
   5.807 +                        default:
   5.808 +                            if (result == PEP_DECRYPTED_AND_VERIFIED)
   5.809 +                                result = PEP_DECRYPTED;
   5.810 +                            break;
   5.811 +                        }
   5.812 +					} while ((gpgme_signature = gpgme_signature->next));
   5.813 +				} else {
   5.814 +					result = PEP_DECRYPTED;
   5.815 +				}
   5.816 +
   5.817 +				if (result == PEP_DECRYPTED_AND_VERIFIED
   5.818 +                        || result == PEP_DECRYPTED) {
   5.819 +					*ptext = _buffer;
   5.820 +					*psize = reading;
   5.821 +                    (*ptext)[*psize] = 0; // safeguard for naive users
   5.822 +					*keylist = _keylist;
   5.823 +				}
   5.824 +                else {
   5.825 +                    free_stringlist(_keylist);
   5.826 +                    free(_buffer);
   5.827 +	            }
   5.828 +				break;
   5.829 +			}
   5.830 +		case GPG_ERR_DECRYPT_FAILED:
   5.831 +			result = PEP_DECRYPT_WRONG_FORMAT;
   5.832 +			break;
   5.833 +		case GPG_ERR_BAD_PASSPHRASE:
   5.834 +			NOT_IMPLEMENTED;
   5.835 +		default:
   5.836 +			result = PEP_CANNOT_DECRYPT_UNKNOWN;
   5.837 +		}
   5.838 +		break;
   5.839 +
   5.840 +	default:
   5.841 +		result = PEP_DECRYPT_WRONG_FORMAT;
   5.842 +	}
   5.843 +
   5.844 +	_session->gpgme_data_release(plain);
   5.845 +	_session->gpgme_data_release(cipher);
   5.846 +	return result;
   5.847 +}
   5.848 +
   5.849 +DYNAMIC_API PEP_STATUS verify_text(
   5.850 +        PEP_SESSION session, const char *text, size_t size,
   5.851 +        const char *signature, size_t sig_size, stringlist_t **keylist
   5.852 +    )
   5.853 +{
   5.854 +	pEpSession *_session = (pEpSession *) session;
   5.855 +
   5.856 +	PEP_STATUS result;
   5.857 +	gpgme_error_t gpgme_error;
   5.858 +	gpgme_data_t d_text, d_sig;
   5.859 +    stringlist_t *_keylist;
   5.860 +
   5.861 +    assert(session);
   5.862 +    assert(text);
   5.863 +    assert(size);
   5.864 +    assert(signature);
   5.865 +    assert(sig_size);
   5.866 +    assert(keylist);
   5.867 +
   5.868 +    *keylist = NULL;
   5.869 +
   5.870 +    gpgme_error = _session->gpgme_data_new_from_mem(&d_text, text, size, 0);
   5.871 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
   5.872 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
   5.873 +		if (gpgme_error == GPG_ERR_ENOMEM)
   5.874 +			return PEP_OUT_OF_MEMORY;
   5.875 +		else
   5.876 +			return PEP_UNKNOWN_ERROR;
   5.877 +	}
   5.878 +
   5.879 +    gpgme_error = _session->gpgme_data_new_from_mem(&d_sig, signature, sig_size, 0);
   5.880 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
   5.881 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
   5.882 +		_session->gpgme_data_release(d_text);
   5.883 +		if (gpgme_error == GPG_ERR_ENOMEM)
   5.884 +			return PEP_OUT_OF_MEMORY;
   5.885 +		else
   5.886 +			return PEP_UNKNOWN_ERROR;
   5.887 +	}
   5.888 +
   5.889 +    gpgme_error = _session->gpgme_op_verify(_session->ctx, d_sig, d_text, NULL);
   5.890 +    assert(gpgme_error != GPG_ERR_INV_VALUE);
   5.891 +
   5.892 +    switch (gpgme_error) {
   5.893 +    case GPG_ERR_NO_ERROR:
   5.894 +        {
   5.895 +            gpgme_verify_result_t gpgme_verify_result;
   5.896 +            gpgme_signature_t gpgme_signature;
   5.897 +
   5.898 +            gpgme_verify_result =
   5.899 +                _session->gpgme_op_verify_result(_session->ctx);
   5.900 +            assert(gpgme_verify_result);
   5.901 +            gpgme_signature = gpgme_verify_result->signatures;
   5.902 +
   5.903 +            if (gpgme_signature) {
   5.904 +                stringlist_t *k;
   5.905 +                _keylist = new_stringlist(NULL);
   5.906 +                assert(_keylist);
   5.907 +                if (_keylist == NULL) {
   5.908 +                    _session->gpgme_data_release(d_text);
   5.909 +                    _session->gpgme_data_release(d_sig);
   5.910 +                    return PEP_OUT_OF_MEMORY;
   5.911 +                }
   5.912 +                k = _keylist;
   5.913 +
   5.914 +                result = PEP_VERIFIED;
   5.915 +                do {
   5.916 +                    k = stringlist_add(k, gpgme_signature->fpr);
   5.917 +                    if (k == NULL) {
   5.918 +                        free_stringlist(_keylist);
   5.919 +                        _session->gpgme_data_release(d_text);
   5.920 +                        _session->gpgme_data_release(d_sig);
   5.921 +                        return PEP_OUT_OF_MEMORY;
   5.922 +                    }
   5.923 +                    if (gpgme_signature->summary & GPGME_SIGSUM_RED) {
   5.924 +                        if (gpgme_signature->summary & GPGME_SIGSUM_KEY_EXPIRED
   5.925 +                                || gpgme_signature->summary & GPGME_SIGSUM_SIG_EXPIRED) {
   5.926 +                            if (result == PEP_VERIFIED
   5.927 +                                    || result == PEP_VERIFIED_AND_TRUSTED)
   5.928 +                                result = PEP_UNENCRYPTED;
   5.929 +                        }
   5.930 +                        else {
   5.931 +                            result = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
   5.932 +                            break;
   5.933 +                        }
   5.934 +                    }
   5.935 +                    else {
   5.936 +                        if (gpgme_signature->summary & GPGME_SIGSUM_VALID) {
   5.937 +                            if (result == PEP_VERIFIED)
   5.938 +                                result = PEP_VERIFIED_AND_TRUSTED;
   5.939 +                        }
   5.940 +                        if (gpgme_signature->summary & GPGME_SIGSUM_GREEN) {
   5.941 +                            // good
   5.942 +                        }
   5.943 +                        else if (gpgme_signature->summary & GPGME_SIGSUM_KEY_MISSING) {
   5.944 +                            result = PEP_VERIFY_NO_KEY;
   5.945 +                        }
   5.946 +                        else if (gpgme_signature->summary & GPGME_SIGSUM_SYS_ERROR) {
   5.947 +                            if (result == PEP_VERIFIED
   5.948 +                                    || result == PEP_VERIFIED_AND_TRUSTED)
   5.949 +                                result = PEP_UNENCRYPTED;
   5.950 +                        }
   5.951 +                        else {
   5.952 +                            // do nothing
   5.953 +                        }
   5.954 +                    }
   5.955 +                } while ((gpgme_signature = gpgme_signature->next));
   5.956 +                *keylist = _keylist;
   5.957 +            } else {
   5.958 +                result = PEP_UNENCRYPTED;
   5.959 +            }
   5.960 +            break;
   5.961 +        }
   5.962 +        break;
   5.963 +    case GPG_ERR_NO_DATA:
   5.964 +        result = PEP_DECRYPT_WRONG_FORMAT;
   5.965 +        break;
   5.966 +    case GPG_ERR_INV_VALUE:
   5.967 +    default:
   5.968 +        result = PEP_UNKNOWN_ERROR;
   5.969 +        break;
   5.970 +    }
   5.971 +
   5.972 +    _session->gpgme_data_release(d_text);
   5.973 +    _session->gpgme_data_release(d_sig);
   5.974 +
   5.975 +    return result;
   5.976 +}
   5.977 +
   5.978 +DYNAMIC_API PEP_STATUS encrypt_and_sign(
   5.979 +        PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   5.980 +        size_t psize, char **ctext, size_t *csize
   5.981 +    )
   5.982 +{
   5.983 +	pEpSession *_session = (pEpSession *) session;
   5.984 +
   5.985 +	PEP_STATUS result;
   5.986 +	gpgme_error_t gpgme_error;
   5.987 +	gpgme_data_t plain, cipher;
   5.988 +	gpgme_key_t *rcpt;
   5.989 +	gpgme_encrypt_flags_t flags;
   5.990 +	const stringlist_t *_keylist;
   5.991 +    int i, j;
   5.992 +
   5.993 +	assert(_session);
   5.994 +	assert(keylist);
   5.995 +	assert(ptext);
   5.996 +	assert(psize);
   5.997 +	assert(ctext);
   5.998 +	assert(csize);
   5.999 +
  5.1000 +	*ctext = NULL;
  5.1001 +	*csize = 0;
  5.1002 +
  5.1003 +    gpgme_error = _session->gpgme_data_new_from_mem(&plain, ptext, psize, 0);
  5.1004 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
  5.1005 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
  5.1006 +		if (gpgme_error == GPG_ERR_ENOMEM)
  5.1007 +			return PEP_OUT_OF_MEMORY;
  5.1008 +		else
  5.1009 +			return PEP_UNKNOWN_ERROR;
  5.1010 +	}
  5.1011 +
  5.1012 +	gpgme_error = _session->gpgme_data_new(&cipher);
  5.1013 +	assert(gpgme_error == GPG_ERR_NO_ERROR);
  5.1014 +	if (gpgme_error != GPG_ERR_NO_ERROR) {
  5.1015 +		_session->gpgme_data_release(plain);
  5.1016 +		if (gpgme_error == GPG_ERR_ENOMEM)
  5.1017 +			return PEP_OUT_OF_MEMORY;
  5.1018 +		else
  5.1019 +			return PEP_UNKNOWN_ERROR;
  5.1020 +	}
  5.1021 +
  5.1022 +    rcpt = (gpgme_key_t *) calloc(stringlist_length(keylist) + 1,
  5.1023 +            sizeof(gpgme_key_t));
  5.1024 +	assert(rcpt);
  5.1025 +	if (rcpt == NULL) {
  5.1026 +		_session->gpgme_data_release(plain);
  5.1027 +		_session->gpgme_data_release(cipher);
  5.1028 +		return PEP_OUT_OF_MEMORY;
  5.1029 +	}
  5.1030 +
  5.1031 +    for (_keylist=keylist, i=0; _keylist!=NULL; _keylist=_keylist->next, i++) {
  5.1032 +		assert(_keylist->value);
  5.1033 +        gpgme_error = _session->gpgme_get_key(_session->ctx, _keylist->value,
  5.1034 +                &rcpt[i], 0);
  5.1035 +		assert(gpgme_error != GPG_ERR_ENOMEM);
  5.1036 +
  5.1037 +		switch (gpgme_error) {
  5.1038 +		case GPG_ERR_ENOMEM:
  5.1039 +            for (j=0; j<i; j++)
  5.1040 +                _session->gpgme_key_unref(rcpt[j]);
  5.1041 +			free(rcpt);
  5.1042 +			_session->gpgme_data_release(plain);
  5.1043 +			_session->gpgme_data_release(cipher);
  5.1044 +			return PEP_OUT_OF_MEMORY;
  5.1045 +		case GPG_ERR_NO_ERROR:
  5.1046 +			break;
  5.1047 +		case GPG_ERR_EOF:
  5.1048 +            for (j=0; j<i; j++)
  5.1049 +                _session->gpgme_key_unref(rcpt[j]);
  5.1050 +			free(rcpt);
  5.1051 +			_session->gpgme_data_release(plain);
  5.1052 +			_session->gpgme_data_release(cipher);
  5.1053 +			return PEP_KEY_NOT_FOUND;
  5.1054 +		case GPG_ERR_AMBIGUOUS_NAME:
  5.1055 +            for (j=0; j<i; j++)
  5.1056 +                _session->gpgme_key_unref(rcpt[j]);
  5.1057 +			free(rcpt);
  5.1058 +			_session->gpgme_data_release(plain);
  5.1059 +			_session->gpgme_data_release(cipher);
  5.1060 +			return PEP_KEY_HAS_AMBIG_NAME;
  5.1061 +        default: // GPG_ERR_INV_VALUE if CTX or R_KEY is not a valid pointer or
  5.1062 +                 // FPR is not a fingerprint or key ID
  5.1063 +            for (j=0; j<i; j++)
  5.1064 +                _session->gpgme_key_unref(rcpt[j]);
  5.1065 +			free(rcpt);
  5.1066 +			_session->gpgme_data_release(plain);
  5.1067 +			_session->gpgme_data_release(cipher);
  5.1068 +			return PEP_GET_KEY_FAILED;
  5.1069 +		}
  5.1070 +	}
  5.1071 +
  5.1072 +	// TODO: remove that and replace with proper key management
  5.1073 +	flags  = GPGME_ENCRYPT_ALWAYS_TRUST;
  5.1074 +
  5.1075 +    gpgme_error = _session->gpgme_op_encrypt_sign(_session->ctx, rcpt, flags,
  5.1076 +            plain, cipher);
  5.1077 +	switch (gpgme_error) {
  5.1078 +	case GPG_ERR_NO_ERROR:
  5.1079 +		{
  5.1080 +            char *_buffer = NULL;
  5.1081 +			size_t reading;
  5.1082 +            size_t length = _session->gpgme_data_seek(cipher, 0, SEEK_END);
  5.1083 +            assert(length != -1);
  5.1084 +			_session->gpgme_data_seek(cipher, 0, SEEK_SET);
  5.1085 +
  5.1086 +			// TODO: make things less memory consuming
  5.1087 +            // the following algorithm allocates a buffer for the complete text
  5.1088 +
  5.1089 +            _buffer = (char *) malloc(length + 1);
  5.1090 +            assert(_buffer);
  5.1091 +            if (_buffer == NULL) {
  5.1092 +                for (j=0; j<stringlist_length(keylist); j++)
  5.1093 +                    _session->gpgme_key_unref(rcpt[j]);
  5.1094 +                free(rcpt);
  5.1095 +                _session->gpgme_data_release(plain);
  5.1096 +                _session->gpgme_data_release(cipher);
  5.1097 +                return PEP_OUT_OF_MEMORY;
  5.1098 +            }
  5.1099 +
  5.1100 +            reading = _session->gpgme_data_read(cipher, _buffer, length);
  5.1101 +			assert(length == reading);
  5.1102 +
  5.1103 +			*ctext = _buffer;
  5.1104 +			*csize = reading;
  5.1105 +			(*ctext)[*csize] = 0; // safeguard for naive users
  5.1106 +			result = PEP_STATUS_OK;
  5.1107 +			break;
  5.1108 +		}
  5.1109 +	default:
  5.1110 +		result = PEP_UNKNOWN_ERROR;
  5.1111 +	}
  5.1112 +
  5.1113 +    for (j=0; j<stringlist_length(keylist); j++)
  5.1114 +        _session->gpgme_key_unref(rcpt[j]);
  5.1115 +	free(rcpt);
  5.1116 +	_session->gpgme_data_release(plain);
  5.1117 +	_session->gpgme_data_release(cipher);
  5.1118 +	return result;
  5.1119 +}
  5.1120 +
  5.1121 +DYNAMIC_API PEP_STATUS log_event(
  5.1122 +        PEP_SESSION session, const char *title, const char *entity,
  5.1123 +        const char *description, const char *comment
  5.1124 +    )
  5.1125 +{
  5.1126 +	pEpSession *_session = (pEpSession *) session;
  5.1127 +	PEP_STATUS status = PEP_STATUS_OK;
  5.1128 +	int result;
  5.1129 +
  5.1130 +	assert(_session);
  5.1131 +	assert(title);
  5.1132 +	assert(entity);
  5.1133 +
  5.1134 +	sqlite3_reset(_session->log);
  5.1135 +	sqlite3_bind_text(_session->log, 1, title, -1, SQLITE_STATIC);
  5.1136 +	sqlite3_bind_text(_session->log, 2, entity, -1, SQLITE_STATIC);
  5.1137 +	if (description)
  5.1138 +        sqlite3_bind_text(_session->log, 3, description, -1, SQLITE_STATIC);
  5.1139 +	else
  5.1140 +		sqlite3_bind_null(_session->log, 3);
  5.1141 +	if (comment)
  5.1142 +		sqlite3_bind_text(_session->log, 4, comment, -1, SQLITE_STATIC);
  5.1143 +	else
  5.1144 +		sqlite3_bind_null(_session->log, 4);
  5.1145 +	do {
  5.1146 +		result = sqlite3_step(_session->log);
  5.1147 +		assert(result == SQLITE_DONE || result == SQLITE_BUSY);
  5.1148 +		if (result != SQLITE_DONE && result != SQLITE_BUSY)
  5.1149 +			status = PEP_UNKNOWN_ERROR;
  5.1150 +	} while (result == SQLITE_BUSY);
  5.1151 +	sqlite3_reset(_session->log);
  5.1152 +
  5.1153 +	return status;
  5.1154 +}
  5.1155 +
  5.1156 +DYNAMIC_API PEP_STATUS safeword(
  5.1157 +            PEP_SESSION session, uint16_t value, const char *lang,
  5.1158 +            char **word, size_t *wsize
  5.1159 +        )
  5.1160 +{
  5.1161 +	pEpSession *_session = (pEpSession *) session;
  5.1162 +	PEP_STATUS status = PEP_STATUS_OK;
  5.1163 +	int result;
  5.1164 +
  5.1165 +	assert(_session);
  5.1166 +	assert(word);
  5.1167 +	assert(wsize);
  5.1168 +
  5.1169 +	*word = NULL;
  5.1170 +	*wsize = 0;
  5.1171 +
  5.1172 +	if (lang == NULL)
  5.1173 +		lang = "en";
  5.1174 +
  5.1175 +	assert((lang[0] >= 'A' && lang[0] <= 'Z')
  5.1176 +            || (lang[0] >= 'a' && lang[0] <= 'z'));
  5.1177 +	assert((lang[1] >= 'A' && lang[1] <= 'Z')
  5.1178 +            || (lang[1] >= 'a' && lang[1] <= 'z'));
  5.1179 +	assert(lang[2] == 0);
  5.1180 +
  5.1181 +	sqlite3_reset(_session->safeword);
  5.1182 +    sqlite3_bind_text(_session->safeword, 1, lang, -1, SQLITE_STATIC);
  5.1183 +	sqlite3_bind_int(_session->safeword, 2, value);
  5.1184 +
  5.1185 +	result = sqlite3_step(_session->safeword);
  5.1186 +	if (result == SQLITE_ROW) {
  5.1187 +        *word = strdup((const char *) sqlite3_column_text(_session->safeword,
  5.1188 +                    1));
  5.1189 +		if (*word)
  5.1190 +            *wsize = sqlite3_column_bytes(_session->safeword, 1);
  5.1191 +		else
  5.1192 +			status = PEP_SAFEWORD_NOT_FOUND;
  5.1193 +	} else
  5.1194 +		status = PEP_SAFEWORD_NOT_FOUND;
  5.1195 +
  5.1196 +	sqlite3_reset(_session->safeword);
  5.1197 +	return status;
  5.1198 +}
  5.1199 +
  5.1200 +DYNAMIC_API PEP_STATUS safewords(
  5.1201 +        PEP_SESSION session, const char *fingerprint, const char *lang,
  5.1202 +        char **words, size_t *wsize, int max_words
  5.1203 +    )
  5.1204 +{
  5.1205 +	const char *source = fingerprint;
  5.1206 +	char *buffer = calloc(1, MAX_SAFEWORDS_SPACE);
  5.1207 +	char *dest = buffer;
  5.1208 +	size_t fsize;
  5.1209 +    PEP_STATUS _status;
  5.1210 +
  5.1211 +	assert(session);
  5.1212 +	assert(fingerprint);
  5.1213 +	assert(words);
  5.1214 +	assert(wsize);
  5.1215 +	assert(max_words >= 0);
  5.1216 +
  5.1217 +	*words = NULL;
  5.1218 +	*wsize = 0;
  5.1219 +
  5.1220 +    assert(buffer);
  5.1221 +    if (buffer == NULL)
  5.1222 +        return PEP_OUT_OF_MEMORY;
  5.1223 +
  5.1224 +	fsize = strlen(fingerprint);
  5.1225 +
  5.1226 +	if (lang == NULL)
  5.1227 +		lang = "en";
  5.1228 +
  5.1229 +	assert((lang[0] >= 'A' && lang[0] <= 'Z')
  5.1230 +            || (lang[0] >= 'a' && lang[0] <= 'z'));
  5.1231 +	assert((lang[1] >= 'A' && lang[1] <= 'Z')
  5.1232 +            || (lang[1] >= 'a' && lang[1] <= 'z'));
  5.1233 +	assert(lang[2] == 0);
  5.1234 +
  5.1235 +	int n_words = 0;
  5.1236 +	while (source < fingerprint + fsize) {
  5.1237 +		uint16_t value;
  5.1238 +		char *word;
  5.1239 +		size_t _wsize;
  5.1240 +		int j;
  5.1241 +
  5.1242 +        for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
  5.1243 +			if (*source >= 'a' && *source <= 'f')
  5.1244 +				value += (*source - 'a' + 10) << (3 - j++) * 4;
  5.1245 +			else if (*source >= 'A' && *source <= 'F')
  5.1246 +				value += (*source - 'A' + 10) << (3 - j++) * 4;
  5.1247 +			else if (*source >= '0' && *source <= '9')
  5.1248 +				value += (*source - '0') << (3 - j++) * 4;
  5.1249 +			
  5.1250 +			source++;
  5.1251 +		}
  5.1252 +
  5.1253 +		_status = safeword(session, value, lang, &word, &_wsize);
  5.1254 +        if (_status == PEP_OUT_OF_MEMORY) {
  5.1255 +            free(buffer);
  5.1256 +            return PEP_OUT_OF_MEMORY;
  5.1257 +        }
  5.1258 +		if (word == NULL) {
  5.1259 +            free(buffer);
  5.1260 +			return PEP_SAFEWORD_NOT_FOUND;
  5.1261 +        }
  5.1262 +
  5.1263 +		if (dest + _wsize < buffer + MAX_SAFEWORDS_SPACE - 1) {
  5.1264 +			strncpy(dest, word, _wsize);
  5.1265 +            free(word);
  5.1266 +			dest += _wsize;
  5.1267 +		}
  5.1268 +		else {
  5.1269 +            free(word);
  5.1270 +			break; // buffer full
  5.1271 +        }
  5.1272 +
  5.1273 +		if (source < fingerprint + fsize
  5.1274 +                && dest + _wsize < buffer + MAX_SAFEWORDS_SPACE - 1)
  5.1275 +			*dest++ = ' ';
  5.1276 +
  5.1277 +		++n_words;
  5.1278 +		if (max_words && n_words >= max_words)
  5.1279 +			break;
  5.1280 +	}
  5.1281 +
  5.1282 +	*words = buffer;
  5.1283 +	*wsize = dest - buffer;
  5.1284 +	return PEP_STATUS_OK;
  5.1285 +}
  5.1286 +
  5.1287 +pEp_identity *new_identity(
  5.1288 +        const char *address, const char *fpr, const char *user_id,
  5.1289 +        const char *username
  5.1290 +    )
  5.1291 +{
  5.1292 +    pEp_identity *result = calloc(1, sizeof(pEp_identity));
  5.1293 +    assert(result);
  5.1294 +    if (result) {
  5.1295 +        if (address) {
  5.1296 +            result->address = strdup(address);
  5.1297 +            assert(result->address);
  5.1298 +            if (result->address == NULL) {
  5.1299 +                free(result);
  5.1300 +                return NULL;
  5.1301 +            }
  5.1302 +            result->address_size = strlen(address);
  5.1303 +        }
  5.1304 +        if (fpr) {
  5.1305 +            result->fpr = strdup(fpr);
  5.1306 +            assert(result->fpr);
  5.1307 +            if (result->fpr == NULL) {
  5.1308 +                free_identity(result);
  5.1309 +                return NULL;
  5.1310 +            }
  5.1311 +            result->fpr_size = strlen(fpr);
  5.1312 +        }
  5.1313 +        if (user_id) {
  5.1314 +            result->user_id = strdup(user_id);
  5.1315 +            assert(result->user_id);
  5.1316 +            if (result->user_id == NULL) {
  5.1317 +                free_identity(result);
  5.1318 +                return NULL;
  5.1319 +            }
  5.1320 +            result->user_id_size = strlen(user_id);
  5.1321 +        }
  5.1322 +        if (username) {
  5.1323 +            result->username = strdup(username);
  5.1324 +            assert(result->username);
  5.1325 +            if (result->username == NULL) {
  5.1326 +                free_identity(result);
  5.1327 +                return NULL;
  5.1328 +            }
  5.1329 +            result->username_size = strlen(username);
  5.1330 +        }
  5.1331 +        result->struct_size = sizeof(pEp_identity);
  5.1332 +    }
  5.1333 +    return result;
  5.1334 +}
  5.1335 +
  5.1336 +void free_identity(pEp_identity *identity)
  5.1337 +{
  5.1338 +    if (identity) {
  5.1339 +        free(identity->address);
  5.1340 +        free(identity->fpr);
  5.1341 +        free(identity->user_id);
  5.1342 +        free(identity->username);
  5.1343 +        free(identity);
  5.1344 +    }
  5.1345 +}
  5.1346 +
  5.1347 +DYNAMIC_API PEP_STATUS get_identity(
  5.1348 +        PEP_SESSION session, const char *address,
  5.1349 +        pEp_identity **identity
  5.1350 +    )
  5.1351 +{
  5.1352 +	pEpSession *_session = (pEpSession *) session;
  5.1353 +	PEP_STATUS status = PEP_STATUS_OK;
  5.1354 +	static pEp_identity *_identity;
  5.1355 +	int result;
  5.1356 +	const char *_lang;
  5.1357 +
  5.1358 +	assert(session);
  5.1359 +	assert(address);
  5.1360 +
  5.1361 +    sqlite3_reset(_session->get_identity);
  5.1362 +    sqlite3_bind_text(_session->get_identity, 1, address, -1, SQLITE_STATIC);
  5.1363 +
  5.1364 +    result = sqlite3_step(_session->get_identity);
  5.1365 +	switch (result) {
  5.1366 +	case SQLITE_ROW:
  5.1367 +        _identity = new_identity(
  5.1368 +                address,
  5.1369 +                (const char *) sqlite3_column_text(_session->get_identity, 0),
  5.1370 +                (const char *) sqlite3_column_text(_session->get_identity, 1),
  5.1371 +                (const char *) sqlite3_column_text(_session->get_identity, 2)
  5.1372 +                );
  5.1373 +        assert(_identity);
  5.1374 +        if (_identity == NULL)
  5.1375 +            return PEP_OUT_OF_MEMORY;
  5.1376 +
  5.1377 +        _identity->comm_type = (PEP_comm_type) sqlite3_column_int(_session->get_identity, 3);
  5.1378 +        _lang = (const char *) sqlite3_column_text(_session->get_identity, 4);
  5.1379 +        if (_lang && _lang[0]) {
  5.1380 +			assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  5.1381 +			assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  5.1382 +			assert(_lang[2] == 0);
  5.1383 +			_identity->lang[0] = _lang[0];
  5.1384 +			_identity->lang[1] = _lang[1];
  5.1385 +            _identity->lang[2] = 0;
  5.1386 +		}
  5.1387 +		*identity = _identity;
  5.1388 +		break;
  5.1389 +	default:
  5.1390 +        status = PEP_CANNOT_FIND_IDENTITY;
  5.1391 +		*identity = NULL;
  5.1392 +	}
  5.1393 +
  5.1394 +    sqlite3_reset(_session->get_identity);
  5.1395 +	return status;
  5.1396 +}
  5.1397 +
  5.1398 +DYNAMIC_API PEP_STATUS set_identity(
  5.1399 +        PEP_SESSION session, const pEp_identity *identity
  5.1400 +    )
  5.1401 +{
  5.1402 +	pEpSession *_session = (pEpSession *) session;
  5.1403 +	int result;
  5.1404 +
  5.1405 +	assert(session);
  5.1406 +	assert(identity);
  5.1407 +	assert(identity->address);
  5.1408 +	assert(identity->fpr);
  5.1409 +	assert(identity->user_id);
  5.1410 +	assert(identity->username);
  5.1411 +
  5.1412 +	sqlite3_exec(_session->db, "BEGIN ;", NULL, NULL, NULL);
  5.1413 +
  5.1414 +	sqlite3_reset(_session->set_person);
  5.1415 +    sqlite3_bind_text(_session->set_person, 1, identity->user_id, -1,
  5.1416 +            SQLITE_STATIC);
  5.1417 +    sqlite3_bind_text(_session->set_person, 2, identity->username, -1,
  5.1418 +            SQLITE_STATIC);
  5.1419 +	if (identity->lang[0])
  5.1420 +        sqlite3_bind_text(_session->set_person, 3, identity->lang, 1,
  5.1421 +                SQLITE_STATIC);
  5.1422 +	else
  5.1423 +		sqlite3_bind_null(_session->set_person, 3);
  5.1424 +	result = sqlite3_step(_session->set_person);
  5.1425 +	sqlite3_reset(_session->set_person);
  5.1426 +	if (result != SQLITE_DONE) {
  5.1427 +		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  5.1428 +		return PEP_CANNOT_SET_PERSON;
  5.1429 +	}
  5.1430 +
  5.1431 +	sqlite3_reset(_session->set_pgp_keypair);
  5.1432 +    sqlite3_bind_text(_session->set_pgp_keypair, 1, identity->fpr, -1,
  5.1433 +            SQLITE_STATIC);
  5.1434 +	result = sqlite3_step(_session->set_pgp_keypair);
  5.1435 +	sqlite3_reset(_session->set_pgp_keypair);
  5.1436 +	if (result != SQLITE_DONE) {
  5.1437 +		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  5.1438 +		return PEP_CANNOT_SET_PGP_KEYPAIR;
  5.1439 +	}
  5.1440 +
  5.1441 +	sqlite3_reset(_session->set_identity);
  5.1442 +    sqlite3_bind_text(_session->set_identity, 1, identity->address, -1,
  5.1443 +            SQLITE_STATIC);
  5.1444 +    sqlite3_bind_text(_session->set_identity, 2, identity->fpr, -1,
  5.1445 +            SQLITE_STATIC);
  5.1446 +    sqlite3_bind_text(_session->set_identity, 3, identity->user_id, -1,
  5.1447 +            SQLITE_STATIC);
  5.1448 +	result = sqlite3_step(_session->set_identity);
  5.1449 +	sqlite3_reset(_session->set_identity);
  5.1450 +	if (result != SQLITE_DONE) {
  5.1451 +		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  5.1452 +		return PEP_CANNOT_SET_IDENTITY;
  5.1453 +	}
  5.1454 +
  5.1455 +	sqlite3_reset(_session->set_trust);
  5.1456 +    sqlite3_bind_text(_session->set_trust, 1, identity->user_id, -1,
  5.1457 +            SQLITE_STATIC);
  5.1458 +    sqlite3_bind_text(_session->set_trust, 2, identity->fpr, -1,
  5.1459 +            SQLITE_STATIC);
  5.1460 +	sqlite3_bind_int(_session->set_trust, 3, identity->comm_type);
  5.1461 +	result = sqlite3_step(_session->set_trust);
  5.1462 +	sqlite3_reset(_session->set_trust);
  5.1463 +	if (result != SQLITE_DONE) {
  5.1464 +		sqlite3_exec(_session->db, "ROLLBACK ;", NULL, NULL, NULL);
  5.1465 +		return PEP_CANNOT_SET_IDENTITY;
  5.1466 +	}
  5.1467 +
  5.1468 +    result = sqlite3_exec(_session->db, "COMMIT ;", NULL, NULL, NULL);
  5.1469 +	if (result == SQLITE_OK)
  5.1470 +		return PEP_STATUS_OK;
  5.1471 +	else
  5.1472 +		return PEP_COMMIT_FAILED;
  5.1473 +}
  5.1474 +
  5.1475 +DYNAMIC_API PEP_STATUS generate_keypair(
  5.1476 +        PEP_SESSION session, pEp_identity *identity
  5.1477 +    )
  5.1478 +{
  5.1479 +	pEpSession *_session = (pEpSession *) session;
  5.1480 +	gpgme_error_t gpgme_error;
  5.1481 +    char *parms;
  5.1482 +    const char *template =
  5.1483 +        "<GnupgKeyParms format=\"internal\">\n"
  5.1484 +        "Key-Type: RSA\n"
  5.1485 +        "Key-Length: 4096\n"
  5.1486 +        "Name-Real: %s\n"
  5.1487 +        "Name-Email: %s\n"
  5.1488 +        /* "Passphrase: %s\n" */
  5.1489 +        "Expire-Date: 1y\n"
  5.1490 +        "</GnupgKeyParms>\n";
  5.1491 +    int result;
  5.1492 +    gpgme_genkey_result_t gpgme_genkey_result;
  5.1493 +
  5.1494 +    assert(session);
  5.1495 +    assert(identity);
  5.1496 +    assert(identity->address);
  5.1497 +    assert(identity->fpr == NULL);
  5.1498 +    assert(identity->username);
  5.1499 +    
  5.1500 +    parms = calloc(1, PARMS_MAX);
  5.1501 +    assert(parms);
  5.1502 +    if (parms == NULL)
  5.1503 +        return PEP_OUT_OF_MEMORY;
  5.1504 +
  5.1505 +    result = snprintf(parms, PARMS_MAX, template, identity->username,
  5.1506 +            identity->address); // , _session->passphrase);
  5.1507 +    assert(result < PARMS_MAX);
  5.1508 +    if (result >= PARMS_MAX) {
  5.1509 +        free(parms);
  5.1510 +        return PEP_BUFFER_TOO_SMALL;
  5.1511 +    }
  5.1512 +
  5.1513 +    gpgme_error = _session->gpgme_op_genkey(_session->ctx, parms, NULL, NULL);
  5.1514 +    free(parms);
  5.1515 +
  5.1516 +    switch (gpgme_error) {
  5.1517 +    case GPG_ERR_NO_ERROR:
  5.1518 +        break;
  5.1519 +    case GPG_ERR_INV_VALUE:
  5.1520 +        return PEP_ILLEGAL_VALUE;
  5.1521 +    case GPG_ERR_GENERAL:
  5.1522 +        return PEP_CANNOT_CREATE_KEY;
  5.1523 +    default:
  5.1524 +        assert(0);
  5.1525 +        return PEP_UNKNOWN_ERROR;
  5.1526 +    }
  5.1527 +
  5.1528 +    gpgme_genkey_result = _session->gpgme_op_genkey_result(_session->ctx);
  5.1529 +    assert(gpgme_genkey_result);
  5.1530 +    assert(gpgme_genkey_result->fpr);
  5.1531 +
  5.1532 +    identity->fpr = strdup(gpgme_genkey_result->fpr);
  5.1533 +
  5.1534 +    return PEP_STATUS_OK;
  5.1535 +}
  5.1536 +
  5.1537 +PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  5.1538 +{
  5.1539 +	pEpSession *_session = (pEpSession *) session;
  5.1540 +	gpgme_error_t gpgme_error;
  5.1541 +    gpgme_key_t key;
  5.1542 +
  5.1543 +    assert(session);
  5.1544 +    assert(fpr);
  5.1545 +
  5.1546 +    gpgme_error = _session->gpgme_get_key(_session->ctx, fpr, &key, 0);
  5.1547 +    assert(gpgme_error != GPG_ERR_ENOMEM);
  5.1548 +    switch (gpgme_error) {
  5.1549 +    case GPG_ERR_NO_ERROR:
  5.1550 +        break;
  5.1551 +    case GPG_ERR_EOF:
  5.1552 +        return PEP_KEY_NOT_FOUND;
  5.1553 +    case GPG_ERR_INV_VALUE:
  5.1554 +        return PEP_ILLEGAL_VALUE;
  5.1555 +    case GPG_ERR_AMBIGUOUS_NAME:
  5.1556 +        return PEP_KEY_HAS_AMBIG_NAME;
  5.1557 +    case GPG_ERR_ENOMEM:
  5.1558 +        return PEP_OUT_OF_MEMORY;
  5.1559 +    default:
  5.1560 +        assert(0);
  5.1561 +        return PEP_UNKNOWN_ERROR;
  5.1562 +    }
  5.1563 +
  5.1564 +    gpgme_error = _session->gpgme_op_delete(_session->ctx, key, 1);
  5.1565 +    _session->gpgme_key_unref(key);
  5.1566 +    switch (gpgme_error) {
  5.1567 +    case GPG_ERR_NO_ERROR:
  5.1568 +        break;
  5.1569 +    case GPG_ERR_INV_VALUE:
  5.1570 +        assert(0);
  5.1571 +        return PEP_UNKNOWN_ERROR;
  5.1572 +    case GPG_ERR_NO_PUBKEY:
  5.1573 +        assert(0);
  5.1574 +        return PEP_KEY_NOT_FOUND;
  5.1575 +    case GPG_ERR_AMBIGUOUS_NAME:
  5.1576 +        assert(0);
  5.1577 +        return PEP_KEY_HAS_AMBIG_NAME;
  5.1578 +    default:
  5.1579 +        assert(0);
  5.1580 +        return PEP_UNKNOWN_ERROR;
  5.1581 +    }
  5.1582 +
  5.1583 +    return PEP_STATUS_OK;
  5.1584 +}
  5.1585 +
  5.1586 +PEP_STATUS import_key(PEP_SESSION session, const char *key_data, size_t size)
  5.1587 +{
  5.1588 +	pEpSession *_session = (pEpSession *) session;
  5.1589 +	gpgme_error_t gpgme_error;
  5.1590 +    gpgme_data_t dh;
  5.1591 +
  5.1592 +    assert(session);
  5.1593 +    assert(key_data);
  5.1594 +
  5.1595 +    gpgme_error = _session->gpgme_data_new_from_mem(&dh, key_data, size, 0);
  5.1596 +    assert(gpgme_error != GPG_ERR_ENOMEM);
  5.1597 +    switch (gpgme_error) {
  5.1598 +    case GPG_ERR_NO_ERROR:
  5.1599 +        break;
  5.1600 +    case GPG_ERR_ENOMEM:
  5.1601 +        return PEP_OUT_OF_MEMORY;
  5.1602 +    case GPG_ERR_INV_VALUE:
  5.1603 +        assert(0);
  5.1604 +        return PEP_UNKNOWN_ERROR;
  5.1605 +    default:
  5.1606 +        assert(0);
  5.1607 +        return PEP_UNKNOWN_ERROR;
  5.1608 +    }
  5.1609 +
  5.1610 +    gpgme_error = _session->gpgme_op_import(_session->ctx, dh);
  5.1611 +    switch (gpgme_error) {
  5.1612 +    case GPG_ERR_NO_ERROR:
  5.1613 +        break;
  5.1614 +    case GPG_ERR_INV_VALUE:
  5.1615 +        assert(0);
  5.1616 +        _session->gpgme_data_release(dh);
  5.1617 +        return PEP_UNKNOWN_ERROR;
  5.1618 +    case GPG_ERR_NO_DATA:
  5.1619 +        _session->gpgme_data_release(dh);
  5.1620 +        return PEP_ILLEGAL_VALUE;
  5.1621 +    default:
  5.1622 +        assert(0);
  5.1623 +        _session->gpgme_data_release(dh);
  5.1624 +        return PEP_UNKNOWN_ERROR;
  5.1625 +    }
  5.1626 +
  5.1627 +    _session->gpgme_data_release(dh);
  5.1628 +    return PEP_STATUS_OK;
  5.1629 +}
  5.1630 +
  5.1631 +PEP_STATUS export_key(
  5.1632 +        PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  5.1633 +    )
  5.1634 +{
  5.1635 +	pEpSession *_session = (pEpSession *) session;
  5.1636 +	gpgme_error_t gpgme_error;
  5.1637 +    gpgme_data_t dh;
  5.1638 +    size_t _size;
  5.1639 +    char *buffer;
  5.1640 +    int reading;
  5.1641 +
  5.1642 +    assert(session);
  5.1643 +    assert(fpr);
  5.1644 +    assert(key_data);
  5.1645 +    assert(size);
  5.1646 +
  5.1647 +    gpgme_error = _session->gpgme_data_new(&dh);
  5.1648 +    assert(gpgme_error != GPG_ERR_ENOMEM);
  5.1649 +    switch (gpgme_error) {
  5.1650 +    case GPG_ERR_NO_ERROR:
  5.1651 +        break;
  5.1652 +    case GPG_ERR_ENOMEM:
  5.1653 +        return PEP_OUT_OF_MEMORY;
  5.1654 +    case GPG_ERR_INV_VALUE:
  5.1655 +        assert(0);
  5.1656 +        return PEP_UNKNOWN_ERROR;
  5.1657 +    default:
  5.1658 +        assert(0);
  5.1659 +        return PEP_UNKNOWN_ERROR;
  5.1660 +    }
  5.1661 +
  5.1662 +    gpgme_error = _session->gpgme_op_export(_session->ctx, fpr,
  5.1663 +            GPGME_EXPORT_MODE_MINIMAL, dh);
  5.1664 +    switch (gpgme_error) {
  5.1665 +    case GPG_ERR_NO_ERROR:
  5.1666 +        break;
  5.1667 +    case GPG_ERR_EOF:
  5.1668 +        _session->gpgme_data_release(dh);
  5.1669 +        return PEP_KEY_NOT_FOUND;
  5.1670 +    case GPG_ERR_INV_VALUE:
  5.1671 +        assert(0);
  5.1672 +        _session->gpgme_data_release(dh);
  5.1673 +        return PEP_UNKNOWN_ERROR;
  5.1674 +    default:
  5.1675 +        assert(0);
  5.1676 +        _session->gpgme_data_release(dh);
  5.1677 +        return PEP_UNKNOWN_ERROR;
  5.1678 +    };
  5.1679 +
  5.1680 +    _size = _session->gpgme_data_seek(dh, 0, SEEK_END);
  5.1681 +    assert(_size != -1);
  5.1682 +    _session->gpgme_data_seek(dh, 0, SEEK_SET);
  5.1683 +
  5.1684 +    buffer = malloc(_size + 1);
  5.1685 +    assert(buffer);
  5.1686 +    if (buffer == NULL) {
  5.1687 +        _session->gpgme_data_release(dh);
  5.1688 +        return PEP_OUT_OF_MEMORY;
  5.1689 +    }
  5.1690 +
  5.1691 +    reading = _session->gpgme_data_read(dh, buffer, _size);
  5.1692 +    assert(_size == reading);
  5.1693 +
  5.1694 +    // safeguard for the naive user
  5.1695 +    buffer[_size] = 0;
  5.1696 +
  5.1697 +    *key_data = buffer;
  5.1698 +    *size = _size;
  5.1699 +
  5.1700 +    _session->gpgme_data_release(dh);
  5.1701 +    return PEP_STATUS_OK;
  5.1702 +}
  5.1703 +
  5.1704 +static void _switch_mode(pEpSession *_session, gpgme_keylist_mode_t remove_mode,
  5.1705 +        gpgme_keylist_mode_t add_mode)
  5.1706 +{
  5.1707 +	gpgme_error_t gpgme_error;
  5.1708 +    gpgme_keylist_mode_t mode;
  5.1709 +
  5.1710 +    mode = _session->gpgme_get_keylist_mode(_session->ctx);
  5.1711 +
  5.1712 +    mode &= ~remove_mode;
  5.1713 +    mode |= add_mode;
  5.1714 +
  5.1715 +    gpgme_error = _session->gpgme_set_keylist_mode(_session->ctx, mode);
  5.1716 +    assert(gpgme_error == GPG_ERR_NO_ERROR);
  5.1717 +}
  5.1718 +
  5.1719 +PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  5.1720 +{
  5.1721 +	pEpSession *_session = (pEpSession *) session;
  5.1722 +	gpgme_error_t gpgme_error;
  5.1723 +    gpgme_key_t key;
  5.1724 +
  5.1725 +    assert(session);
  5.1726 +    assert(pattern);
  5.1727 +
  5.1728 +    _switch_mode(_session, GPGME_KEYLIST_MODE_LOCAL, GPGME_KEYLIST_MODE_EXTERN);
  5.1729 +
  5.1730 +    gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, pattern, 0);
  5.1731 +    switch (gpgme_error) {
  5.1732 +    case GPG_ERR_NO_ERROR:
  5.1733 +        break;
  5.1734 +    case GPG_ERR_INV_VALUE:
  5.1735 +        assert(0);
  5.1736 +        _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  5.1737 +                GPGME_KEYLIST_MODE_LOCAL);
  5.1738 +        return PEP_UNKNOWN_ERROR;
  5.1739 +    default:
  5.1740 +        _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  5.1741 +                GPGME_KEYLIST_MODE_LOCAL);
  5.1742 +        return PEP_GET_KEY_FAILED;
  5.1743 +    };
  5.1744 +
  5.1745 +    do {
  5.1746 +        gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  5.1747 +        assert(gpgme_error != GPG_ERR_INV_VALUE);
  5.1748 +        switch (gpgme_error) {
  5.1749 +        case GPG_ERR_EOF:
  5.1750 +            break;
  5.1751 +        case GPG_ERR_NO_ERROR:
  5.1752 +            {
  5.1753 +                gpgme_error_t gpgme_error;
  5.1754 +                gpgme_key_t keys[2];
  5.1755 +
  5.1756 +                keys[0] = key;
  5.1757 +                keys[1] = NULL;
  5.1758 +
  5.1759 +                gpgme_error = _session->gpgme_op_import_keys(_session->ctx, keys);
  5.1760 +                _session->gpgme_key_unref(key);
  5.1761 +                assert(gpgme_error != GPG_ERR_INV_VALUE);
  5.1762 +                assert(gpgme_error != GPG_ERR_CONFLICT);
  5.1763 +            }
  5.1764 +            break;
  5.1765 +        case GPG_ERR_ENOMEM:
  5.1766 +            _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  5.1767 +                    GPGME_KEYLIST_MODE_LOCAL);
  5.1768 +            _session->gpgme_op_keylist_end(_session->ctx);
  5.1769 +            return PEP_OUT_OF_MEMORY;
  5.1770 +        default:
  5.1771 +            // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  5.1772 +            // reading first key
  5.1773 +#ifndef NDEBUG
  5.1774 +            fprintf(stderr, "warning: unknown result 0x%x of"
  5.1775 +                    " gpgme_op_keylist_next()\n", gpgme_error);
  5.1776 +#endif
  5.1777 +            gpgme_error = GPG_ERR_EOF;
  5.1778 +            break;
  5.1779 +        };
  5.1780 +    } while (gpgme_error != GPG_ERR_EOF);
  5.1781 +
  5.1782 +    _session->gpgme_op_keylist_end(_session->ctx);
  5.1783 +    _switch_mode(_session, GPGME_KEYLIST_MODE_EXTERN,
  5.1784 +            GPGME_KEYLIST_MODE_LOCAL);
  5.1785 +    return PEP_STATUS_OK;
  5.1786 +}
  5.1787 +
  5.1788 +DYNAMIC_API PEP_STATUS find_keys(
  5.1789 +        PEP_SESSION session, const char *pattern, stringlist_t **keylist
  5.1790 +    )
  5.1791 +{
  5.1792 +	pEpSession *_session = (pEpSession *) session;
  5.1793 +	gpgme_error_t gpgme_error;
  5.1794 +    gpgme_key_t key;
  5.1795 +    stringlist_t *_keylist;
  5.1796 +    char *fpr;
  5.1797 +
  5.1798 +    assert(session);
  5.1799 +    assert(pattern);
  5.1800 +    assert(keylist);
  5.1801 +
  5.1802 +    *keylist = NULL;
  5.1803 +
  5.1804 +    gpgme_error = _session->gpgme_op_keylist_start(_session->ctx, pattern, 0);
  5.1805 +    switch (gpgme_error) {
  5.1806 +    case GPG_ERR_NO_ERROR:
  5.1807 +        break;
  5.1808 +    case GPG_ERR_INV_VALUE:
  5.1809 +        assert(0);
  5.1810 +        return PEP_UNKNOWN_ERROR;
  5.1811 +    default:
  5.1812 +        return PEP_GET_KEY_FAILED;
  5.1813 +    };
  5.1814 +
  5.1815 +    _keylist = new_stringlist(NULL);
  5.1816 +    stringlist_t *_k = _keylist;
  5.1817 +
  5.1818 +    do {
  5.1819 +        gpgme_error = _session->gpgme_op_keylist_next(_session->ctx, &key);
  5.1820 +        assert(gpgme_error != GPG_ERR_INV_VALUE);
  5.1821 +        switch (gpgme_error) {
  5.1822 +        case GPG_ERR_EOF:
  5.1823 +            break;
  5.1824 +        case GPG_ERR_NO_ERROR:
  5.1825 +            assert(key);
  5.1826 +            assert(key->subkeys);
  5.1827 +            fpr = key->subkeys->fpr;
  5.1828 +            assert(fpr);
  5.1829 +            _k = stringlist_add(_k, fpr);
  5.1830 +            assert(_k);
  5.1831 +            if (_k != NULL)
  5.1832 +                break;
  5.1833 +        case GPG_ERR_ENOMEM:
  5.1834 +            free_stringlist(_keylist);
  5.1835 +            _session->gpgme_op_keylist_end(_session->ctx);
  5.1836 +            return PEP_OUT_OF_MEMORY;
  5.1837 +        default:
  5.1838 +            // BUG: GPGME returns an illegal value instead of GPG_ERR_EOF after
  5.1839 +            // reading first key
  5.1840 +#ifndef NDEBUG
  5.1841 +            fprintf(stderr, "warning: unknown result 0x%x of"
  5.1842 +                    " gpgme_op_keylist_next()\n", gpgme_error);
  5.1843 +#endif
  5.1844 +            gpgme_error = GPG_ERR_EOF;
  5.1845 +            break;
  5.1846 +        };
  5.1847 +    } while (gpgme_error != GPG_ERR_EOF);
  5.1848 +
  5.1849 +    _session->gpgme_op_keylist_end(_session->ctx);
  5.1850 +    *keylist = _keylist;
  5.1851 +    return PEP_STATUS_OK;
  5.1852 +}
  5.1853 +
  5.1854 +PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  5.1855 +{
  5.1856 +	pEpSession *_session = (pEpSession *) session;
  5.1857 +	gpgme_error_t gpgme_error;
  5.1858 +
  5.1859 +    gpgme_error = _session->gpgme_op_export(_session->ctx, pattern,
  5.1860 +            GPGME_EXPORT_MODE_EXTERN, NULL);
  5.1861 +    assert(gpgme_error != GPG_ERR_INV_VALUE);
  5.1862 +    if (gpgme_error == GPG_ERR_NO_ERROR)
  5.1863 +        return PEP_STATUS_OK;
  5.1864 +    else
  5.1865 +        return PEP_CANNOT_SEND_KEY;
  5.1866 +}
  5.1867 +
  5.1868 +void pEp_free(void *p)
  5.1869 +{
  5.1870 +    free(p);
  5.1871 +}
  5.1872 +
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/src/pEpEngine.h	Wed Jun 25 18:44:58 2014 +0200
     6.3 @@ -0,0 +1,583 @@
     6.4 +#ifdef __cplusplus
     6.5 +extern "C" {
     6.6 +#endif
     6.7 +
     6.8 +#include <stdint.h>
     6.9 +#include <stdbool.h>
    6.10 +
    6.11 +#ifdef WIN32
    6.12 +#ifdef _EXPORT_PEP_ENGINE_DLL
    6.13 +#define DYNAMIC_API __declspec(dllexport)
    6.14 +#else
    6.15 +#define DYNAMIC_API __declspec(dllimport)
    6.16 +#endif
    6.17 +#else
    6.18 +#define DYNAMIC_API
    6.19 +#endif
    6.20 +
    6.21 +
    6.22 +// pEp Engine API
    6.23 +
    6.24 +//  caveat:
    6.25 +//      Unicode data has to be normalized to NFC before calling
    6.26 +//      UTF-8 strings are UTF-8 encoded C strings (zero terminated)
    6.27 +
    6.28 +
    6.29 +typedef void * PEP_SESSION;
    6.30 +
    6.31 +typedef enum {
    6.32 +	PEP_STATUS_OK									= 0,
    6.33 +
    6.34 +	PEP_INIT_CANNOT_LOAD_GPGME						= 0x0110,
    6.35 +	PEP_INIT_GPGME_INIT_FAILED						= 0x0111,
    6.36 +
    6.37 +	PEP_INIT_SQLITE3_WITHOUT_MUTEX					= 0x0120,
    6.38 +	PEP_INIT_CANNOT_OPEN_DB							= 0x0121,
    6.39 +	PEP_INIT_CANNOT_OPEN_SYSTEM_DB					= 0x0122,
    6.40 +	
    6.41 +	PEP_KEY_NOT_FOUND						        = 0x0201,
    6.42 +	PEP_KEY_HAS_AMBIG_NAME					        = 0x0202,
    6.43 +	PEP_GET_KEY_FAILED						        = 0x0203,
    6.44 +	
    6.45 +	PEP_CANNOT_FIND_IDENTITY						= 0x0301,
    6.46 +	PEP_CANNOT_SET_PERSON							= 0x0381,
    6.47 +	PEP_CANNOT_SET_PGP_KEYPAIR						= 0x0382,
    6.48 +	PEP_CANNOT_SET_IDENTITY							= 0x0383,
    6.49 +	
    6.50 +	PEP_UNENCRYPTED									= 0x0400,
    6.51 +	PEP_VERIFIED									= 0x0401,
    6.52 +	PEP_DECRYPTED									= 0x0402,
    6.53 +	PEP_DECRYPTED_AND_VERIFIED						= 0x0403,
    6.54 +	PEP_DECRYPT_WRONG_FORMAT						= 0x0404,
    6.55 +	PEP_DECRYPT_NO_KEY								= 0x0405,
    6.56 +	PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH			= 0x0406,
    6.57 +    PEP_VERIFY_NO_KEY                               = 0x0407,
    6.58 +    PEP_VERIFIED_AND_TRUSTED                        = 0x0408,
    6.59 +	PEP_CANNOT_DECRYPT_UNKNOWN						= 0x04ff,
    6.60 +
    6.61 +	PEP_SAFEWORD_NOT_FOUND							= 0x0501,
    6.62 +
    6.63 +    PEP_CANNOT_CREATE_KEY                           = 0x0601,
    6.64 +    PEP_CANNOT_SEND_KEY                             = 0x0602,
    6.65 +
    6.66 +	PEP_COMMIT_FAILED								= 0xff01,
    6.67 +
    6.68 +    PEP_ILLEGAL_VALUE                               = -4,
    6.69 +    PEP_BUFFER_TOO_SMALL                            = -3,
    6.70 +	PEP_OUT_OF_MEMORY								= -2,
    6.71 +	PEP_UNKNOWN_ERROR								= -1
    6.72 +} PEP_STATUS;
    6.73 +
    6.74 +
    6.75 +// INIT_STATUS init() - initialize pEpEngine for a thread
    6.76 +//
    6.77 +//  parameters:
    6.78 +//		session (out)	init() allocates session memory and returns a pointer
    6.79 +//		                as a handle
    6.80 +//
    6.81 +//  return value:
    6.82 +//		PEP_STATUS_OK = 0					if init() succeeds
    6.83 +//		PEP_INIT_SQLITE3_WITHOUT_MUTEX		if SQLite3 was compiled with
    6.84 +//		                                    SQLITE_THREADSAFE 0
    6.85 +//		PEP_INIT_CANNOT_LOAD_GPGME			if libgpgme.dll cannot be found
    6.86 +//		PEP_INIT_GPGME_INIT_FAILED			if GPGME init fails
    6.87 +//		PEP_INIT_CANNOT_OPEN_DB				if user's management db cannot be
    6.88 +//		                                    opened
    6.89 +//		PEP_INIT_CANNOT_OPEN_SYSTEM_DB		if system's management db cannot be
    6.90 +//		                                    opened
    6.91 +//
    6.92 +//  caveat:
    6.93 +//      the pointer is valid only if the return value is PEP_STATUS_OK
    6.94 +//      in other case a NULL pointer will be returned; a valid handle must
    6.95 +//      be released using release() when it's no longer needed
    6.96 +
    6.97 +DYNAMIC_API PEP_STATUS init(PEP_SESSION *session);
    6.98 +
    6.99 +
   6.100 +// void release() - release thread session handle
   6.101 +//
   6.102 +//  parameters:
   6.103 +//		session (in)	session handle to release
   6.104 +
   6.105 +DYNAMIC_API void release(PEP_SESSION session);
   6.106 +
   6.107 +
   6.108 +typedef struct _stringlist_t {
   6.109 +    char *value;
   6.110 +    struct _stringlist_t *next;
   6.111 +} stringlist_t;
   6.112 +
   6.113 +
   6.114 +// new_stringlist() - allocate a new stringlist
   6.115 +//
   6.116 +//  parameters:
   6.117 +//      value (in)        initial value as C string or NULL for empty list
   6.118 +//
   6.119 +//  return value:
   6.120 +//      pointer to stringlist_t object or NULL if out of memory
   6.121 +//
   6.122 +//  caveat:
   6.123 +//      the value is being copied before being added to the list
   6.124 +//      the original string is still being owned by the caller
   6.125 +
   6.126 +DYNAMIC_API stringlist_t *new_stringlist(const char *value);
   6.127 +
   6.128 +
   6.129 +// stringlist_add() - add key to stringlist
   6.130 +//
   6.131 +//  parameters:
   6.132 +//      stringlist (in)     stringlist struct or NULL to create a new one
   6.133 +//      value (in)          value as C string
   6.134 +//
   6.135 +//  return value:
   6.136 +//      pointer to last element in stringlist or NULL if out of memory
   6.137 +//
   6.138 +//  caveat:
   6.139 +//      the value is being copied before being added to the list
   6.140 +//      the original string is still being owned by the caller
   6.141 +
   6.142 +DYNAMIC_API stringlist_t *stringlist_add(stringlist_t *stringlist, const char *value);
   6.143 +
   6.144 +
   6.145 +// stringlist_length() - get length of stringlist
   6.146 +//
   6.147 +//  parameters:
   6.148 +//      stringlist (in)     stringlist struct to determine length of
   6.149 +//
   6.150 +//  return value:
   6.151 +//      length of stringlist in number of elements
   6.152 +
   6.153 +DYNAMIC_API int stringlist_length(const stringlist_t *stringlist);
   6.154 +
   6.155 +
   6.156 +// free_stringlist() - free memory occupied by stringlist
   6.157 +//
   6.158 +//  parameters:
   6.159 +//      stringlist (in)    stringlist to free
   6.160 +
   6.161 +DYNAMIC_API void free_stringlist(stringlist_t *stringlist);
   6.162 +
   6.163 +
   6.164 +// decrypt_and_verify() - decrypt and/or verify a message
   6.165 +//
   6.166 +//	parameters:
   6.167 +//		session (in)	session handle
   6.168 +//		ctext (in)		cipher text to decrypt and/or verify
   6.169 +//		csize (in)		size of cipher text
   6.170 +//		ptext (out)		pointer to internal buffer with plain text
   6.171 +//		psize (out)		size of plain text
   6.172 +//		keylist (out)	array of key ids which where used to encrypt or NULL on
   6.173 +//		                error
   6.174 +//
   6.175 +//	return value:
   6.176 +//		PEP_UNENCRYPTED				message was unencrypted and not signed
   6.177 +//		PEP_VERIFIED				message was unencrypted, signature matches
   6.178 +//		PEP_DECRYPTED				message is decrypted now, no signature
   6.179 +//		PEP_DECRYPTED_AND_VERIFIED	message is decrypted now and verified
   6.180 +//		PEP_DECRYPT_WRONG_FORMAT	message has wrong format to handle
   6.181 +//		PEP_DECRYPT_NO_KEY			key not available to decrypt and/or verify
   6.182 +//		PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH	wrong signature
   6.183 +//
   6.184 +//	caveat:
   6.185 +//	    the ownerships of ptext as well as keylist are going to the caller
   6.186 +//	    the caller must use free() (or an Windoze pEp_free()) and
   6.187 +//	    free_stringlist() to free them
   6.188 +
   6.189 +DYNAMIC_API PEP_STATUS decrypt_and_verify(
   6.190 +        PEP_SESSION session, const char *ctext, size_t csize,
   6.191 +        char **ptext, size_t *psize, stringlist_t **keylist
   6.192 +    );
   6.193 +
   6.194 +
   6.195 +// verify_text() - verfy plain text with a digital signature
   6.196 +//
   6.197 +//  parameters:
   6.198 +//      session (in)    session handle
   6.199 +//      text (in)       text to verify
   6.200 +//      size (in)       size of text
   6.201 +//      signature (in)  signature text
   6.202 +//      sig_size (in)   size of signature
   6.203 +//		keylist (out)	array of key ids which where used to encrypt or NULL on
   6.204 +//		                error
   6.205 +//
   6.206 +//  return value:
   6.207 +//		PEP_VERIFIED				message was unencrypted, signature matches
   6.208 +//		PEP_DECRYPT_NO_KEY			key not available to decrypt and/or verify
   6.209 +//		PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH	wrong signature
   6.210 +
   6.211 +DYNAMIC_API PEP_STATUS verify_text(
   6.212 +        PEP_SESSION session, const char *text, size_t size,
   6.213 +        const char *signature, size_t sig_size, stringlist_t **keylist
   6.214 +    );
   6.215 +
   6.216 +
   6.217 +// encrypt_and_sign() - encrypt and sign a message
   6.218 +//
   6.219 +//	parameters:
   6.220 +//		session (in)	session handle
   6.221 +//		keylist (in)	array of key ids to encrypt with as C strings
   6.222 +//		ptext (in)		plain text to decrypt and/or verify
   6.223 +//		psize (in)		size of plain text
   6.224 +//		ctext (out)		pointer to internal buffer with cipher text
   6.225 +//		csize (out)		size of cipher text
   6.226 +//
   6.227 +//	return value:
   6.228 +//		PEP_STATUS_OK = 0				encryption and signing succeeded
   6.229 +//		PEP_KEY_NOT_FOUND	            at least one of the receipient keys
   6.230 +//		                                could not be found
   6.231 +//		PEP_KEY_HAS_AMBIG_NAME          at least one of the receipient keys has
   6.232 +//		                                an ambiguous name
   6.233 +//		PEP_GET_KEY_FAILED		        cannot retrieve key
   6.234 +//
   6.235 +//	caveat:
   6.236 +//	    the ownership of ctext is going to the caller
   6.237 +//      the caller is responsible to free() it (on Windoze use pEp_free())
   6.238 +
   6.239 +DYNAMIC_API PEP_STATUS encrypt_and_sign(
   6.240 +        PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   6.241 +        size_t psize, char **ctext, size_t *csize
   6.242 +    );
   6.243 +
   6.244 +
   6.245 +// log_event() - log a user defined event defined by UTF-8 encoded strings into
   6.246 +// management log
   6.247 +//
   6.248 +//	parameters:
   6.249 +//		session (in)		session handle
   6.250 +//		title (in)			C string with event name
   6.251 +//		entity (in)			C string with name of entity which is logging
   6.252 +//		description (in)	C string with long description for event or NULL if
   6.253 +//		                    omitted
   6.254 +//		comment (in)		C string with user defined comment or NULL if
   6.255 +//		                    omitted
   6.256 +//
   6.257 +//	return value:
   6.258 +//	    PEP_STATUS_OK       log entry created
   6.259 +
   6.260 +DYNAMIC_API PEP_STATUS log_event(
   6.261 +        PEP_SESSION session, const char *title, const char *entity,
   6.262 +        const char *description, const char *comment
   6.263 +    );
   6.264 +
   6.265 +
   6.266 +// safeword() - get the corresponding safeword for a 16 bit value
   6.267 +//
   6.268 +//	parameters:
   6.269 +//		session (in)		    session handle
   6.270 +//		value (in)			    value to find a safeword for
   6.271 +//		lang (in)			    C string with ISO 3166-1 ALPHA-2 language code
   6.272 +//		word (out)			    pointer to C string with safeword UTF-8 encoded
   6.273 +//							    NULL if language is not supported or safeword
   6.274 +//							    wordlist is damaged or unavailable
   6.275 +//		wsize (out)			    length of safeword
   6.276 +//
   6.277 +//	return value:
   6.278 +//	    PEP_STATUS_OK           safeword retrieved
   6.279 +//	    PEP_SAFEWORD_NOT_FOUND  safeword not found
   6.280 +//
   6.281 +//	caveat:
   6.282 +//		the word pointer goes to the ownership of the caller
   6.283 +//      the caller is responsible to free() it (on Windoze use pEp_free())
   6.284 +
   6.285 +DYNAMIC_API PEP_STATUS safeword(
   6.286 +            PEP_SESSION session, uint16_t value, const char *lang,
   6.287 +            char **word, size_t *wsize
   6.288 +        );
   6.289 +
   6.290 +
   6.291 +// safewords() - get safewords for a string of hex values of a fingerprint
   6.292 +//
   6.293 +//	parameters:
   6.294 +//		session (in)		session handle
   6.295 +//		fingerprint (in)	C string with hex values to find safewords for
   6.296 +//		lang (in)			C string with ISO 3166-1 ALPHA-2 language code
   6.297 +//		words (out)			pointer to C string with safewords UTF-8 encoded,
   6.298 +//		                    separated by a blank each
   6.299 +//							NULL if language is not supported or safeword
   6.300 +//							wordlist is damaged or unavailable
   6.301 +//		wsize (out)			length of safewords string
   6.302 +//		max_words (in)		only generate a string with max_words;
   6.303 +//							if max_words == 0 there is no such limit
   6.304 +//
   6.305 +//	return value:
   6.306 +//	    PEP_STATUS_OK           safewords retrieved
   6.307 +//      PEP_OUT_OF_MEMORY       out of memory
   6.308 +//	    PEP_SAFEWORD_NOT_FOUND  at least one safeword not found
   6.309 +//
   6.310 +//	caveat:
   6.311 +//		the word pointer goes to the ownership of the caller
   6.312 +//      the caller is responsible to free() it (on Windoze use pEp_free())
   6.313 +//
   6.314 +//  DON'T USE THIS FUNCTION FROM HIGH LEVEL LANGUAGES!
   6.315 +//
   6.316 +//  Better implement a simple one in the adapter yourself using safeword(), and
   6.317 +//  return a list of safewords.
   6.318 +//  This function is provided for being used by C and C++ programs only.
   6.319 +
   6.320 +DYNAMIC_API PEP_STATUS safewords(
   6.321 +        PEP_SESSION session, const char *fingerprint, const char *lang,
   6.322 +        char **words, size_t *wsize, int max_words
   6.323 +    );
   6.324 +
   6.325 +
   6.326 +typedef enum _PEP_comm_type {
   6.327 +	PEP_ct_unknown = 0,
   6.328 +
   6.329 +	// range 0x01 to 0x0f: no encryption or nothing reasonable
   6.330 +
   6.331 +	PEP_ct_no_encryption = 0x01,                // generic
   6.332 +	PEP_ct_key_too_short = 0x02,                // key too short to talk
   6.333 +                                                // about encryption
   6.334 +    PEP_ct_compromized = 0x0f,                  // known compromized connection
   6.335 +
   6.336 +	// range 0x10 to 0x3f: unconfirmed encryption
   6.337 +
   6.338 +    PEP_ct_unconfirmed_encryption = 0x10,       // generic
   6.339 +	PEP_ct_OpenPGP_1024_RSA_unconfirmed = 0x11,	// RSA 1024 is weak
   6.340 +	PEP_ct_OpenPGP_unconfirmed = 0x3f,          // key at least 2048 bit RSA
   6.341 +                                                // or 1024 bit DSA
   6.342 +
   6.343 +	// range 0x40 to 0x7f: unconfirmed encryption and anonymization
   6.344 +
   6.345 +    PEP_ct_unconfirmed_enc_anon = 0x40,         // generic
   6.346 +	PEP_ct_PEP_unconfirmed = 0x7f,
   6.347 +
   6.348 +	// range 0x80 to 0x8f: reserved
   6.349 +	// range 0x90 to 0xbf: confirmed encryption
   6.350 +
   6.351 +    PEP_ct_confirmed_encryption = 0x90,         // generic
   6.352 +	PEP_ct_OpenPGP_1024_RSA = 0x91, // RSA 1024 is weak
   6.353 +	PEP_ct_OpenPGP = 0xbf, // key at least 2048 bit RSA or 1024 bit DSA
   6.354 +
   6.355 +    // range 0xc0 to 0xff: confirmed encryption and anonymization
   6.356 +
   6.357 +    PEP_ct_confirmed_enc_anon = 0xc0,           // generic
   6.358 +	PEP_ct_pEp = 0xff
   6.359 +} PEP_comm_type;
   6.360 +
   6.361 +typedef struct _pEp_identity {
   6.362 +	size_t struct_size;			// size of whole struct
   6.363 +	char *address;		        // C string with address UTF-8 encoded
   6.364 +	size_t address_size;		// size of address
   6.365 +	char *fpr;			        // C string with fingerprint UTF-8 encoded
   6.366 +	size_t fpr_size;			// size of fingerprint
   6.367 +	char *user_id;		        // C string with user ID UTF-8 encoded
   6.368 +	size_t user_id_size;		// size of user ID
   6.369 +	char *username;		        // C string with user name UTF-8 encoded
   6.370 +	size_t username_size;		// size of user name
   6.371 +	PEP_comm_type comm_type;	// type of communication with this ID
   6.372 +    char lang[3];				// language of conversation
   6.373 +                                // ISO 639-1 ALPHA-2, last byte is 0
   6.374 +    bool me;                    // if this is the local user herself/himself
   6.375 +} pEp_identity;
   6.376 +
   6.377 +
   6.378 +// new_identity() - allocate memory and set the string and size fields
   6.379 +//
   6.380 +//  parameters:
   6.381 +//      address (in)        UTF-8 string or NULL 
   6.382 +//      fpr (in)            UTF-8 string or NULL 
   6.383 +//      user_id (in)        UTF-8 string or NULL 
   6.384 +//      username (in)       UTF-8 string or NULL 
   6.385 +//
   6.386 +//  return value:
   6.387 +//      pEp_identity struct with correct size values or NULL if out of memory
   6.388 +//
   6.389 +//  caveat:
   6.390 +//      the strings are copied; the original strings are still being owned by
   6.391 +//      the caller
   6.392 +
   6.393 +DYNAMIC_API pEp_identity *new_identity(
   6.394 +        const char *address, const char *fpr, const char *user_id,
   6.395 +        const char *username
   6.396 +    );
   6.397 +
   6.398 +
   6.399 +// free_identity() - free all memory being occupied by a pEp_identity struct
   6.400 +//
   6.401 +//  parameters:
   6.402 +//      identity (in)       struct to release
   6.403 +//
   6.404 +//  caveat:
   6.405 +//      not only the struct but also all string memory referenced by the
   6.406 +//      struct is being freed; all pointers inside are invalid afterwards
   6.407 +
   6.408 +DYNAMIC_API void free_identity(pEp_identity *identity);
   6.409 +
   6.410 +
   6.411 +// get_identity() - get identity information
   6.412 +//
   6.413 +//	parameters:
   6.414 +//		session (in)		session handle
   6.415 +//		address (in)		C string with communication address, UTF-8 encoded
   6.416 +//		identity (out)		pointer to pEp_identity structure with results or
   6.417 +//		                    NULL if failure
   6.418 +//
   6.419 +//	caveat:
   6.420 +//	    the address string is being copied; the original string remains in the
   6.421 +//	    ownership of the caller
   6.422 +//		the resulting pEp_identity structure goes to the ownership of the
   6.423 +//		caller and has to be freed with free_identity() when not in use any
   6.424 +//		more
   6.425 +
   6.426 +DYNAMIC_API PEP_STATUS get_identity(
   6.427 +        PEP_SESSION session, const char *address,
   6.428 +        pEp_identity **identity
   6.429 +    );
   6.430 +
   6.431 +
   6.432 +// set_identity() - set identity information
   6.433 +//
   6.434 +//	parameters:
   6.435 +//		session (in)		session handle
   6.436 +//		identity (in)		pointer to pEp_identity structure
   6.437 +//
   6.438 +//	return value:
   6.439 +//		PEP_STATUS_OK = 0			    encryption and signing succeeded
   6.440 +//		PEP_CANNOT_SET_PERSON		    writing to table person failed
   6.441 +//		PEP_CANNOT_SET_PGP_KEYPAIR	    writing to table pgp_keypair failed
   6.442 +//		PEP_CANNOT_SET_IDENTITY		    writing to table identity failed
   6.443 +//		PEP_COMMIT_FAILED			    SQL commit failed
   6.444 +//
   6.445 +//	caveat:
   6.446 +//		in the identity structure you need to set the const char * fields to
   6.447 +//		UTF-8 C strings
   6.448 +//		the size fields are ignored
   6.449 +
   6.450 +DYNAMIC_API PEP_STATUS set_identity(
   6.451 +        PEP_SESSION session, const pEp_identity *identity
   6.452 +    );
   6.453 +
   6.454 +
   6.455 +// generate_keypair() - generate a new key pair and add it to the key ring
   6.456 +//
   6.457 +//  parameters:
   6.458 +//      session (in)            session handle
   6.459 +//		identity (inout)	    pointer to pEp_identity structure
   6.460 +//
   6.461 +//	return value:
   6.462 +//		PEP_STATUS_OK = 0	    encryption and signing succeeded
   6.463 +//		PEP_ILLEGAL_VALUE       illegal values for identity fields given
   6.464 +//		PEP_CANNOT_CREATE_KEY   key engine is on strike
   6.465 +//
   6.466 +//  caveat:
   6.467 +//      address and username fields must be set to UTF-8 strings
   6.468 +//      the fpr field must be set to NULL
   6.469 +//
   6.470 +//      this function allocates a string and sets set fpr field of identity
   6.471 +//      the caller is responsible to call free() for that string or use
   6.472 +//      free_identity() on the struct
   6.473 +
   6.474 +DYNAMIC_API PEP_STATUS generate_keypair(
   6.475 +        PEP_SESSION session, pEp_identity *identity
   6.476 +    );
   6.477 +
   6.478 +
   6.479 +// delete_keypair() - delete a public key or a key pair from the key ring
   6.480 +//
   6.481 +//  parameters:
   6.482 +//      session (in)            session handle
   6.483 +//      fpr (in)                C string with key id or fingerprint of the
   6.484 +//                              public key
   6.485 +//
   6.486 +//  return value:
   6.487 +//      PEP_STATUS_OK = 0       key was successfully deleted
   6.488 +//      PEP_KEY_NOT_FOUND       key not found
   6.489 +//      PEP_ILLEGAL_VALUE       not a valid key id or fingerprint
   6.490 +//      PEP_KEY_HAS_AMBIG_NAME  fpr does not uniquely identify a key
   6.491 +//      PEP_OUT_OF_MEMORY       out of memory
   6.492 +
   6.493 +DYNAMIC_API PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr);
   6.494 +
   6.495 +
   6.496 +// import_key() - import key from data
   6.497 +//
   6.498 +//  parameters:
   6.499 +//      session (in)            session handle
   6.500 +//      key_data (in)           key data, i.e. ASCII armored OpenPGP key
   6.501 +//      size (in)               amount of data to handle
   6.502 +//
   6.503 +//  return value:
   6.504 +//      PEP_STATUS_OK = 0       key was successfully imported
   6.505 +//      PEP_OUT_OF_MEMORY       out of memory
   6.506 +//      PEP_ILLEGAL_VALUE       there is no key data to import
   6.507 +
   6.508 +DYNAMIC_API PEP_STATUS import_key(PEP_SESSION session, const char *key_data, size_t size);
   6.509 +
   6.510 +
   6.511 +// export_key() - export ascii armored key
   6.512 +//
   6.513 +//  parameters:
   6.514 +//      session (in)            session handle
   6.515 +//      fpr (in)                key id or fingerprint of key
   6.516 +//      key_data (out)          ASCII armored OpenPGP key
   6.517 +//      size (out)               amount of data to handle
   6.518 +//
   6.519 +//  return value:
   6.520 +//      PEP_STATUS_OK = 0       key was successfully exported
   6.521 +//      PEP_OUT_OF_MEMORY       out of memory
   6.522 +//      PEP_KEY_NOT_FOUND       key not found
   6.523 +//
   6.524 +//  caveat:
   6.525 +//      the key_data goes to the ownership of the caller
   6.526 +//      the caller is responsible to free() it (on Windoze use pEp_free())
   6.527 +
   6.528 +DYNAMIC_API PEP_STATUS export_key(
   6.529 +        PEP_SESSION session, const char *fpr, char **key_data, size_t *size
   6.530 +    );
   6.531 +
   6.532 +
   6.533 +// recv_key() - update key(s) from keyserver
   6.534 +//
   6.535 +//  parameters:
   6.536 +//      session (in)            session handle
   6.537 +//      pattern (in)            key id, user id or address to search for as
   6.538 +//                              UTF-8 string
   6.539 +
   6.540 +DYNAMIC_API PEP_STATUS recv_key(PEP_SESSION session, const char *pattern);
   6.541 +
   6.542 +
   6.543 +// find_keys() - find keys in keyring
   6.544 +//
   6.545 +//  parameters:
   6.546 +//      session (in)            session handle
   6.547 +//      pattern (in)            key id, user id or address to search for as
   6.548 +//                              UTF-8 string
   6.549 +//      keylist (out)           list of fingerprints found or NULL on error
   6.550 +//
   6.551 +//  caveat:
   6.552 +//	    the ownerships of keylist isgoing to the caller
   6.553 +//	    the caller must use free_stringlist() to free it
   6.554 +
   6.555 +
   6.556 +DYNAMIC_API PEP_STATUS find_keys(
   6.557 +        PEP_SESSION session, const char *pattern, stringlist_t **keylist
   6.558 +    );
   6.559 +
   6.560 +
   6.561 +// send_key() - send key(s) to keyserver
   6.562 +//
   6.563 +//  parameters:
   6.564 +//      session (in)            session handle
   6.565 +//      pattern (in)            key id, user id or address to search for as
   6.566 +//                              UTF-8 string
   6.567 +
   6.568 +DYNAMIC_API PEP_STATUS send_key(PEP_SESSION session, const char *pattern);
   6.569 +
   6.570 +
   6.571 +// pEp_free() - free memory allocated by pEp engine
   6.572 +//
   6.573 +//  parameters:
   6.574 +//      p (in)                  pointer to free
   6.575 +//
   6.576 +//  The reason for this function is that heap management can be a pretty
   6.577 +//  complex task with Windoze. This free() version calls the free()
   6.578 +//  implementation of the C runtime library which was used to build pEp engine,
   6.579 +//  so you're using the correct heap. For more information, see:
   6.580 +//  <http://msdn.microsoft.com/en-us/library/windows/desktop/aa366711(v=vs.85).aspx>
   6.581 +
   6.582 +DYNAMIC_API void pEp_free(void *p);
   6.583 +
   6.584 +#ifdef __cplusplus
   6.585 +}
   6.586 +#endif
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/src/platform_windows.cpp	Wed Jun 25 18:44:58 2014 +0200
     7.3 @@ -0,0 +1,189 @@
     7.4 +// Windows platform specifica
     7.5 +
     7.6 +#define WIN32_LEAN_AND_MEAN
     7.7 +#ifndef UNICODE
     7.8 +#define UNICODE
     7.9 +#endif
    7.10 +#define _WIN32_WINNT 0x0600
    7.11 +
    7.12 +#include <windows.h>
    7.13 +#include <assert.h>
    7.14 +#include <string>
    7.15 +#include <stdexcept>
    7.16 +#include "platform_windows.h"
    7.17 +
    7.18 +#ifndef WC_ERR_INVALID_CHARS
    7.19 +#define WC_ERR_INVALID_CHARS      0x00000080  // error for invalid chars
    7.20 +#endif
    7.21 +
    7.22 +using namespace std;
    7.23 +
    7.24 +static string utf8_string(wstring wstr) {
    7.25 +    string result;
    7.26 +
    7.27 +    if (wstr.length()) {
    7.28 +        int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS,
    7.29 +                wstr.c_str(), -1, NULL, 0, NULL, NULL);
    7.30 +        assert(size);
    7.31 +        if (size) {
    7.32 +            char *buf = new char[size];
    7.33 +            WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wstr.c_str(),
    7.34 +                    -1, buf, size, NULL, NULL);
    7.35 +            result = buf;
    7.36 +            delete[] buf;
    7.37 +        } else
    7.38 +            throw out_of_range("input wstring is not valid"
    7.39 +                    " while converting UTF-16 to UTF-8.");
    7.40 +    }
    7.41 +
    7.42 +    return result;
    7.43 +}
    7.44 +
    7.45 +static wstring utf16_string(string str) {
    7.46 +    wstring result;
    7.47 +
    7.48 +    if (str.length()) {
    7.49 +        int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
    7.50 +                str.c_str(), -1, NULL, 0);
    7.51 +        assert(size);
    7.52 +        if (size) {
    7.53 +            wchar_t * buf = new wchar_t[size];
    7.54 +            MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), -1,
    7.55 +                    buf, size);
    7.56 +            result = buf;
    7.57 +            delete[] buf;
    7.58 +        } else
    7.59 +            throw out_of_range("input string is not valid"
    7.60 +                    " while converting UTF-8 to UTF-16.");
    7.61 +    }
    7.62 +
    7.63 +    return result;
    7.64 +}
    7.65 +
    7.66 +static bool readRegistryString(
    7.67 +        HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueName, LPTSTR lpResult,
    7.68 +        DWORD dwSize, LPCTSTR lpDefault
    7.69 +    )
    7.70 +{
    7.71 +    assert(lpResult);
    7.72 +
    7.73 +	HKEY theKey;
    7.74 +	DWORD type;
    7.75 +	DWORD bytesCopied = dwSize;
    7.76 +	HRESULT result;
    7.77 +
    7.78 +	result = RegOpenKeyEx(hKey, lpSubKey, 0, KEY_READ, &theKey);
    7.79 +	if (result != ERROR_SUCCESS) {
    7.80 +		if (lpDefault) {
    7.81 +			wcsncpy_s(lpResult, dwSize, lpDefault, _TRUNCATE);
    7.82 +			return true;
    7.83 +		}
    7.84 +		else
    7.85 +			return false;
    7.86 +	}
    7.87 +
    7.88 +	result = RegQueryValueEx(theKey, lpValueName, NULL, &type,
    7.89 +            (LPBYTE) lpResult, &bytesCopied);
    7.90 +    if (result != ERROR_SUCCESS || (type != REG_EXPAND_SZ && type != REG_SZ)) {
    7.91 +		if (lpDefault) {
    7.92 +			wcsncpy_s(lpResult, dwSize, lpDefault, _TRUNCATE);
    7.93 +			RegCloseKey(theKey);
    7.94 +			return true;
    7.95 +		}
    7.96 +		else {
    7.97 +			RegCloseKey(theKey);
    7.98 +			return false;
    7.99 +		}
   7.100 +	}
   7.101 +
   7.102 +	RegCloseKey(theKey);
   7.103 +	return true;
   7.104 +}
   7.105 +
   7.106 +static const DWORD PATH_BUF_SIZE = 32768;
   7.107 +
   7.108 +static inline string managementPath(const char *file_path, const char *file_name)
   7.109 +{
   7.110 +    string path;
   7.111 +	static TCHAR tPath[PATH_BUF_SIZE];
   7.112 +
   7.113 +    DWORD length = ExpandEnvironmentStringsW(utf16_string(file_path).c_str(),
   7.114 +            tPath, PATH_BUF_SIZE);
   7.115 +	assert(length);
   7.116 +    if (length == 0)
   7.117 +        throw bad_alloc();
   7.118 +
   7.119 +	CreateDirectory(tPath, NULL);
   7.120 +	DWORD error = GetLastError();
   7.121 +	assert(error == 0 || error == ERROR_ALREADY_EXISTS);
   7.122 +
   7.123 +	path = utf8_string(tPath);
   7.124 +	path += "\\";
   7.125 +	path += file_name;
   7.126 +
   7.127 +	return path;
   7.128 +}
   7.129 +
   7.130 +extern "C" {
   7.131 +
   7.132 +void *dlopen(const char *filename, int flag) {
   7.133 +	static TCHAR path[PATH_BUF_SIZE];
   7.134 +
   7.135 +    assert(filename);
   7.136 +	assert(flag == RTLD_LAZY); // only lazy binding is implemented
   7.137 +
   7.138 +    bool result = readRegistryString(HKEY_LOCAL_MACHINE,
   7.139 +            TEXT("SOFTWARE\\GNU\\GnuPG"), TEXT("Install Directory"), path,
   7.140 +            PATH_BUF_SIZE, NULL);
   7.141 +	assert(result);
   7.142 +	if (!result)
   7.143 +		return NULL;
   7.144 +
   7.145 +    SetDllDirectory(TEXT(""));
   7.146 +    BOOL _result = SetDllDirectory(path);
   7.147 +    assert(_result != 0);
   7.148 +    if (_result == 0)
   7.149 +        return NULL;
   7.150 +
   7.151 +	HMODULE module = LoadLibrary(utf16_string(filename).c_str());
   7.152 +    SetDllDirectory(NULL);
   7.153 +	if (module == NULL)
   7.154 +		return NULL;
   7.155 +	else
   7.156 +		return (void *) module;
   7.157 +}
   7.158 +
   7.159 +int dlclose(void *handle) {
   7.160 +	if (FreeLibrary((HMODULE) handle))
   7.161 +		return 0;
   7.162 +	else
   7.163 +		return 1;
   7.164 +}
   7.165 +
   7.166 +void *dlsym(void *handle, const char *symbol) {
   7.167 +	return (void *) (intptr_t) GetProcAddress((HMODULE) handle, symbol);
   7.168 +}
   7.169 +
   7.170 +const char *windoze_local_db() {
   7.171 +	static string path;
   7.172 +	if (path.length() == 0)
   7.173 +        path = managementPath("%LOCALAPPDATA%\\pEp", "management.db");
   7.174 +    return path.c_str();
   7.175 +}
   7.176 +
   7.177 +const char *windoze_system_db() {
   7.178 +	static string path;
   7.179 +	if (path.length() == 0)
   7.180 +		path = managementPath("%ALLUSERSPROFILE%\\pEp", "system.db");
   7.181 +    return path.c_str();
   7.182 +}
   7.183 +
   7.184 +const char *gpg_conf()
   7.185 +{
   7.186 +    static string path;
   7.187 +    if (path.length() == 0)
   7.188 +        path = managementPath("%APPDATA%\\gnupg", "gpg.conf");
   7.189 +    return path.c_str();
   7.190 +}
   7.191 +
   7.192 +} // "C"
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/src/platform_windows.h	Wed Jun 25 18:44:58 2014 +0200
     8.3 @@ -0,0 +1,29 @@
     8.4 +#pragma once
     8.5 +
     8.6 +// Windows platform specifica
     8.7 +
     8.8 +#define RTLD_LAZY 1
     8.9 +#ifndef strdup
    8.10 +#define strdup _strdup
    8.11 +#endif
    8.12 +#ifndef snprintf
    8.13 +#define snprintf _snprintf
    8.14 +#endif
    8.15 +#define _CRT_NONSTDC_NO_DEPRECATE
    8.16 +#define _CRT_SECURE_NO_WARNINGS
    8.17 +
    8.18 +#ifdef __cplusplus
    8.19 +extern "C" {
    8.20 +#endif
    8.21 +
    8.22 +void *dlopen(const char *filename, int flag);
    8.23 +int dlclose(void *handle);
    8.24 +void *dlsym(void *handle, const char *symbol);
    8.25 +
    8.26 +const char *windoze_local_db(void);
    8.27 +const char *windoze_system_db(void);
    8.28 +const char *gpg_conf(void);
    8.29 +
    8.30 +#ifdef __cplusplus
    8.31 +}
    8.32 +#endif
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/src/sqlite3.c	Wed Jun 25 18:44:58 2014 +0200
     9.3 @@ -0,0 +1,145295 @@
     9.4 +/******************************************************************************
     9.5 +** This file is an amalgamation of many separate C source files from SQLite
     9.6 +** version 3.8.2.  By combining all the individual C code files into this 
     9.7 +** single large file, the entire code can be compiled as a single translation
     9.8 +** unit.  This allows many compilers to do optimizations that would not be
     9.9 +** possible if the files were compiled separately.  Performance improvements
    9.10 +** of 5% or more are commonly seen when SQLite is compiled as a single
    9.11 +** translation unit.
    9.12 +**
    9.13 +** This file is all you need to compile SQLite.  To use SQLite in other
    9.14 +** programs, you need this file and the "sqlite3.h" header file that defines
    9.15 +** the programming interface to the SQLite library.  (If you do not have 
    9.16 +** the "sqlite3.h" header file at hand, you will find a copy embedded within
    9.17 +** the text of this file.  Search for "Begin file sqlite3.h" to find the start
    9.18 +** of the embedded sqlite3.h header file.) Additional code files may be needed
    9.19 +** if you want a wrapper to interface SQLite with your choice of programming
    9.20 +** language. The code for the "sqlite3" command-line shell is also in a
    9.21 +** separate file. This file contains only code for the core SQLite library.
    9.22 +*/
    9.23 +#define SQLITE_CORE 1
    9.24 +#define SQLITE_AMALGAMATION 1
    9.25 +#ifndef SQLITE_PRIVATE
    9.26 +# define SQLITE_PRIVATE static
    9.27 +#endif
    9.28 +#ifndef SQLITE_API
    9.29 +# define SQLITE_API
    9.30 +#endif
    9.31 +/************** Begin file sqlite3.h *****************************************/
    9.32 +/*
    9.33 +** 2001 September 15
    9.34 +**
    9.35 +** The author disclaims copyright to this source code.  In place of
    9.36 +** a legal notice, here is a blessing:
    9.37 +**
    9.38 +**    May you do good and not evil.
    9.39 +**    May you find forgiveness for yourself and forgive others.
    9.40 +**    May you share freely, never taking more than you give.
    9.41 +**
    9.42 +*************************************************************************
    9.43 +** This header file defines the interface that the SQLite library
    9.44 +** presents to client programs.  If a C-function, structure, datatype,
    9.45 +** or constant definition does not appear in this file, then it is
    9.46 +** not a published API of SQLite, is subject to change without
    9.47 +** notice, and should not be referenced by programs that use SQLite.
    9.48 +**
    9.49 +** Some of the definitions that are in this file are marked as
    9.50 +** "experimental".  Experimental interfaces are normally new
    9.51 +** features recently added to SQLite.  We do not anticipate changes
    9.52 +** to experimental interfaces but reserve the right to make minor changes
    9.53 +** if experience from use "in the wild" suggest such changes are prudent.
    9.54 +**
    9.55 +** The official C-language API documentation for SQLite is derived
    9.56 +** from comments in this file.  This file is the authoritative source
    9.57 +** on how SQLite interfaces are suppose to operate.
    9.58 +**
    9.59 +** The name of this file under configuration management is "sqlite.h.in".
    9.60 +** The makefile makes some minor changes to this file (such as inserting
    9.61 +** the version number) and changes its name to "sqlite3.h" as
    9.62 +** part of the build process.
    9.63 +*/
    9.64 +#ifndef _SQLITE3_H_
    9.65 +#define _SQLITE3_H_
    9.66 +#include <stdarg.h>     /* Needed for the definition of va_list */
    9.67 +
    9.68 +/*
    9.69 +** Make sure we can call this stuff from C++.
    9.70 +*/
    9.71 +#if 0
    9.72 +extern "C" {
    9.73 +#endif
    9.74 +
    9.75 +
    9.76 +/*
    9.77 +** Add the ability to override 'extern'
    9.78 +*/
    9.79 +#ifndef SQLITE_EXTERN
    9.80 +# define SQLITE_EXTERN extern
    9.81 +#endif
    9.82 +
    9.83 +#ifndef SQLITE_API
    9.84 +# define SQLITE_API
    9.85 +#endif
    9.86 +
    9.87 +
    9.88 +/*
    9.89 +** These no-op macros are used in front of interfaces to mark those
    9.90 +** interfaces as either deprecated or experimental.  New applications
    9.91 +** should not use deprecated interfaces - they are support for backwards
    9.92 +** compatibility only.  Application writers should be aware that
    9.93 +** experimental interfaces are subject to change in point releases.
    9.94 +**
    9.95 +** These macros used to resolve to various kinds of compiler magic that
    9.96 +** would generate warning messages when they were used.  But that
    9.97 +** compiler magic ended up generating such a flurry of bug reports
    9.98 +** that we have taken it all out and gone back to using simple
    9.99 +** noop macros.
   9.100 +*/
   9.101 +#define SQLITE_DEPRECATED
   9.102 +#define SQLITE_EXPERIMENTAL
   9.103 +
   9.104 +/*
   9.105 +** Ensure these symbols were not defined by some previous header file.
   9.106 +*/
   9.107 +#ifdef SQLITE_VERSION
   9.108 +# undef SQLITE_VERSION
   9.109 +#endif
   9.110 +#ifdef SQLITE_VERSION_NUMBER
   9.111 +# undef SQLITE_VERSION_NUMBER
   9.112 +#endif
   9.113 +
   9.114 +/*
   9.115 +** CAPI3REF: Compile-Time Library Version Numbers
   9.116 +**
   9.117 +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
   9.118 +** evaluates to a string literal that is the SQLite version in the
   9.119 +** format "X.Y.Z" where X is the major version number (always 3 for
   9.120 +** SQLite3) and Y is the minor version number and Z is the release number.)^
   9.121 +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
   9.122 +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
   9.123 +** numbers used in [SQLITE_VERSION].)^
   9.124 +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
   9.125 +** be larger than the release from which it is derived.  Either Y will
   9.126 +** be held constant and Z will be incremented or else Y will be incremented
   9.127 +** and Z will be reset to zero.
   9.128 +**
   9.129 +** Since version 3.6.18, SQLite source code has been stored in the
   9.130 +** <a href="http://www.fossil-scm.org/">Fossil configuration management
   9.131 +** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
   9.132 +** a string which identifies a particular check-in of SQLite
   9.133 +** within its configuration management system.  ^The SQLITE_SOURCE_ID
   9.134 +** string contains the date and time of the check-in (UTC) and an SHA1
   9.135 +** hash of the entire source tree.
   9.136 +**
   9.137 +** See also: [sqlite3_libversion()],
   9.138 +** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   9.139 +** [sqlite_version()] and [sqlite_source_id()].
   9.140 +*/
   9.141 +#define SQLITE_VERSION        "3.8.2"
   9.142 +#define SQLITE_VERSION_NUMBER 3008002
   9.143 +#define SQLITE_SOURCE_ID      "2013-12-06 14:53:30 27392118af4c38c5203a04b8013e1afdb1cebd0d"
   9.144 +
   9.145 +/*
   9.146 +** CAPI3REF: Run-Time Library Version Numbers
   9.147 +** KEYWORDS: sqlite3_version, sqlite3_sourceid
   9.148 +**
   9.149 +** These interfaces provide the same information as the [SQLITE_VERSION],
   9.150 +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
   9.151 +** but are associated with the library instead of the header file.  ^(Cautious
   9.152 +** programmers might include assert() statements in their application to
   9.153 +** verify that values returned by these interfaces match the macros in
   9.154 +** the header, and thus insure that the application is
   9.155 +** compiled with matching library and header files.
   9.156 +**
   9.157 +** <blockquote><pre>
   9.158 +** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
   9.159 +** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
   9.160 +** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
   9.161 +** </pre></blockquote>)^
   9.162 +**
   9.163 +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
   9.164 +** macro.  ^The sqlite3_libversion() function returns a pointer to the
   9.165 +** to the sqlite3_version[] string constant.  The sqlite3_libversion()
   9.166 +** function is provided for use in DLLs since DLL users usually do not have
   9.167 +** direct access to string constants within the DLL.  ^The
   9.168 +** sqlite3_libversion_number() function returns an integer equal to
   9.169 +** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
   9.170 +** a pointer to a string constant whose value is the same as the 
   9.171 +** [SQLITE_SOURCE_ID] C preprocessor macro.
   9.172 +**
   9.173 +** See also: [sqlite_version()] and [sqlite_source_id()].
   9.174 +*/
   9.175 +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   9.176 +SQLITE_API const char *sqlite3_libversion(void);
   9.177 +SQLITE_API const char *sqlite3_sourceid(void);
   9.178 +SQLITE_API int sqlite3_libversion_number(void);
   9.179 +
   9.180 +/*
   9.181 +** CAPI3REF: Run-Time Library Compilation Options Diagnostics
   9.182 +**
   9.183 +** ^The sqlite3_compileoption_used() function returns 0 or 1 
   9.184 +** indicating whether the specified option was defined at 
   9.185 +** compile time.  ^The SQLITE_ prefix may be omitted from the 
   9.186 +** option name passed to sqlite3_compileoption_used().  
   9.187 +**
   9.188 +** ^The sqlite3_compileoption_get() function allows iterating
   9.189 +** over the list of options that were defined at compile time by
   9.190 +** returning the N-th compile time option string.  ^If N is out of range,
   9.191 +** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
   9.192 +** prefix is omitted from any strings returned by 
   9.193 +** sqlite3_compileoption_get().
   9.194 +**
   9.195 +** ^Support for the diagnostic functions sqlite3_compileoption_used()
   9.196 +** and sqlite3_compileoption_get() may be omitted by specifying the 
   9.197 +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
   9.198 +**
   9.199 +** See also: SQL functions [sqlite_compileoption_used()] and
   9.200 +** [sqlite_compileoption_get()] and the [compile_options pragma].
   9.201 +*/
   9.202 +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   9.203 +SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
   9.204 +SQLITE_API const char *sqlite3_compileoption_get(int N);
   9.205 +#endif
   9.206 +
   9.207 +/*
   9.208 +** CAPI3REF: Test To See If The Library Is Threadsafe
   9.209 +**
   9.210 +** ^The sqlite3_threadsafe() function returns zero if and only if
   9.211 +** SQLite was compiled with mutexing code omitted due to the
   9.212 +** [SQLITE_THREADSAFE] compile-time option being set to 0.
   9.213 +**
   9.214 +** SQLite can be compiled with or without mutexes.  When
   9.215 +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
   9.216 +** are enabled and SQLite is threadsafe.  When the
   9.217 +** [SQLITE_THREADSAFE] macro is 0, 
   9.218 +** the mutexes are omitted.  Without the mutexes, it is not safe
   9.219 +** to use SQLite concurrently from more than one thread.
   9.220 +**
   9.221 +** Enabling mutexes incurs a measurable performance penalty.
   9.222 +** So if speed is of utmost importance, it makes sense to disable
   9.223 +** the mutexes.  But for maximum safety, mutexes should be enabled.
   9.224 +** ^The default behavior is for mutexes to be enabled.
   9.225 +**
   9.226 +** This interface can be used by an application to make sure that the
   9.227 +** version of SQLite that it is linking against was compiled with
   9.228 +** the desired setting of the [SQLITE_THREADSAFE] macro.
   9.229 +**
   9.230 +** This interface only reports on the compile-time mutex setting
   9.231 +** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
   9.232 +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
   9.233 +** can be fully or partially disabled using a call to [sqlite3_config()]
   9.234 +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
   9.235 +** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
   9.236 +** sqlite3_threadsafe() function shows only the compile-time setting of
   9.237 +** thread safety, not any run-time changes to that setting made by
   9.238 +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
   9.239 +** is unchanged by calls to sqlite3_config().)^
   9.240 +**
   9.241 +** See the [threading mode] documentation for additional information.
   9.242 +*/
   9.243 +SQLITE_API int sqlite3_threadsafe(void);
   9.244 +
   9.245 +/*
   9.246 +** CAPI3REF: Database Connection Handle
   9.247 +** KEYWORDS: {database connection} {database connections}
   9.248 +**
   9.249 +** Each open SQLite database is represented by a pointer to an instance of
   9.250 +** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
   9.251 +** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
   9.252 +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
   9.253 +** and [sqlite3_close_v2()] are its destructors.  There are many other
   9.254 +** interfaces (such as
   9.255 +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
   9.256 +** [sqlite3_busy_timeout()] to name but three) that are methods on an
   9.257 +** sqlite3 object.
   9.258 +*/
   9.259 +typedef struct sqlite3 sqlite3;
   9.260 +
   9.261 +/*
   9.262 +** CAPI3REF: 64-Bit Integer Types
   9.263 +** KEYWORDS: sqlite_int64 sqlite_uint64
   9.264 +**
   9.265 +** Because there is no cross-platform way to specify 64-bit integer types
   9.266 +** SQLite includes typedefs for 64-bit signed and unsigned integers.
   9.267 +**
   9.268 +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
   9.269 +** The sqlite_int64 and sqlite_uint64 types are supported for backwards
   9.270 +** compatibility only.
   9.271 +**
   9.272 +** ^The sqlite3_int64 and sqlite_int64 types can store integer values
   9.273 +** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
   9.274 +** sqlite3_uint64 and sqlite_uint64 types can store integer values 
   9.275 +** between 0 and +18446744073709551615 inclusive.
   9.276 +*/
   9.277 +#ifdef SQLITE_INT64_TYPE
   9.278 +  typedef SQLITE_INT64_TYPE sqlite_int64;
   9.279 +  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
   9.280 +#elif defined(_MSC_VER) || defined(__BORLANDC__)
   9.281 +  typedef __int64 sqlite_int64;
   9.282 +  typedef unsigned __int64 sqlite_uint64;
   9.283 +#else
   9.284 +  typedef long long int sqlite_int64;
   9.285 +  typedef unsigned long long int sqlite_uint64;
   9.286 +#endif
   9.287 +typedef sqlite_int64 sqlite3_int64;
   9.288 +typedef sqlite_uint64 sqlite3_uint64;
   9.289 +
   9.290 +/*
   9.291 +** If compiling for a processor that lacks floating point support,
   9.292 +** substitute integer for floating-point.
   9.293 +*/
   9.294 +#ifdef SQLITE_OMIT_FLOATING_POINT
   9.295 +# define double sqlite3_int64
   9.296 +#endif
   9.297 +
   9.298 +/*
   9.299 +** CAPI3REF: Closing A Database Connection
   9.300 +**
   9.301 +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
   9.302 +** for the [sqlite3] object.
   9.303 +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
   9.304 +** the [sqlite3] object is successfully destroyed and all associated
   9.305 +** resources are deallocated.
   9.306 +**
   9.307 +** ^If the database connection is associated with unfinalized prepared
   9.308 +** statements or unfinished sqlite3_backup objects then sqlite3_close()
   9.309 +** will leave the database connection open and return [SQLITE_BUSY].
   9.310 +** ^If sqlite3_close_v2() is called with unfinalized prepared statements
   9.311 +** and unfinished sqlite3_backups, then the database connection becomes
   9.312 +** an unusable "zombie" which will automatically be deallocated when the
   9.313 +** last prepared statement is finalized or the last sqlite3_backup is
   9.314 +** finished.  The sqlite3_close_v2() interface is intended for use with
   9.315 +** host languages that are garbage collected, and where the order in which
   9.316 +** destructors are called is arbitrary.
   9.317 +**
   9.318 +** Applications should [sqlite3_finalize | finalize] all [prepared statements],
   9.319 +** [sqlite3_blob_close | close] all [BLOB handles], and 
   9.320 +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
   9.321 +** with the [sqlite3] object prior to attempting to close the object.  ^If
   9.322 +** sqlite3_close_v2() is called on a [database connection] that still has
   9.323 +** outstanding [prepared statements], [BLOB handles], and/or
   9.324 +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
   9.325 +** of resources is deferred until all [prepared statements], [BLOB handles],
   9.326 +** and [sqlite3_backup] objects are also destroyed.
   9.327 +**
   9.328 +** ^If an [sqlite3] object is destroyed while a transaction is open,
   9.329 +** the transaction is automatically rolled back.
   9.330 +**
   9.331 +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
   9.332 +** must be either a NULL
   9.333 +** pointer or an [sqlite3] object pointer obtained
   9.334 +** from [sqlite3_open()], [sqlite3_open16()], or
   9.335 +** [sqlite3_open_v2()], and not previously closed.
   9.336 +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
   9.337 +** argument is a harmless no-op.
   9.338 +*/
   9.339 +SQLITE_API int sqlite3_close(sqlite3*);
   9.340 +SQLITE_API int sqlite3_close_v2(sqlite3*);
   9.341 +
   9.342 +/*
   9.343 +** The type for a callback function.
   9.344 +** This is legacy and deprecated.  It is included for historical
   9.345 +** compatibility and is not documented.
   9.346 +*/
   9.347 +typedef int (*sqlite3_callback)(void*,int,char**, char**);
   9.348 +
   9.349 +/*
   9.350 +** CAPI3REF: One-Step Query Execution Interface
   9.351 +**
   9.352 +** The sqlite3_exec() interface is a convenience wrapper around
   9.353 +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
   9.354 +** that allows an application to run multiple statements of SQL
   9.355 +** without having to use a lot of C code. 
   9.356 +**
   9.357 +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
   9.358 +** semicolon-separate SQL statements passed into its 2nd argument,
   9.359 +** in the context of the [database connection] passed in as its 1st
   9.360 +** argument.  ^If the callback function of the 3rd argument to
   9.361 +** sqlite3_exec() is not NULL, then it is invoked for each result row
   9.362 +** coming out of the evaluated SQL statements.  ^The 4th argument to
   9.363 +** sqlite3_exec() is relayed through to the 1st argument of each
   9.364 +** callback invocation.  ^If the callback pointer to sqlite3_exec()
   9.365 +** is NULL, then no callback is ever invoked and result rows are
   9.366 +** ignored.
   9.367 +**
   9.368 +** ^If an error occurs while evaluating the SQL statements passed into
   9.369 +** sqlite3_exec(), then execution of the current statement stops and
   9.370 +** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
   9.371 +** is not NULL then any error message is written into memory obtained
   9.372 +** from [sqlite3_malloc()] and passed back through the 5th parameter.
   9.373 +** To avoid memory leaks, the application should invoke [sqlite3_free()]
   9.374 +** on error message strings returned through the 5th parameter of
   9.375 +** of sqlite3_exec() after the error message string is no longer needed.
   9.376 +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
   9.377 +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
   9.378 +** NULL before returning.
   9.379 +**
   9.380 +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
   9.381 +** routine returns SQLITE_ABORT without invoking the callback again and
   9.382 +** without running any subsequent SQL statements.
   9.383 +**
   9.384 +** ^The 2nd argument to the sqlite3_exec() callback function is the
   9.385 +** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
   9.386 +** callback is an array of pointers to strings obtained as if from
   9.387 +** [sqlite3_column_text()], one for each column.  ^If an element of a
   9.388 +** result row is NULL then the corresponding string pointer for the
   9.389 +** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
   9.390 +** sqlite3_exec() callback is an array of pointers to strings where each
   9.391 +** entry represents the name of corresponding result column as obtained
   9.392 +** from [sqlite3_column_name()].
   9.393 +**
   9.394 +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
   9.395 +** to an empty string, or a pointer that contains only whitespace and/or 
   9.396 +** SQL comments, then no SQL statements are evaluated and the database
   9.397 +** is not changed.
   9.398 +**
   9.399 +** Restrictions:
   9.400 +**
   9.401 +** <ul>
   9.402 +** <li> The application must insure that the 1st parameter to sqlite3_exec()
   9.403 +**      is a valid and open [database connection].
   9.404 +** <li> The application must not close the [database connection] specified by
   9.405 +**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
   9.406 +** <li> The application must not modify the SQL statement text passed into
   9.407 +**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
   9.408 +** </ul>
   9.409 +*/
   9.410 +SQLITE_API int sqlite3_exec(
   9.411 +  sqlite3*,                                  /* An open database */
   9.412 +  const char *sql,                           /* SQL to be evaluated */
   9.413 +  int (*callback)(void*,int,char**,char**),  /* Callback function */
   9.414 +  void *,                                    /* 1st argument to callback */
   9.415 +  char **errmsg                              /* Error msg written here */
   9.416 +);
   9.417 +
   9.418 +/*
   9.419 +** CAPI3REF: Result Codes
   9.420 +** KEYWORDS: SQLITE_OK {error code} {error codes}
   9.421 +** KEYWORDS: {result code} {result codes}
   9.422 +**
   9.423 +** Many SQLite functions return an integer result code from the set shown
   9.424 +** here in order to indicate success or failure.
   9.425 +**
   9.426 +** New error codes may be added in future versions of SQLite.
   9.427 +**
   9.428 +** See also: [SQLITE_IOERR_READ | extended result codes],
   9.429 +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
   9.430 +*/
   9.431 +#define SQLITE_OK           0   /* Successful result */
   9.432 +/* beginning-of-error-codes */
   9.433 +#define SQLITE_ERROR        1   /* SQL error or missing database */
   9.434 +#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
   9.435 +#define SQLITE_PERM         3   /* Access permission denied */
   9.436 +#define SQLITE_ABORT        4   /* Callback routine requested an abort */
   9.437 +#define SQLITE_BUSY         5   /* The database file is locked */
   9.438 +#define SQLITE_LOCKED       6   /* A table in the database is locked */
   9.439 +#define SQLITE_NOMEM        7   /* A malloc() failed */
   9.440 +#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
   9.441 +#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
   9.442 +#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
   9.443 +#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
   9.444 +#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
   9.445 +#define SQLITE_FULL        13   /* Insertion failed because database is full */
   9.446 +#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
   9.447 +#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
   9.448 +#define SQLITE_EMPTY       16   /* Database is empty */
   9.449 +#define SQLITE_SCHEMA      17   /* The database schema changed */
   9.450 +#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
   9.451 +#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
   9.452 +#define SQLITE_MISMATCH    20   /* Data type mismatch */
   9.453 +#define SQLITE_MISUSE      21   /* Library used incorrectly */
   9.454 +#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
   9.455 +#define SQLITE_AUTH        23   /* Authorization denied */
   9.456 +#define SQLITE_FORMAT      24   /* Auxiliary database format error */
   9.457 +#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
   9.458 +#define SQLITE_NOTADB      26   /* File opened that is not a database file */
   9.459 +#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
   9.460 +#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
   9.461 +#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
   9.462 +#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
   9.463 +/* end-of-error-codes */
   9.464 +
   9.465 +/*
   9.466 +** CAPI3REF: Extended Result Codes
   9.467 +** KEYWORDS: {extended error code} {extended error codes}
   9.468 +** KEYWORDS: {extended result code} {extended result codes}
   9.469 +**
   9.470 +** In its default configuration, SQLite API routines return one of 26 integer
   9.471 +** [SQLITE_OK | result codes].  However, experience has shown that many of
   9.472 +** these result codes are too coarse-grained.  They do not provide as
   9.473 +** much information about problems as programmers might like.  In an effort to
   9.474 +** address this, newer versions of SQLite (version 3.3.8 and later) include
   9.475 +** support for additional result codes that provide more detailed information
   9.476 +** about errors. The extended result codes are enabled or disabled
   9.477 +** on a per database connection basis using the
   9.478 +** [sqlite3_extended_result_codes()] API.
   9.479 +**
   9.480 +** Some of the available extended result codes are listed here.
   9.481 +** One may expect the number of extended result codes will increase
   9.482 +** over time.  Software that uses extended result codes should expect
   9.483 +** to see new result codes in future releases of SQLite.
   9.484 +**
   9.485 +** The SQLITE_OK result code will never be extended.  It will always
   9.486 +** be exactly zero.
   9.487 +*/
   9.488 +#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
   9.489 +#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
   9.490 +#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
   9.491 +#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
   9.492 +#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
   9.493 +#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
   9.494 +#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
   9.495 +#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
   9.496 +#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
   9.497 +#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
   9.498 +#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
   9.499 +#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
   9.500 +#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
   9.501 +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
   9.502 +#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
   9.503 +#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
   9.504 +#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
   9.505 +#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
   9.506 +#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
   9.507 +#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
   9.508 +#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
   9.509 +#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
   9.510 +#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
   9.511 +#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
   9.512 +#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
   9.513 +#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
   9.514 +#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   9.515 +#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   9.516 +#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
   9.517 +#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   9.518 +#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
   9.519 +#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
   9.520 +#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
   9.521 +#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
   9.522 +#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
   9.523 +#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
   9.524 +#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
   9.525 +#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
   9.526 +#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
   9.527 +#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
   9.528 +#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
   9.529 +#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
   9.530 +#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
   9.531 +#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
   9.532 +#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
   9.533 +#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
   9.534 +#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
   9.535 +#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
   9.536 +#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
   9.537 +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
   9.538 +#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
   9.539 +
   9.540 +/*
   9.541 +** CAPI3REF: Flags For File Open Operations
   9.542 +**
   9.543 +** These bit values are intended for use in the
   9.544 +** 3rd parameter to the [sqlite3_open_v2()] interface and
   9.545 +** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
   9.546 +*/
   9.547 +#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
   9.548 +#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
   9.549 +#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
   9.550 +#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
   9.551 +#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
   9.552 +#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
   9.553 +#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
   9.554 +#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
   9.555 +#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
   9.556 +#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
   9.557 +#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
   9.558 +#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
   9.559 +#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
   9.560 +#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
   9.561 +#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
   9.562 +#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
   9.563 +#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
   9.564 +#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
   9.565 +#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
   9.566 +#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
   9.567 +
   9.568 +/* Reserved:                         0x00F00000 */
   9.569 +
   9.570 +/*
   9.571 +** CAPI3REF: Device Characteristics
   9.572 +**
   9.573 +** The xDeviceCharacteristics method of the [sqlite3_io_methods]
   9.574 +** object returns an integer which is a vector of these
   9.575 +** bit values expressing I/O characteristics of the mass storage
   9.576 +** device that holds the file that the [sqlite3_io_methods]
   9.577 +** refers to.
   9.578 +**
   9.579 +** The SQLITE_IOCAP_ATOMIC property means that all writes of
   9.580 +** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   9.581 +** mean that writes of blocks that are nnn bytes in size and
   9.582 +** are aligned to an address which is an integer multiple of
   9.583 +** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   9.584 +** that when data is appended to a file, the data is appended
   9.585 +** first then the size of the file is extended, never the other
   9.586 +** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   9.587 +** information is written to disk in the same order as calls
   9.588 +** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
   9.589 +** after reboot following a crash or power loss, the only bytes in a
   9.590 +** file that were written at the application level might have changed
   9.591 +** and that adjacent bytes, even bytes within the same sector are
   9.592 +** guaranteed to be unchanged.
   9.593 +*/
   9.594 +#define SQLITE_IOCAP_ATOMIC                 0x00000001
   9.595 +#define SQLITE_IOCAP_ATOMIC512              0x00000002
   9.596 +#define SQLITE_IOCAP_ATOMIC1K               0x00000004
   9.597 +#define SQLITE_IOCAP_ATOMIC2K               0x00000008
   9.598 +#define SQLITE_IOCAP_ATOMIC4K               0x00000010
   9.599 +#define SQLITE_IOCAP_ATOMIC8K               0x00000020
   9.600 +#define SQLITE_IOCAP_ATOMIC16K              0x00000040
   9.601 +#define SQLITE_IOCAP_ATOMIC32K              0x00000080
   9.602 +#define SQLITE_IOCAP_ATOMIC64K              0x00000100
   9.603 +#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
   9.604 +#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
   9.605 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
   9.606 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
   9.607 +
   9.608 +/*
   9.609 +** CAPI3REF: File Locking Levels
   9.610 +**
   9.611 +** SQLite uses one of these integer values as the second
   9.612 +** argument to calls it makes to the xLock() and xUnlock() methods
   9.613 +** of an [sqlite3_io_methods] object.
   9.614 +*/
   9.615 +#define SQLITE_LOCK_NONE          0
   9.616 +#define SQLITE_LOCK_SHARED        1
   9.617 +#define SQLITE_LOCK_RESERVED      2
   9.618 +#define SQLITE_LOCK_PENDING       3
   9.619 +#define SQLITE_LOCK_EXCLUSIVE     4
   9.620 +
   9.621 +/*
   9.622 +** CAPI3REF: Synchronization Type Flags
   9.623 +**
   9.624 +** When SQLite invokes the xSync() method of an
   9.625 +** [sqlite3_io_methods] object it uses a combination of
   9.626 +** these integer values as the second argument.
   9.627 +**
   9.628 +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   9.629 +** sync operation only needs to flush data to mass storage.  Inode
   9.630 +** information need not be flushed. If the lower four bits of the flag
   9.631 +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   9.632 +** If the lower four bits equal SQLITE_SYNC_FULL, that means
   9.633 +** to use Mac OS X style fullsync instead of fsync().
   9.634 +**
   9.635 +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
   9.636 +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
   9.637 +** settings.  The [synchronous pragma] determines when calls to the
   9.638 +** xSync VFS method occur and applies uniformly across all platforms.
   9.639 +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
   9.640 +** energetic or rigorous or forceful the sync operations are and
   9.641 +** only make a difference on Mac OSX for the default SQLite code.
   9.642 +** (Third-party VFS implementations might also make the distinction
   9.643 +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
   9.644 +** operating systems natively supported by SQLite, only Mac OSX
   9.645 +** cares about the difference.)
   9.646 +*/
   9.647 +#define SQLITE_SYNC_NORMAL        0x00002
   9.648 +#define SQLITE_SYNC_FULL          0x00003
   9.649 +#define SQLITE_SYNC_DATAONLY      0x00010
   9.650 +
   9.651 +/*
   9.652 +** CAPI3REF: OS Interface Open File Handle
   9.653 +**
   9.654 +** An [sqlite3_file] object represents an open file in the 
   9.655 +** [sqlite3_vfs | OS interface layer].  Individual OS interface
   9.656 +** implementations will
   9.657 +** want to subclass this object by appending additional fields
   9.658 +** for their own use.  The pMethods entry is a pointer to an
   9.659 +** [sqlite3_io_methods] object that defines methods for performing
   9.660 +** I/O operations on the open file.
   9.661 +*/
   9.662 +typedef struct sqlite3_file sqlite3_file;
   9.663 +struct sqlite3_file {
   9.664 +  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   9.665 +};
   9.666 +
   9.667 +/*
   9.668 +** CAPI3REF: OS Interface File Virtual Methods Object
   9.669 +**
   9.670 +** Every file opened by the [sqlite3_vfs.xOpen] method populates an
   9.671 +** [sqlite3_file] object (or, more commonly, a subclass of the
   9.672 +** [sqlite3_file] object) with a pointer to an instance of this object.
   9.673 +** This object defines the methods used to perform various operations
   9.674 +** against the open file represented by the [sqlite3_file] object.
   9.675 +**
   9.676 +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
   9.677 +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   9.678 +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
   9.679 +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
   9.680 +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
   9.681 +** to NULL.
   9.682 +**
   9.683 +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   9.684 +** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   9.685 +** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   9.686 +** flag may be ORed in to indicate that only the data of the file
   9.687 +** and not its inode needs to be synced.
   9.688 +**
   9.689 +** The integer values to xLock() and xUnlock() are one of
   9.690 +** <ul>
   9.691 +** <li> [SQLITE_LOCK_NONE],
   9.692 +** <li> [SQLITE_LOCK_SHARED],
   9.693 +** <li> [SQLITE_LOCK_RESERVED],
   9.694 +** <li> [SQLITE_LOCK_PENDING], or
   9.695 +** <li> [SQLITE_LOCK_EXCLUSIVE].
   9.696 +** </ul>
   9.697 +** xLock() increases the lock. xUnlock() decreases the lock.
   9.698 +** The xCheckReservedLock() method checks whether any database connection,
   9.699 +** either in this process or in some other process, is holding a RESERVED,
   9.700 +** PENDING, or EXCLUSIVE lock on the file.  It returns true
   9.701 +** if such a lock exists and false otherwise.
   9.702 +**
   9.703 +** The xFileControl() method is a generic interface that allows custom
   9.704 +** VFS implementations to directly control an open file using the
   9.705 +** [sqlite3_file_control()] interface.  The second "op" argument is an
   9.706 +** integer opcode.  The third argument is a generic pointer intended to
   9.707 +** point to a structure that may contain arguments or space in which to
   9.708 +** write return values.  Potential uses for xFileControl() might be
   9.709 +** functions to enable blocking locks with timeouts, to change the
   9.710 +** locking strategy (for example to use dot-file locks), to inquire
   9.711 +** about the status of a lock, or to break stale locks.  The SQLite
   9.712 +** core reserves all opcodes less than 100 for its own use.
   9.713 +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
   9.714 +** Applications that define a custom xFileControl method should use opcodes
   9.715 +** greater than 100 to avoid conflicts.  VFS implementations should
   9.716 +** return [SQLITE_NOTFOUND] for file control opcodes that they do not
   9.717 +** recognize.
   9.718 +**
   9.719 +** The xSectorSize() method returns the sector size of the
   9.720 +** device that underlies the file.  The sector size is the
   9.721 +** minimum write that can be performed without disturbing
   9.722 +** other bytes in the file.  The xDeviceCharacteristics()
   9.723 +** method returns a bit vector describing behaviors of the
   9.724 +** underlying device:
   9.725 +**
   9.726 +** <ul>
   9.727 +** <li> [SQLITE_IOCAP_ATOMIC]
   9.728 +** <li> [SQLITE_IOCAP_ATOMIC512]
   9.729 +** <li> [SQLITE_IOCAP_ATOMIC1K]
   9.730 +** <li> [SQLITE_IOCAP_ATOMIC2K]
   9.731 +** <li> [SQLITE_IOCAP_ATOMIC4K]
   9.732 +** <li> [SQLITE_IOCAP_ATOMIC8K]
   9.733 +** <li> [SQLITE_IOCAP_ATOMIC16K]
   9.734 +** <li> [SQLITE_IOCAP_ATOMIC32K]
   9.735 +** <li> [SQLITE_IOCAP_ATOMIC64K]
   9.736 +** <li> [SQLITE_IOCAP_SAFE_APPEND]
   9.737 +** <li> [SQLITE_IOCAP_SEQUENTIAL]
   9.738 +** </ul>
   9.739 +**
   9.740 +** The SQLITE_IOCAP_ATOMIC property means that all writes of
   9.741 +** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   9.742 +** mean that writes of blocks that are nnn bytes in size and
   9.743 +** are aligned to an address which is an integer multiple of
   9.744 +** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   9.745 +** that when data is appended to a file, the data is appended
   9.746 +** first then the size of the file is extended, never the other
   9.747 +** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   9.748 +** information is written to disk in the same order as calls
   9.749 +** to xWrite().
   9.750 +**
   9.751 +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   9.752 +** in the unread portions of the buffer with zeros.  A VFS that
   9.753 +** fails to zero-fill short reads might seem to work.  However,
   9.754 +** failure to zero-fill short reads will eventually lead to
   9.755 +** database corruption.
   9.756 +*/
   9.757 +typedef struct sqlite3_io_methods sqlite3_io_methods;
   9.758 +struct sqlite3_io_methods {
   9.759 +  int iVersion;
   9.760 +  int (*xClose)(sqlite3_file*);
   9.761 +  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   9.762 +  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   9.763 +  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   9.764 +  int (*xSync)(sqlite3_file*, int flags);
   9.765 +  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   9.766 +  int (*xLock)(sqlite3_file*, int);
   9.767 +  int (*xUnlock)(sqlite3_file*, int);
   9.768 +  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   9.769 +  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   9.770 +  int (*xSectorSize)(sqlite3_file*);
   9.771 +  int (*xDeviceCharacteristics)(sqlite3_file*);
   9.772 +  /* Methods above are valid for version 1 */
   9.773 +  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   9.774 +  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
   9.775 +  void (*xShmBarrier)(sqlite3_file*);
   9.776 +  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
   9.777 +  /* Methods above are valid for version 2 */
   9.778 +  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
   9.779 +  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
   9.780 +  /* Methods above are valid for version 3 */
   9.781 +  /* Additional methods may be added in future releases */
   9.782 +};
   9.783 +
   9.784 +/*
   9.785 +** CAPI3REF: Standard File Control Opcodes
   9.786 +**
   9.787 +** These integer constants are opcodes for the xFileControl method
   9.788 +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   9.789 +** interface.
   9.790 +**
   9.791 +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   9.792 +** opcode causes the xFileControl method to write the current state of
   9.793 +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   9.794 +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   9.795 +** into an integer that the pArg argument points to. This capability
   9.796 +** is used during testing and only needs to be supported when SQLITE_TEST
   9.797 +** is defined.
   9.798 +** <ul>
   9.799 +** <li>[[SQLITE_FCNTL_SIZE_HINT]]
   9.800 +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
   9.801 +** layer a hint of how large the database file will grow to be during the
   9.802 +** current transaction.  This hint is not guaranteed to be accurate but it
   9.803 +** is often close.  The underlying VFS might choose to preallocate database
   9.804 +** file space based on this hint in order to help writes to the database
   9.805 +** file run faster.
   9.806 +**
   9.807 +** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
   9.808 +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
   9.809 +** extends and truncates the database file in chunks of a size specified
   9.810 +** by the user. The fourth argument to [sqlite3_file_control()] should 
   9.811 +** point to an integer (type int) containing the new chunk-size to use
   9.812 +** for the nominated database. Allocating database file space in large
   9.813 +** chunks (say 1MB at a time), may reduce file-system fragmentation and
   9.814 +** improve performance on some systems.
   9.815 +**
   9.816 +** <li>[[SQLITE_FCNTL_FILE_POINTER]]
   9.817 +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
   9.818 +** to the [sqlite3_file] object associated with a particular database
   9.819 +** connection.  See the [sqlite3_file_control()] documentation for
   9.820 +** additional information.
   9.821 +**
   9.822 +** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
   9.823 +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
   9.824 +** SQLite and sent to all VFSes in place of a call to the xSync method
   9.825 +** when the database connection has [PRAGMA synchronous] set to OFF.)^
   9.826 +** Some specialized VFSes need this signal in order to operate correctly
   9.827 +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
   9.828 +** VFSes do not need this signal and should silently ignore this opcode.
   9.829 +** Applications should not call [sqlite3_file_control()] with this
   9.830 +** opcode as doing so may disrupt the operation of the specialized VFSes
   9.831 +** that do require it.  
   9.832 +**
   9.833 +** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
   9.834 +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
   9.835 +** retry counts and intervals for certain disk I/O operations for the
   9.836 +** windows [VFS] in order to provide robustness in the presence of
   9.837 +** anti-virus programs.  By default, the windows VFS will retry file read,
   9.838 +** file write, and file delete operations up to 10 times, with a delay
   9.839 +** of 25 milliseconds before the first retry and with the delay increasing
   9.840 +** by an additional 25 milliseconds with each subsequent retry.  This
   9.841 +** opcode allows these two values (10 retries and 25 milliseconds of delay)
   9.842 +** to be adjusted.  The values are changed for all database connections
   9.843 +** within the same process.  The argument is a pointer to an array of two
   9.844 +** integers where the first integer i the new retry count and the second
   9.845 +** integer is the delay.  If either integer is negative, then the setting
   9.846 +** is not changed but instead the prior value of that setting is written
   9.847 +** into the array entry, allowing the current retry settings to be
   9.848 +** interrogated.  The zDbName parameter is ignored.
   9.849 +**
   9.850 +** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
   9.851 +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
   9.852 +** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
   9.853 +** write ahead log and shared memory files used for transaction control
   9.854 +** are automatically deleted when the latest connection to the database
   9.855 +** closes.  Setting persistent WAL mode causes those files to persist after
   9.856 +** close.  Persisting the files is useful when other processes that do not
   9.857 +** have write permission on the directory containing the database file want
   9.858 +** to read the database file, as the WAL and shared memory files must exist
   9.859 +** in order for the database to be readable.  The fourth parameter to
   9.860 +** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   9.861 +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
   9.862 +** WAL mode.  If the integer is -1, then it is overwritten with the current
   9.863 +** WAL persistence setting.
   9.864 +**
   9.865 +** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
   9.866 +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
   9.867 +** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
   9.868 +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
   9.869 +** xDeviceCharacteristics methods. The fourth parameter to
   9.870 +** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   9.871 +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
   9.872 +** mode.  If the integer is -1, then it is overwritten with the current
   9.873 +** zero-damage mode setting.
   9.874 +**
   9.875 +** <li>[[SQLITE_FCNTL_OVERWRITE]]
   9.876 +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
   9.877 +** a write transaction to indicate that, unless it is rolled back for some
   9.878 +** reason, the entire database file will be overwritten by the current 
   9.879 +** transaction. This is used by VACUUM operations.
   9.880 +**
   9.881 +** <li>[[SQLITE_FCNTL_VFSNAME]]
   9.882 +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
   9.883 +** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
   9.884 +** final bottom-level VFS are written into memory obtained from 
   9.885 +** [sqlite3_malloc()] and the result is stored in the char* variable
   9.886 +** that the fourth parameter of [sqlite3_file_control()] points to.
   9.887 +** The caller is responsible for freeing the memory when done.  As with
   9.888 +** all file-control actions, there is no guarantee that this will actually
   9.889 +** do anything.  Callers should initialize the char* variable to a NULL
   9.890 +** pointer in case this file-control is not implemented.  This file-control
   9.891 +** is intended for diagnostic use only.
   9.892 +**
   9.893 +** <li>[[SQLITE_FCNTL_PRAGMA]]
   9.894 +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
   9.895 +** file control is sent to the open [sqlite3_file] object corresponding
   9.896 +** to the database file to which the pragma statement refers. ^The argument
   9.897 +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
   9.898 +** pointers to strings (char**) in which the second element of the array
   9.899 +** is the name of the pragma and the third element is the argument to the
   9.900 +** pragma or NULL if the pragma has no argument.  ^The handler for an
   9.901 +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
   9.902 +** of the char** argument point to a string obtained from [sqlite3_mprintf()]
   9.903 +** or the equivalent and that string will become the result of the pragma or
   9.904 +** the error message if the pragma fails. ^If the
   9.905 +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
   9.906 +** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
   9.907 +** file control returns [SQLITE_OK], then the parser assumes that the
   9.908 +** VFS has handled the PRAGMA itself and the parser generates a no-op
   9.909 +** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
   9.910 +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
   9.911 +** that the VFS encountered an error while handling the [PRAGMA] and the
   9.912 +** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
   9.913 +** file control occurs at the beginning of pragma statement analysis and so
   9.914 +** it is able to override built-in [PRAGMA] statements.
   9.915 +**
   9.916 +** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
   9.917 +** ^The [SQLITE_FCNTL_BUSYHANDLER]
   9.918 +** file-control may be invoked by SQLite on the database file handle
   9.919 +** shortly after it is opened in order to provide a custom VFS with access
   9.920 +** to the connections busy-handler callback. The argument is of type (void **)
   9.921 +** - an array of two (void *) values. The first (void *) actually points
   9.922 +** to a function of type (int (*)(void *)). In order to invoke the connections
   9.923 +** busy-handler, this function should be invoked with the second (void *) in
   9.924 +** the array as the only argument. If it returns non-zero, then the operation
   9.925 +** should be retried. If it returns zero, the custom VFS should abandon the
   9.926 +** current operation.
   9.927 +**
   9.928 +** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
   9.929 +** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
   9.930 +** to have SQLite generate a
   9.931 +** temporary filename using the same algorithm that is followed to generate
   9.932 +** temporary filenames for TEMP tables and other internal uses.  The
   9.933 +** argument should be a char** which will be filled with the filename
   9.934 +** written into memory obtained from [sqlite3_malloc()].  The caller should
   9.935 +** invoke [sqlite3_free()] on the result to avoid a memory leak.
   9.936 +**
   9.937 +** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
   9.938 +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
   9.939 +** maximum number of bytes that will be used for memory-mapped I/O.
   9.940 +** The argument is a pointer to a value of type sqlite3_int64 that
   9.941 +** is an advisory maximum number of bytes in the file to memory map.  The
   9.942 +** pointer is overwritten with the old value.  The limit is not changed if
   9.943 +** the value originally pointed to is negative, and so the current limit 
   9.944 +** can be queried by passing in a pointer to a negative number.  This
   9.945 +** file-control is used internally to implement [PRAGMA mmap_size].
   9.946 +**
   9.947 +** <li>[[SQLITE_FCNTL_TRACE]]
   9.948 +** The [SQLITE_FCNTL_TRACE] file control provides advisory information
   9.949 +** to the VFS about what the higher layers of the SQLite stack are doing.
   9.950 +** This file control is used by some VFS activity tracing [shims].
   9.951 +** The argument is a zero-terminated string.  Higher layers in the
   9.952 +** SQLite stack may generate instances of this file control if
   9.953 +** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
   9.954 +**
   9.955 +** </ul>
   9.956 +*/
   9.957 +#define SQLITE_FCNTL_LOCKSTATE               1
   9.958 +#define SQLITE_GET_LOCKPROXYFILE             2
   9.959 +#define SQLITE_SET_LOCKPROXYFILE             3
   9.960 +#define SQLITE_LAST_ERRNO                    4
   9.961 +#define SQLITE_FCNTL_SIZE_HINT               5
   9.962 +#define SQLITE_FCNTL_CHUNK_SIZE              6
   9.963 +#define SQLITE_FCNTL_FILE_POINTER            7
   9.964 +#define SQLITE_FCNTL_SYNC_OMITTED            8
   9.965 +#define SQLITE_FCNTL_WIN32_AV_RETRY          9
   9.966 +#define SQLITE_FCNTL_PERSIST_WAL            10
   9.967 +#define SQLITE_FCNTL_OVERWRITE              11
   9.968 +#define SQLITE_FCNTL_VFSNAME                12
   9.969 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
   9.970 +#define SQLITE_FCNTL_PRAGMA                 14
   9.971 +#define SQLITE_FCNTL_BUSYHANDLER            15
   9.972 +#define SQLITE_FCNTL_TEMPFILENAME           16
   9.973 +#define SQLITE_FCNTL_MMAP_SIZE              18
   9.974 +#define SQLITE_FCNTL_TRACE                  19
   9.975 +
   9.976 +/*
   9.977 +** CAPI3REF: Mutex Handle
   9.978 +**
   9.979 +** The mutex module within SQLite defines [sqlite3_mutex] to be an
   9.980 +** abstract type for a mutex object.  The SQLite core never looks
   9.981 +** at the internal representation of an [sqlite3_mutex].  It only
   9.982 +** deals with pointers to the [sqlite3_mutex] object.
   9.983 +**
   9.984 +** Mutexes are created using [sqlite3_mutex_alloc()].
   9.985 +*/
   9.986 +typedef struct sqlite3_mutex sqlite3_mutex;
   9.987 +
   9.988 +/*
   9.989 +** CAPI3REF: OS Interface Object
   9.990 +**
   9.991 +** An instance of the sqlite3_vfs object defines the interface between
   9.992 +** the SQLite core and the underlying operating system.  The "vfs"
   9.993 +** in the name of the object stands for "virtual file system".  See
   9.994 +** the [VFS | VFS documentation] for further information.
   9.995 +**
   9.996 +** The value of the iVersion field is initially 1 but may be larger in
   9.997 +** future versions of SQLite.  Additional fields may be appended to this
   9.998 +** object when the iVersion value is increased.  Note that the structure
   9.999 +** of the sqlite3_vfs object changes in the transaction between
  9.1000 +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  9.1001 +** modified.
  9.1002 +**
  9.1003 +** The szOsFile field is the size of the subclassed [sqlite3_file]
  9.1004 +** structure used by this VFS.  mxPathname is the maximum length of
  9.1005 +** a pathname in this VFS.
  9.1006 +**
  9.1007 +** Registered sqlite3_vfs objects are kept on a linked list formed by
  9.1008 +** the pNext pointer.  The [sqlite3_vfs_register()]
  9.1009 +** and [sqlite3_vfs_unregister()] interfaces manage this list
  9.1010 +** in a thread-safe way.  The [sqlite3_vfs_find()] interface
  9.1011 +** searches the list.  Neither the application code nor the VFS
  9.1012 +** implementation should use the pNext pointer.
  9.1013 +**
  9.1014 +** The pNext field is the only field in the sqlite3_vfs
  9.1015 +** structure that SQLite will ever modify.  SQLite will only access
  9.1016 +** or modify this field while holding a particular static mutex.
  9.1017 +** The application should never modify anything within the sqlite3_vfs
  9.1018 +** object once the object has been registered.
  9.1019 +**
  9.1020 +** The zName field holds the name of the VFS module.  The name must
  9.1021 +** be unique across all VFS modules.
  9.1022 +**
  9.1023 +** [[sqlite3_vfs.xOpen]]
  9.1024 +** ^SQLite guarantees that the zFilename parameter to xOpen
  9.1025 +** is either a NULL pointer or string obtained
  9.1026 +** from xFullPathname() with an optional suffix added.
  9.1027 +** ^If a suffix is added to the zFilename parameter, it will
  9.1028 +** consist of a single "-" character followed by no more than
  9.1029 +** 11 alphanumeric and/or "-" characters.
  9.1030 +** ^SQLite further guarantees that
  9.1031 +** the string will be valid and unchanged until xClose() is
  9.1032 +** called. Because of the previous sentence,
  9.1033 +** the [sqlite3_file] can safely store a pointer to the
  9.1034 +** filename if it needs to remember the filename for some reason.
  9.1035 +** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  9.1036 +** must invent its own temporary name for the file.  ^Whenever the 
  9.1037 +** xFilename parameter is NULL it will also be the case that the
  9.1038 +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  9.1039 +**
  9.1040 +** The flags argument to xOpen() includes all bits set in
  9.1041 +** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
  9.1042 +** or [sqlite3_open16()] is used, then flags includes at least
  9.1043 +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
  9.1044 +** If xOpen() opens a file read-only then it sets *pOutFlags to
  9.1045 +** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
  9.1046 +**
  9.1047 +** ^(SQLite will also add one of the following flags to the xOpen()
  9.1048 +** call, depending on the object being opened:
  9.1049 +**
  9.1050 +** <ul>
  9.1051 +** <li>  [SQLITE_OPEN_MAIN_DB]
  9.1052 +** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
  9.1053 +** <li>  [SQLITE_OPEN_TEMP_DB]
  9.1054 +** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
  9.1055 +** <li>  [SQLITE_OPEN_TRANSIENT_DB]
  9.1056 +** <li>  [SQLITE_OPEN_SUBJOURNAL]
  9.1057 +** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
  9.1058 +** <li>  [SQLITE_OPEN_WAL]
  9.1059 +** </ul>)^
  9.1060 +**
  9.1061 +** The file I/O implementation can use the object type flags to
  9.1062 +** change the way it deals with files.  For example, an application
  9.1063 +** that does not care about crash recovery or rollback might make
  9.1064 +** the open of a journal file a no-op.  Writes to this journal would
  9.1065 +** also be no-ops, and any attempt to read the journal would return
  9.1066 +** SQLITE_IOERR.  Or the implementation might recognize that a database
  9.1067 +** file will be doing page-aligned sector reads and writes in a random
  9.1068 +** order and set up its I/O subsystem accordingly.
  9.1069 +**
  9.1070 +** SQLite might also add one of the following flags to the xOpen method:
  9.1071 +**
  9.1072 +** <ul>
  9.1073 +** <li> [SQLITE_OPEN_DELETEONCLOSE]
  9.1074 +** <li> [SQLITE_OPEN_EXCLUSIVE]
  9.1075 +** </ul>
  9.1076 +**
  9.1077 +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  9.1078 +** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
  9.1079 +** will be set for TEMP databases and their journals, transient
  9.1080 +** databases, and subjournals.
  9.1081 +**
  9.1082 +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  9.1083 +** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  9.1084 +** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  9.1085 +** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
  9.1086 +** SQLITE_OPEN_CREATE, is used to indicate that file should always
  9.1087 +** be created, and that it is an error if it already exists.
  9.1088 +** It is <i>not</i> used to indicate the file should be opened 
  9.1089 +** for exclusive access.
  9.1090 +**
  9.1091 +** ^At least szOsFile bytes of memory are allocated by SQLite
  9.1092 +** to hold the  [sqlite3_file] structure passed as the third
  9.1093 +** argument to xOpen.  The xOpen method does not have to
  9.1094 +** allocate the structure; it should just fill it in.  Note that
  9.1095 +** the xOpen method must set the sqlite3_file.pMethods to either
  9.1096 +** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
  9.1097 +** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
  9.1098 +** element will be valid after xOpen returns regardless of the success
  9.1099 +** or failure of the xOpen call.
  9.1100 +**
  9.1101 +** [[sqlite3_vfs.xAccess]]
  9.1102 +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  9.1103 +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  9.1104 +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  9.1105 +** to test whether a file is at least readable.   The file can be a
  9.1106 +** directory.
  9.1107 +**
  9.1108 +** ^SQLite will always allocate at least mxPathname+1 bytes for the
  9.1109 +** output buffer xFullPathname.  The exact size of the output buffer
  9.1110 +** is also passed as a parameter to both  methods. If the output buffer
  9.1111 +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  9.1112 +** handled as a fatal error by SQLite, vfs implementations should endeavor
  9.1113 +** to prevent this by setting mxPathname to a sufficiently large value.
  9.1114 +**
  9.1115 +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  9.1116 +** interfaces are not strictly a part of the filesystem, but they are
  9.1117 +** included in the VFS structure for completeness.
  9.1118 +** The xRandomness() function attempts to return nBytes bytes
  9.1119 +** of good-quality randomness into zOut.  The return value is
  9.1120 +** the actual number of bytes of randomness obtained.
  9.1121 +** The xSleep() method causes the calling thread to sleep for at
  9.1122 +** least the number of microseconds given.  ^The xCurrentTime()
  9.1123 +** method returns a Julian Day Number for the current date and time as
  9.1124 +** a floating point value.
  9.1125 +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  9.1126 +** Day Number multiplied by 86400000 (the number of milliseconds in 
  9.1127 +** a 24-hour day).  
  9.1128 +** ^SQLite will use the xCurrentTimeInt64() method to get the current
  9.1129 +** date and time if that method is available (if iVersion is 2 or 
  9.1130 +** greater and the function pointer is not NULL) and will fall back
  9.1131 +** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  9.1132 +**
  9.1133 +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  9.1134 +** are not used by the SQLite core.  These optional interfaces are provided
  9.1135 +** by some VFSes to facilitate testing of the VFS code. By overriding 
  9.1136 +** system calls with functions under its control, a test program can
  9.1137 +** simulate faults and error conditions that would otherwise be difficult
  9.1138 +** or impossible to induce.  The set of system calls that can be overridden
  9.1139 +** varies from one VFS to another, and from one version of the same VFS to the
  9.1140 +** next.  Applications that use these interfaces must be prepared for any
  9.1141 +** or all of these interfaces to be NULL or for their behavior to change
  9.1142 +** from one release to the next.  Applications must not attempt to access
  9.1143 +** any of these methods if the iVersion of the VFS is less than 3.
  9.1144 +*/
  9.1145 +typedef struct sqlite3_vfs sqlite3_vfs;
  9.1146 +typedef void (*sqlite3_syscall_ptr)(void);
  9.1147 +struct sqlite3_vfs {
  9.1148 +  int iVersion;            /* Structure version number (currently 3) */
  9.1149 +  int szOsFile;            /* Size of subclassed sqlite3_file */
  9.1150 +  int mxPathname;          /* Maximum file pathname length */
  9.1151 +  sqlite3_vfs *pNext;      /* Next registered VFS */
  9.1152 +  const char *zName;       /* Name of this virtual file system */
  9.1153 +  void *pAppData;          /* Pointer to application-specific data */
  9.1154 +  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  9.1155 +               int flags, int *pOutFlags);
  9.1156 +  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  9.1157 +  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  9.1158 +  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  9.1159 +  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  9.1160 +  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  9.1161 +  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  9.1162 +  void (*xDlClose)(sqlite3_vfs*, void*);
  9.1163 +  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  9.1164 +  int (*xSleep)(sqlite3_vfs*, int microseconds);
  9.1165 +  int (*xCurrentTime)(sqlite3_vfs*, double*);
  9.1166 +  int (*xGetLastError)(sqlite3_vfs*, int, char *);
  9.1167 +  /*
  9.1168 +  ** The methods above are in version 1 of the sqlite_vfs object
  9.1169 +  ** definition.  Those that follow are added in version 2 or later
  9.1170 +  */
  9.1171 +  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  9.1172 +  /*
  9.1173 +  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  9.1174 +  ** Those below are for version 3 and greater.
  9.1175 +  */
  9.1176 +  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  9.1177 +  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  9.1178 +  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  9.1179 +  /*
  9.1180 +  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  9.1181 +  ** New fields may be appended in figure versions.  The iVersion
  9.1182 +  ** value will increment whenever this happens. 
  9.1183 +  */
  9.1184 +};
  9.1185 +
  9.1186 +/*
  9.1187 +** CAPI3REF: Flags for the xAccess VFS method
  9.1188 +**
  9.1189 +** These integer constants can be used as the third parameter to
  9.1190 +** the xAccess method of an [sqlite3_vfs] object.  They determine
  9.1191 +** what kind of permissions the xAccess method is looking for.
  9.1192 +** With SQLITE_ACCESS_EXISTS, the xAccess method
  9.1193 +** simply checks whether the file exists.
  9.1194 +** With SQLITE_ACCESS_READWRITE, the xAccess method
  9.1195 +** checks whether the named directory is both readable and writable
  9.1196 +** (in other words, if files can be added, removed, and renamed within
  9.1197 +** the directory).
  9.1198 +** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  9.1199 +** [temp_store_directory pragma], though this could change in a future
  9.1200 +** release of SQLite.
  9.1201 +** With SQLITE_ACCESS_READ, the xAccess method
  9.1202 +** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
  9.1203 +** currently unused, though it might be used in a future release of
  9.1204 +** SQLite.
  9.1205 +*/
  9.1206 +#define SQLITE_ACCESS_EXISTS    0
  9.1207 +#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
  9.1208 +#define SQLITE_ACCESS_READ      2   /* Unused */
  9.1209 +
  9.1210 +/*
  9.1211 +** CAPI3REF: Flags for the xShmLock VFS method
  9.1212 +**
  9.1213 +** These integer constants define the various locking operations
  9.1214 +** allowed by the xShmLock method of [sqlite3_io_methods].  The
  9.1215 +** following are the only legal combinations of flags to the
  9.1216 +** xShmLock method:
  9.1217 +**
  9.1218 +** <ul>
  9.1219 +** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  9.1220 +** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  9.1221 +** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  9.1222 +** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  9.1223 +** </ul>
  9.1224 +**
  9.1225 +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  9.1226 +** was given no the corresponding lock.  
  9.1227 +**
  9.1228 +** The xShmLock method can transition between unlocked and SHARED or
  9.1229 +** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
  9.1230 +** and EXCLUSIVE.
  9.1231 +*/
  9.1232 +#define SQLITE_SHM_UNLOCK       1
  9.1233 +#define SQLITE_SHM_LOCK         2
  9.1234 +#define SQLITE_SHM_SHARED       4
  9.1235 +#define SQLITE_SHM_EXCLUSIVE    8
  9.1236 +
  9.1237 +/*
  9.1238 +** CAPI3REF: Maximum xShmLock index
  9.1239 +**
  9.1240 +** The xShmLock method on [sqlite3_io_methods] may use values
  9.1241 +** between 0 and this upper bound as its "offset" argument.
  9.1242 +** The SQLite core will never attempt to acquire or release a
  9.1243 +** lock outside of this range
  9.1244 +*/
  9.1245 +#define SQLITE_SHM_NLOCK        8
  9.1246 +
  9.1247 +
  9.1248 +/*
  9.1249 +** CAPI3REF: Initialize The SQLite Library
  9.1250 +**
  9.1251 +** ^The sqlite3_initialize() routine initializes the
  9.1252 +** SQLite library.  ^The sqlite3_shutdown() routine
  9.1253 +** deallocates any resources that were allocated by sqlite3_initialize().
  9.1254 +** These routines are designed to aid in process initialization and
  9.1255 +** shutdown on embedded systems.  Workstation applications using
  9.1256 +** SQLite normally do not need to invoke either of these routines.
  9.1257 +**
  9.1258 +** A call to sqlite3_initialize() is an "effective" call if it is
  9.1259 +** the first time sqlite3_initialize() is invoked during the lifetime of
  9.1260 +** the process, or if it is the first time sqlite3_initialize() is invoked
  9.1261 +** following a call to sqlite3_shutdown().  ^(Only an effective call
  9.1262 +** of sqlite3_initialize() does any initialization.  All other calls
  9.1263 +** are harmless no-ops.)^
  9.1264 +**
  9.1265 +** A call to sqlite3_shutdown() is an "effective" call if it is the first
  9.1266 +** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
  9.1267 +** an effective call to sqlite3_shutdown() does any deinitialization.
  9.1268 +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  9.1269 +**
  9.1270 +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  9.1271 +** is not.  The sqlite3_shutdown() interface must only be called from a
  9.1272 +** single thread.  All open [database connections] must be closed and all
  9.1273 +** other SQLite resources must be deallocated prior to invoking
  9.1274 +** sqlite3_shutdown().
  9.1275 +**
  9.1276 +** Among other things, ^sqlite3_initialize() will invoke
  9.1277 +** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
  9.1278 +** will invoke sqlite3_os_end().
  9.1279 +**
  9.1280 +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  9.1281 +** ^If for some reason, sqlite3_initialize() is unable to initialize
  9.1282 +** the library (perhaps it is unable to allocate a needed resource such
  9.1283 +** as a mutex) it returns an [error code] other than [SQLITE_OK].
  9.1284 +**
  9.1285 +** ^The sqlite3_initialize() routine is called internally by many other
  9.1286 +** SQLite interfaces so that an application usually does not need to
  9.1287 +** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
  9.1288 +** calls sqlite3_initialize() so the SQLite library will be automatically
  9.1289 +** initialized when [sqlite3_open()] is called if it has not be initialized
  9.1290 +** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  9.1291 +** compile-time option, then the automatic calls to sqlite3_initialize()
  9.1292 +** are omitted and the application must call sqlite3_initialize() directly
  9.1293 +** prior to using any other SQLite interface.  For maximum portability,
  9.1294 +** it is recommended that applications always invoke sqlite3_initialize()
  9.1295 +** directly prior to using any other SQLite interface.  Future releases
  9.1296 +** of SQLite may require this.  In other words, the behavior exhibited
  9.1297 +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  9.1298 +** default behavior in some future release of SQLite.
  9.1299 +**
  9.1300 +** The sqlite3_os_init() routine does operating-system specific
  9.1301 +** initialization of the SQLite library.  The sqlite3_os_end()
  9.1302 +** routine undoes the effect of sqlite3_os_init().  Typical tasks
  9.1303 +** performed by these routines include allocation or deallocation
  9.1304 +** of static resources, initialization of global variables,
  9.1305 +** setting up a default [sqlite3_vfs] module, or setting up
  9.1306 +** a default configuration using [sqlite3_config()].
  9.1307 +**
  9.1308 +** The application should never invoke either sqlite3_os_init()
  9.1309 +** or sqlite3_os_end() directly.  The application should only invoke
  9.1310 +** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
  9.1311 +** interface is called automatically by sqlite3_initialize() and
  9.1312 +** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
  9.1313 +** implementations for sqlite3_os_init() and sqlite3_os_end()
  9.1314 +** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  9.1315 +** When [custom builds | built for other platforms]
  9.1316 +** (using the [SQLITE_OS_OTHER=1] compile-time
  9.1317 +** option) the application must supply a suitable implementation for
  9.1318 +** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
  9.1319 +** implementation of sqlite3_os_init() or sqlite3_os_end()
  9.1320 +** must return [SQLITE_OK] on success and some other [error code] upon
  9.1321 +** failure.
  9.1322 +*/
  9.1323 +SQLITE_API int sqlite3_initialize(void);
  9.1324 +SQLITE_API int sqlite3_shutdown(void);
  9.1325 +SQLITE_API int sqlite3_os_init(void);
  9.1326 +SQLITE_API int sqlite3_os_end(void);
  9.1327 +
  9.1328 +/*
  9.1329 +** CAPI3REF: Configuring The SQLite Library
  9.1330 +**
  9.1331 +** The sqlite3_config() interface is used to make global configuration
  9.1332 +** changes to SQLite in order to tune SQLite to the specific needs of
  9.1333 +** the application.  The default configuration is recommended for most
  9.1334 +** applications and so this routine is usually not necessary.  It is
  9.1335 +** provided to support rare applications with unusual needs.
  9.1336 +**
  9.1337 +** The sqlite3_config() interface is not threadsafe.  The application
  9.1338 +** must insure that no other SQLite interfaces are invoked by other
  9.1339 +** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
  9.1340 +** may only be invoked prior to library initialization using
  9.1341 +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  9.1342 +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  9.1343 +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  9.1344 +** Note, however, that ^sqlite3_config() can be called as part of the
  9.1345 +** implementation of an application-defined [sqlite3_os_init()].
  9.1346 +**
  9.1347 +** The first argument to sqlite3_config() is an integer
  9.1348 +** [configuration option] that determines
  9.1349 +** what property of SQLite is to be configured.  Subsequent arguments
  9.1350 +** vary depending on the [configuration option]
  9.1351 +** in the first argument.
  9.1352 +**
  9.1353 +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  9.1354 +** ^If the option is unknown or SQLite is unable to set the option
  9.1355 +** then this routine returns a non-zero [error code].
  9.1356 +*/
  9.1357 +SQLITE_API int sqlite3_config(int, ...);
  9.1358 +
  9.1359 +/*
  9.1360 +** CAPI3REF: Configure database connections
  9.1361 +**
  9.1362 +** The sqlite3_db_config() interface is used to make configuration
  9.1363 +** changes to a [database connection].  The interface is similar to
  9.1364 +** [sqlite3_config()] except that the changes apply to a single
  9.1365 +** [database connection] (specified in the first argument).
  9.1366 +**
  9.1367 +** The second argument to sqlite3_db_config(D,V,...)  is the
  9.1368 +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
  9.1369 +** that indicates what aspect of the [database connection] is being configured.
  9.1370 +** Subsequent arguments vary depending on the configuration verb.
  9.1371 +**
  9.1372 +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  9.1373 +** the call is considered successful.
  9.1374 +*/
  9.1375 +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  9.1376 +
  9.1377 +/*
  9.1378 +** CAPI3REF: Memory Allocation Routines
  9.1379 +**
  9.1380 +** An instance of this object defines the interface between SQLite
  9.1381 +** and low-level memory allocation routines.
  9.1382 +**
  9.1383 +** This object is used in only one place in the SQLite interface.
  9.1384 +** A pointer to an instance of this object is the argument to
  9.1385 +** [sqlite3_config()] when the configuration option is
  9.1386 +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
  9.1387 +** By creating an instance of this object
  9.1388 +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  9.1389 +** during configuration, an application can specify an alternative
  9.1390 +** memory allocation subsystem for SQLite to use for all of its
  9.1391 +** dynamic memory needs.
  9.1392 +**
  9.1393 +** Note that SQLite comes with several [built-in memory allocators]
  9.1394 +** that are perfectly adequate for the overwhelming majority of applications
  9.1395 +** and that this object is only useful to a tiny minority of applications
  9.1396 +** with specialized memory allocation requirements.  This object is
  9.1397 +** also used during testing of SQLite in order to specify an alternative
  9.1398 +** memory allocator that simulates memory out-of-memory conditions in
  9.1399 +** order to verify that SQLite recovers gracefully from such
  9.1400 +** conditions.
  9.1401 +**
  9.1402 +** The xMalloc, xRealloc, and xFree methods must work like the
  9.1403 +** malloc(), realloc() and free() functions from the standard C library.
  9.1404 +** ^SQLite guarantees that the second argument to
  9.1405 +** xRealloc is always a value returned by a prior call to xRoundup.
  9.1406 +**
  9.1407 +** xSize should return the allocated size of a memory allocation
  9.1408 +** previously obtained from xMalloc or xRealloc.  The allocated size
  9.1409 +** is always at least as big as the requested size but may be larger.
  9.1410 +**
  9.1411 +** The xRoundup method returns what would be the allocated size of
  9.1412 +** a memory allocation given a particular requested size.  Most memory
  9.1413 +** allocators round up memory allocations at least to the next multiple
  9.1414 +** of 8.  Some allocators round up to a larger multiple or to a power of 2.
  9.1415 +** Every memory allocation request coming in through [sqlite3_malloc()]
  9.1416 +** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
  9.1417 +** that causes the corresponding memory allocation to fail.
  9.1418 +**
  9.1419 +** The xInit method initializes the memory allocator.  For example,
  9.1420 +** it might allocate any require mutexes or initialize internal data
  9.1421 +** structures.  The xShutdown method is invoked (indirectly) by
  9.1422 +** [sqlite3_shutdown()] and should deallocate any resources acquired
  9.1423 +** by xInit.  The pAppData pointer is used as the only parameter to
  9.1424 +** xInit and xShutdown.
  9.1425 +**
  9.1426 +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  9.1427 +** the xInit method, so the xInit method need not be threadsafe.  The
  9.1428 +** xShutdown method is only called from [sqlite3_shutdown()] so it does
  9.1429 +** not need to be threadsafe either.  For all other methods, SQLite
  9.1430 +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  9.1431 +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  9.1432 +** it is by default) and so the methods are automatically serialized.
  9.1433 +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  9.1434 +** methods must be threadsafe or else make their own arrangements for
  9.1435 +** serialization.
  9.1436 +**
  9.1437 +** SQLite will never invoke xInit() more than once without an intervening
  9.1438 +** call to xShutdown().
  9.1439 +*/
  9.1440 +typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  9.1441 +struct sqlite3_mem_methods {
  9.1442 +  void *(*xMalloc)(int);         /* Memory allocation function */
  9.1443 +  void (*xFree)(void*);          /* Free a prior allocation */
  9.1444 +  void *(*xRealloc)(void*,int);  /* Resize an allocation */
  9.1445 +  int (*xSize)(void*);           /* Return the size of an allocation */
  9.1446 +  int (*xRoundup)(int);          /* Round up request size to allocation size */
  9.1447 +  int (*xInit)(void*);           /* Initialize the memory allocator */
  9.1448 +  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
  9.1449 +  void *pAppData;                /* Argument to xInit() and xShutdown() */
  9.1450 +};
  9.1451 +
  9.1452 +/*
  9.1453 +** CAPI3REF: Configuration Options
  9.1454 +** KEYWORDS: {configuration option}
  9.1455 +**
  9.1456 +** These constants are the available integer configuration options that
  9.1457 +** can be passed as the first argument to the [sqlite3_config()] interface.
  9.1458 +**
  9.1459 +** New configuration options may be added in future releases of SQLite.
  9.1460 +** Existing configuration options might be discontinued.  Applications
  9.1461 +** should check the return code from [sqlite3_config()] to make sure that
  9.1462 +** the call worked.  The [sqlite3_config()] interface will return a
  9.1463 +** non-zero [error code] if a discontinued or unsupported configuration option
  9.1464 +** is invoked.
  9.1465 +**
  9.1466 +** <dl>
  9.1467 +** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  9.1468 +** <dd>There are no arguments to this option.  ^This option sets the
  9.1469 +** [threading mode] to Single-thread.  In other words, it disables
  9.1470 +** all mutexing and puts SQLite into a mode where it can only be used
  9.1471 +** by a single thread.   ^If SQLite is compiled with
  9.1472 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  9.1473 +** it is not possible to change the [threading mode] from its default
  9.1474 +** value of Single-thread and so [sqlite3_config()] will return 
  9.1475 +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  9.1476 +** configuration option.</dd>
  9.1477 +**
  9.1478 +** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  9.1479 +** <dd>There are no arguments to this option.  ^This option sets the
  9.1480 +** [threading mode] to Multi-thread.  In other words, it disables
  9.1481 +** mutexing on [database connection] and [prepared statement] objects.
  9.1482 +** The application is responsible for serializing access to
  9.1483 +** [database connections] and [prepared statements].  But other mutexes
  9.1484 +** are enabled so that SQLite will be safe to use in a multi-threaded
  9.1485 +** environment as long as no two threads attempt to use the same
  9.1486 +** [database connection] at the same time.  ^If SQLite is compiled with
  9.1487 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  9.1488 +** it is not possible to set the Multi-thread [threading mode] and
  9.1489 +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  9.1490 +** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  9.1491 +**
  9.1492 +** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  9.1493 +** <dd>There are no arguments to this option.  ^This option sets the
  9.1494 +** [threading mode] to Serialized. In other words, this option enables
  9.1495 +** all mutexes including the recursive
  9.1496 +** mutexes on [database connection] and [prepared statement] objects.
  9.1497 +** In this mode (which is the default when SQLite is compiled with
  9.1498 +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  9.1499 +** to [database connections] and [prepared statements] so that the
  9.1500 +** application is free to use the same [database connection] or the
  9.1501 +** same [prepared statement] in different threads at the same time.
  9.1502 +** ^If SQLite is compiled with
  9.1503 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  9.1504 +** it is not possible to set the Serialized [threading mode] and
  9.1505 +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  9.1506 +** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  9.1507 +**
  9.1508 +** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  9.1509 +** <dd> ^(This option takes a single argument which is a pointer to an
  9.1510 +** instance of the [sqlite3_mem_methods] structure.  The argument specifies
  9.1511 +** alternative low-level memory allocation routines to be used in place of
  9.1512 +** the memory allocation routines built into SQLite.)^ ^SQLite makes
  9.1513 +** its own private copy of the content of the [sqlite3_mem_methods] structure
  9.1514 +** before the [sqlite3_config()] call returns.</dd>
  9.1515 +**
  9.1516 +** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  9.1517 +** <dd> ^(This option takes a single argument which is a pointer to an
  9.1518 +** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
  9.1519 +** structure is filled with the currently defined memory allocation routines.)^
  9.1520 +** This option can be used to overload the default memory allocation
  9.1521 +** routines with a wrapper that simulations memory allocation failure or
  9.1522 +** tracks memory usage, for example. </dd>
  9.1523 +**
  9.1524 +** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  9.1525 +** <dd> ^This option takes single argument of type int, interpreted as a 
  9.1526 +** boolean, which enables or disables the collection of memory allocation 
  9.1527 +** statistics. ^(When memory allocation statistics are disabled, the 
  9.1528 +** following SQLite interfaces become non-operational:
  9.1529 +**   <ul>
  9.1530 +**   <li> [sqlite3_memory_used()]
  9.1531 +**   <li> [sqlite3_memory_highwater()]
  9.1532 +**   <li> [sqlite3_soft_heap_limit64()]
  9.1533 +**   <li> [sqlite3_status()]
  9.1534 +**   </ul>)^
  9.1535 +** ^Memory allocation statistics are enabled by default unless SQLite is
  9.1536 +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  9.1537 +** allocation statistics are disabled by default.
  9.1538 +** </dd>
  9.1539 +**
  9.1540 +** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  9.1541 +** <dd> ^This option specifies a static memory buffer that SQLite can use for
  9.1542 +** scratch memory.  There are three arguments:  A pointer an 8-byte
  9.1543 +** aligned memory buffer from which the scratch allocations will be
  9.1544 +** drawn, the size of each scratch allocation (sz),
  9.1545 +** and the maximum number of scratch allocations (N).  The sz
  9.1546 +** argument must be a multiple of 16.
  9.1547 +** The first argument must be a pointer to an 8-byte aligned buffer
  9.1548 +** of at least sz*N bytes of memory.
  9.1549 +** ^SQLite will use no more than two scratch buffers per thread.  So
  9.1550 +** N should be set to twice the expected maximum number of threads.
  9.1551 +** ^SQLite will never require a scratch buffer that is more than 6
  9.1552 +** times the database page size. ^If SQLite needs needs additional
  9.1553 +** scratch memory beyond what is provided by this configuration option, then 
  9.1554 +** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  9.1555 +**
  9.1556 +** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  9.1557 +** <dd> ^This option specifies a static memory buffer that SQLite can use for
  9.1558 +** the database page cache with the default page cache implementation.  
  9.1559 +** This configuration should not be used if an application-define page
  9.1560 +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  9.1561 +** There are three arguments to this option: A pointer to 8-byte aligned
  9.1562 +** memory, the size of each page buffer (sz), and the number of pages (N).
  9.1563 +** The sz argument should be the size of the largest database page
  9.1564 +** (a power of two between 512 and 32768) plus a little extra for each
  9.1565 +** page header.  ^The page header size is 20 to 40 bytes depending on
  9.1566 +** the host architecture.  ^It is harmless, apart from the wasted memory,
  9.1567 +** to make sz a little too large.  The first
  9.1568 +** argument should point to an allocation of at least sz*N bytes of memory.
  9.1569 +** ^SQLite will use the memory provided by the first argument to satisfy its
  9.1570 +** memory needs for the first N pages that it adds to cache.  ^If additional
  9.1571 +** page cache memory is needed beyond what is provided by this option, then
  9.1572 +** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  9.1573 +** The pointer in the first argument must
  9.1574 +** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  9.1575 +** will be undefined.</dd>
  9.1576 +**
  9.1577 +** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  9.1578 +** <dd> ^This option specifies a static memory buffer that SQLite will use
  9.1579 +** for all of its dynamic memory allocation needs beyond those provided
  9.1580 +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  9.1581 +** There are three arguments: An 8-byte aligned pointer to the memory,
  9.1582 +** the number of bytes in the memory buffer, and the minimum allocation size.
  9.1583 +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  9.1584 +** to using its default memory allocator (the system malloc() implementation),
  9.1585 +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
  9.1586 +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  9.1587 +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  9.1588 +** allocator is engaged to handle all of SQLites memory allocation needs.
  9.1589 +** The first pointer (the memory pointer) must be aligned to an 8-byte
  9.1590 +** boundary or subsequent behavior of SQLite will be undefined.
  9.1591 +** The minimum allocation size is capped at 2**12. Reasonable values
  9.1592 +** for the minimum allocation size are 2**5 through 2**8.</dd>
  9.1593 +**
  9.1594 +** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  9.1595 +** <dd> ^(This option takes a single argument which is a pointer to an
  9.1596 +** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
  9.1597 +** alternative low-level mutex routines to be used in place
  9.1598 +** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
  9.1599 +** content of the [sqlite3_mutex_methods] structure before the call to
  9.1600 +** [sqlite3_config()] returns. ^If SQLite is compiled with
  9.1601 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  9.1602 +** the entire mutexing subsystem is omitted from the build and hence calls to
  9.1603 +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  9.1604 +** return [SQLITE_ERROR].</dd>
  9.1605 +**
  9.1606 +** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  9.1607 +** <dd> ^(This option takes a single argument which is a pointer to an
  9.1608 +** instance of the [sqlite3_mutex_methods] structure.  The
  9.1609 +** [sqlite3_mutex_methods]
  9.1610 +** structure is filled with the currently defined mutex routines.)^
  9.1611 +** This option can be used to overload the default mutex allocation
  9.1612 +** routines with a wrapper used to track mutex usage for performance
  9.1613 +** profiling or testing, for example.   ^If SQLite is compiled with
  9.1614 +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  9.1615 +** the entire mutexing subsystem is omitted from the build and hence calls to
  9.1616 +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  9.1617 +** return [SQLITE_ERROR].</dd>
  9.1618 +**
  9.1619 +** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  9.1620 +** <dd> ^(This option takes two arguments that determine the default
  9.1621 +** memory allocation for the lookaside memory allocator on each
  9.1622 +** [database connection].  The first argument is the
  9.1623 +** size of each lookaside buffer slot and the second is the number of
  9.1624 +** slots allocated to each database connection.)^  ^(This option sets the
  9.1625 +** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  9.1626 +** verb to [sqlite3_db_config()] can be used to change the lookaside
  9.1627 +** configuration on individual connections.)^ </dd>
  9.1628 +**
  9.1629 +** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  9.1630 +** <dd> ^(This option takes a single argument which is a pointer to
  9.1631 +** an [sqlite3_pcache_methods2] object.  This object specifies the interface
  9.1632 +** to a custom page cache implementation.)^  ^SQLite makes a copy of the
  9.1633 +** object and uses it for page cache memory allocations.</dd>
  9.1634 +**
  9.1635 +** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  9.1636 +** <dd> ^(This option takes a single argument which is a pointer to an
  9.1637 +** [sqlite3_pcache_methods2] object.  SQLite copies of the current
  9.1638 +** page cache implementation into that object.)^ </dd>
  9.1639 +**
  9.1640 +** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  9.1641 +** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  9.1642 +** global [error log].
  9.1643 +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  9.1644 +** function with a call signature of void(*)(void*,int,const char*), 
  9.1645 +** and a pointer to void. ^If the function pointer is not NULL, it is
  9.1646 +** invoked by [sqlite3_log()] to process each logging event.  ^If the
  9.1647 +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  9.1648 +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  9.1649 +** passed through as the first parameter to the application-defined logger
  9.1650 +** function whenever that function is invoked.  ^The second parameter to
  9.1651 +** the logger function is a copy of the first parameter to the corresponding
  9.1652 +** [sqlite3_log()] call and is intended to be a [result code] or an
  9.1653 +** [extended result code].  ^The third parameter passed to the logger is
  9.1654 +** log message after formatting via [sqlite3_snprintf()].
  9.1655 +** The SQLite logging interface is not reentrant; the logger function
  9.1656 +** supplied by the application must not invoke any SQLite interface.
  9.1657 +** In a multi-threaded application, the application-defined logger
  9.1658 +** function must be threadsafe. </dd>
  9.1659 +**
  9.1660 +** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  9.1661 +** <dd>^(This option takes a single argument of type int. If non-zero, then
  9.1662 +** URI handling is globally enabled. If the parameter is zero, then URI handling
  9.1663 +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  9.1664 +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  9.1665 +** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  9.1666 +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  9.1667 +** connection is opened. ^If it is globally disabled, filenames are
  9.1668 +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  9.1669 +** database connection is opened. ^(By default, URI handling is globally
  9.1670 +** disabled. The default value may be changed by compiling with the
  9.1671 +** [SQLITE_USE_URI] symbol defined.)^
  9.1672 +**
  9.1673 +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  9.1674 +** <dd>^This option takes a single integer argument which is interpreted as
  9.1675 +** a boolean in order to enable or disable the use of covering indices for
  9.1676 +** full table scans in the query optimizer.  ^The default setting is determined
  9.1677 +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  9.1678 +** if that compile-time option is omitted.
  9.1679 +** The ability to disable the use of covering indices for full table scans
  9.1680 +** is because some incorrectly coded legacy applications might malfunction
  9.1681 +** when the optimization is enabled.  Providing the ability to
  9.1682 +** disable the optimization allows the older, buggy application code to work
  9.1683 +** without change even with newer versions of SQLite.
  9.1684 +**
  9.1685 +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  9.1686 +** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  9.1687 +** <dd> These options are obsolete and should not be used by new code.
  9.1688 +** They are retained for backwards compatibility but are now no-ops.
  9.1689 +** </dd>
  9.1690 +**
  9.1691 +** [[SQLITE_CONFIG_SQLLOG]]
  9.1692 +** <dt>SQLITE_CONFIG_SQLLOG
  9.1693 +** <dd>This option is only available if sqlite is compiled with the
  9.1694 +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  9.1695 +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  9.1696 +** The second should be of type (void*). The callback is invoked by the library
  9.1697 +** in three separate circumstances, identified by the value passed as the
  9.1698 +** fourth parameter. If the fourth parameter is 0, then the database connection
  9.1699 +** passed as the second argument has just been opened. The third argument
  9.1700 +** points to a buffer containing the name of the main database file. If the
  9.1701 +** fourth parameter is 1, then the SQL statement that the third parameter
  9.1702 +** points to has just been executed. Or, if the fourth parameter is 2, then
  9.1703 +** the connection being passed as the second parameter is being closed. The
  9.1704 +** third parameter is passed NULL In this case.  An example of using this
  9.1705 +** configuration option can be seen in the "test_sqllog.c" source file in
  9.1706 +** the canonical SQLite source tree.</dd>
  9.1707 +**
  9.1708 +** [[SQLITE_CONFIG_MMAP_SIZE]]
  9.1709 +** <dt>SQLITE_CONFIG_MMAP_SIZE
  9.1710 +** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  9.1711 +** that are the default mmap size limit (the default setting for
  9.1712 +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  9.1713 +** ^The default setting can be overridden by each database connection using
  9.1714 +** either the [PRAGMA mmap_size] command, or by using the
  9.1715 +** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
  9.1716 +** cannot be changed at run-time.  Nor may the maximum allowed mmap size
  9.1717 +** exceed the compile-time maximum mmap size set by the
  9.1718 +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  9.1719 +** ^If either argument to this option is negative, then that argument is
  9.1720 +** changed to its compile-time default.
  9.1721 +**
  9.1722 +** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  9.1723 +** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  9.1724 +** <dd>^This option is only available if SQLite is compiled for Windows
  9.1725 +** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
  9.1726 +** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  9.1727 +** that specifies the maximum size of the created heap.
  9.1728 +** </dl>
  9.1729 +*/
  9.1730 +#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  9.1731 +#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  9.1732 +#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  9.1733 +#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
  9.1734 +#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
  9.1735 +#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
  9.1736 +#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
  9.1737 +#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
  9.1738 +#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
  9.1739 +#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
  9.1740 +#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
  9.1741 +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
  9.1742 +#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
  9.1743 +#define SQLITE_CONFIG_PCACHE       14  /* no-op */
  9.1744 +#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
  9.1745 +#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
  9.1746 +#define SQLITE_CONFIG_URI          17  /* int */
  9.1747 +#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
  9.1748 +#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
  9.1749 +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
  9.1750 +#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
  9.1751 +#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
  9.1752 +#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
  9.1753 +
  9.1754 +/*
  9.1755 +** CAPI3REF: Database Connection Configuration Options
  9.1756 +**
  9.1757 +** These constants are the available integer configuration options that
  9.1758 +** can be passed as the second argument to the [sqlite3_db_config()] interface.
  9.1759 +**
  9.1760 +** New configuration options may be added in future releases of SQLite.
  9.1761 +** Existing configuration options might be discontinued.  Applications
  9.1762 +** should check the return code from [sqlite3_db_config()] to make sure that
  9.1763 +** the call worked.  ^The [sqlite3_db_config()] interface will return a
  9.1764 +** non-zero [error code] if a discontinued or unsupported configuration option
  9.1765 +** is invoked.
  9.1766 +**
  9.1767 +** <dl>
  9.1768 +** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  9.1769 +** <dd> ^This option takes three additional arguments that determine the 
  9.1770 +** [lookaside memory allocator] configuration for the [database connection].
  9.1771 +** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  9.1772 +** pointer to a memory buffer to use for lookaside memory.
  9.1773 +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  9.1774 +** may be NULL in which case SQLite will allocate the
  9.1775 +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  9.1776 +** size of each lookaside buffer slot.  ^The third argument is the number of
  9.1777 +** slots.  The size of the buffer in the first argument must be greater than
  9.1778 +** or equal to the product of the second and third arguments.  The buffer
  9.1779 +** must be aligned to an 8-byte boundary.  ^If the second argument to
  9.1780 +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  9.1781 +** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
  9.1782 +** configuration for a database connection can only be changed when that
  9.1783 +** connection is not currently using lookaside memory, or in other words
  9.1784 +** when the "current value" returned by
  9.1785 +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  9.1786 +** Any attempt to change the lookaside memory configuration when lookaside
  9.1787 +** memory is in use leaves the configuration unchanged and returns 
  9.1788 +** [SQLITE_BUSY].)^</dd>
  9.1789 +**
  9.1790 +** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  9.1791 +** <dd> ^This option is used to enable or disable the enforcement of
  9.1792 +** [foreign key constraints].  There should be two additional arguments.
  9.1793 +** The first argument is an integer which is 0 to disable FK enforcement,
  9.1794 +** positive to enable FK enforcement or negative to leave FK enforcement
  9.1795 +** unchanged.  The second parameter is a pointer to an integer into which
  9.1796 +** is written 0 or 1 to indicate whether FK enforcement is off or on
  9.1797 +** following this call.  The second parameter may be a NULL pointer, in
  9.1798 +** which case the FK enforcement setting is not reported back. </dd>
  9.1799 +**
  9.1800 +** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  9.1801 +** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  9.1802 +** There should be two additional arguments.
  9.1803 +** The first argument is an integer which is 0 to disable triggers,
  9.1804 +** positive to enable triggers or negative to leave the setting unchanged.
  9.1805 +** The second parameter is a pointer to an integer into which
  9.1806 +** is written 0 or 1 to indicate whether triggers are disabled or enabled
  9.1807 +** following this call.  The second parameter may be a NULL pointer, in
  9.1808 +** which case the trigger setting is not reported back. </dd>
  9.1809 +**
  9.1810 +** </dl>
  9.1811 +*/
  9.1812 +#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
  9.1813 +#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
  9.1814 +#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
  9.1815 +
  9.1816 +
  9.1817 +/*
  9.1818 +** CAPI3REF: Enable Or Disable Extended Result Codes
  9.1819 +**
  9.1820 +** ^The sqlite3_extended_result_codes() routine enables or disables the
  9.1821 +** [extended result codes] feature of SQLite. ^The extended result
  9.1822 +** codes are disabled by default for historical compatibility.
  9.1823 +*/
  9.1824 +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  9.1825 +
  9.1826 +/*
  9.1827 +** CAPI3REF: Last Insert Rowid
  9.1828 +**
  9.1829 +** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  9.1830 +** has a unique 64-bit signed
  9.1831 +** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  9.1832 +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  9.1833 +** names are not also used by explicitly declared columns. ^If
  9.1834 +** the table has a column of type [INTEGER PRIMARY KEY] then that column
  9.1835 +** is another alias for the rowid.
  9.1836 +**
  9.1837 +** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the 
  9.1838 +** most recent successful [INSERT] into a rowid table or [virtual table]
  9.1839 +** on database connection D.
  9.1840 +** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  9.1841 +** ^If no successful [INSERT]s into rowid tables
  9.1842 +** have ever occurred on the database connection D, 
  9.1843 +** then sqlite3_last_insert_rowid(D) returns zero.
  9.1844 +**
  9.1845 +** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  9.1846 +** method, then this routine will return the [rowid] of the inserted
  9.1847 +** row as long as the trigger or virtual table method is running.
  9.1848 +** But once the trigger or virtual table method ends, the value returned 
  9.1849 +** by this routine reverts to what it was before the trigger or virtual
  9.1850 +** table method began.)^
  9.1851 +**
  9.1852 +** ^An [INSERT] that fails due to a constraint violation is not a
  9.1853 +** successful [INSERT] and does not change the value returned by this
  9.1854 +** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  9.1855 +** and INSERT OR ABORT make no changes to the return value of this
  9.1856 +** routine when their insertion fails.  ^(When INSERT OR REPLACE
  9.1857 +** encounters a constraint violation, it does not fail.  The
  9.1858 +** INSERT continues to completion after deleting rows that caused
  9.1859 +** the constraint problem so INSERT OR REPLACE will always change
  9.1860 +** the return value of this interface.)^
  9.1861 +**
  9.1862 +** ^For the purposes of this routine, an [INSERT] is considered to
  9.1863 +** be successful even if it is subsequently rolled back.
  9.1864 +**
  9.1865 +** This function is accessible to SQL statements via the
  9.1866 +** [last_insert_rowid() SQL function].
  9.1867 +**
  9.1868 +** If a separate thread performs a new [INSERT] on the same
  9.1869 +** database connection while the [sqlite3_last_insert_rowid()]
  9.1870 +** function is running and thus changes the last insert [rowid],
  9.1871 +** then the value returned by [sqlite3_last_insert_rowid()] is
  9.1872 +** unpredictable and might not equal either the old or the new
  9.1873 +** last insert [rowid].
  9.1874 +*/
  9.1875 +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  9.1876 +
  9.1877 +/*
  9.1878 +** CAPI3REF: Count The Number Of Rows Modified
  9.1879 +**
  9.1880 +** ^This function returns the number of database rows that were changed
  9.1881 +** or inserted or deleted by the most recently completed SQL statement
  9.1882 +** on the [database connection] specified by the first parameter.
  9.1883 +** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  9.1884 +** or [DELETE] statement are counted.  Auxiliary changes caused by
  9.1885 +** triggers or [foreign key actions] are not counted.)^ Use the
  9.1886 +** [sqlite3_total_changes()] function to find the total number of changes
  9.1887 +** including changes caused by triggers and foreign key actions.
  9.1888 +**
  9.1889 +** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  9.1890 +** are not counted.  Only real table changes are counted.
  9.1891 +**
  9.1892 +** ^(A "row change" is a change to a single row of a single table
  9.1893 +** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
  9.1894 +** are changed as side effects of [REPLACE] constraint resolution,
  9.1895 +** rollback, ABORT processing, [DROP TABLE], or by any other
  9.1896 +** mechanisms do not count as direct row changes.)^
  9.1897 +**
  9.1898 +** A "trigger context" is a scope of execution that begins and
  9.1899 +** ends with the script of a [CREATE TRIGGER | trigger]. 
  9.1900 +** Most SQL statements are
  9.1901 +** evaluated outside of any trigger.  This is the "top level"
  9.1902 +** trigger context.  If a trigger fires from the top level, a
  9.1903 +** new trigger context is entered for the duration of that one
  9.1904 +** trigger.  Subtriggers create subcontexts for their duration.
  9.1905 +**
  9.1906 +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  9.1907 +** not create a new trigger context.
  9.1908 +**
  9.1909 +** ^This function returns the number of direct row changes in the
  9.1910 +** most recent INSERT, UPDATE, or DELETE statement within the same
  9.1911 +** trigger context.
  9.1912 +**
  9.1913 +** ^Thus, when called from the top level, this function returns the
  9.1914 +** number of changes in the most recent INSERT, UPDATE, or DELETE
  9.1915 +** that also occurred at the top level.  ^(Within the body of a trigger,
  9.1916 +** the sqlite3_changes() interface can be called to find the number of
  9.1917 +** changes in the most recently completed INSERT, UPDATE, or DELETE
  9.1918 +** statement within the body of the same trigger.
  9.1919 +** However, the number returned does not include changes
  9.1920 +** caused by subtriggers since those have their own context.)^
  9.1921 +**
  9.1922 +** See also the [sqlite3_total_changes()] interface, the
  9.1923 +** [count_changes pragma], and the [changes() SQL function].
  9.1924 +**
  9.1925 +** If a separate thread makes changes on the same database connection
  9.1926 +** while [sqlite3_changes()] is running then the value returned
  9.1927 +** is unpredictable and not meaningful.
  9.1928 +*/
  9.1929 +SQLITE_API int sqlite3_changes(sqlite3*);
  9.1930 +
  9.1931 +/*
  9.1932 +** CAPI3REF: Total Number Of Rows Modified
  9.1933 +**
  9.1934 +** ^This function returns the number of row changes caused by [INSERT],
  9.1935 +** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  9.1936 +** ^(The count returned by sqlite3_total_changes() includes all changes
  9.1937 +** from all [CREATE TRIGGER | trigger] contexts and changes made by
  9.1938 +** [foreign key actions]. However,
  9.1939 +** the count does not include changes used to implement [REPLACE] constraints,
  9.1940 +** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
  9.1941 +** count does not include rows of views that fire an [INSTEAD OF trigger],
  9.1942 +** though if the INSTEAD OF trigger makes changes of its own, those changes 
  9.1943 +** are counted.)^
  9.1944 +** ^The sqlite3_total_changes() function counts the changes as soon as
  9.1945 +** the statement that makes them is completed (when the statement handle
  9.1946 +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  9.1947 +**
  9.1948 +** See also the [sqlite3_changes()] interface, the
  9.1949 +** [count_changes pragma], and the [total_changes() SQL function].
  9.1950 +**
  9.1951 +** If a separate thread makes changes on the same database connection
  9.1952 +** while [sqlite3_total_changes()] is running then the value
  9.1953 +** returned is unpredictable and not meaningful.
  9.1954 +*/
  9.1955 +SQLITE_API int sqlite3_total_changes(sqlite3*);
  9.1956 +
  9.1957 +/*
  9.1958 +** CAPI3REF: Interrupt A Long-Running Query
  9.1959 +**
  9.1960 +** ^This function causes any pending database operation to abort and
  9.1961 +** return at its earliest opportunity. This routine is typically
  9.1962 +** called in response to a user action such as pressing "Cancel"
  9.1963 +** or Ctrl-C where the user wants a long query operation to halt
  9.1964 +** immediately.
  9.1965 +**
  9.1966 +** ^It is safe to call this routine from a thread different from the
  9.1967 +** thread that is currently running the database operation.  But it
  9.1968 +** is not safe to call this routine with a [database connection] that
  9.1969 +** is closed or might close before sqlite3_interrupt() returns.
  9.1970 +**
  9.1971 +** ^If an SQL operation is very nearly finished at the time when
  9.1972 +** sqlite3_interrupt() is called, then it might not have an opportunity
  9.1973 +** to be interrupted and might continue to completion.
  9.1974 +**
  9.1975 +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  9.1976 +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  9.1977 +** that is inside an explicit transaction, then the entire transaction
  9.1978 +** will be rolled back automatically.
  9.1979 +**
  9.1980 +** ^The sqlite3_interrupt(D) call is in effect until all currently running
  9.1981 +** SQL statements on [database connection] D complete.  ^Any new SQL statements
  9.1982 +** that are started after the sqlite3_interrupt() call and before the 
  9.1983 +** running statements reaches zero are interrupted as if they had been
  9.1984 +** running prior to the sqlite3_interrupt() call.  ^New SQL statements
  9.1985 +** that are started after the running statement count reaches zero are
  9.1986 +** not effected by the sqlite3_interrupt().
  9.1987 +** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  9.1988 +** SQL statements is a no-op and has no effect on SQL statements
  9.1989 +** that are started after the sqlite3_interrupt() call returns.
  9.1990 +**
  9.1991 +** If the database connection closes while [sqlite3_interrupt()]
  9.1992 +** is running then bad things will likely happen.
  9.1993 +*/
  9.1994 +SQLITE_API void sqlite3_interrupt(sqlite3*);
  9.1995 +
  9.1996 +/*
  9.1997 +** CAPI3REF: Determine If An SQL Statement Is Complete
  9.1998 +**
  9.1999 +** These routines are useful during command-line input to determine if the
  9.2000 +** currently entered text seems to form a complete SQL statement or
  9.2001 +** if additional input is needed before sending the text into
  9.2002 +** SQLite for parsing.  ^These routines return 1 if the input string
  9.2003 +** appears to be a complete SQL statement.  ^A statement is judged to be
  9.2004 +** complete if it ends with a semicolon token and is not a prefix of a
  9.2005 +** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
  9.2006 +** string literals or quoted identifier names or comments are not
  9.2007 +** independent tokens (they are part of the token in which they are
  9.2008 +** embedded) and thus do not count as a statement terminator.  ^Whitespace
  9.2009 +** and comments that follow the final semicolon are ignored.
  9.2010 +**
  9.2011 +** ^These routines return 0 if the statement is incomplete.  ^If a
  9.2012 +** memory allocation fails, then SQLITE_NOMEM is returned.
  9.2013 +**
  9.2014 +** ^These routines do not parse the SQL statements thus
  9.2015 +** will not detect syntactically incorrect SQL.
  9.2016 +**
  9.2017 +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
  9.2018 +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  9.2019 +** automatically by sqlite3_complete16().  If that initialization fails,
  9.2020 +** then the return value from sqlite3_complete16() will be non-zero
  9.2021 +** regardless of whether or not the input SQL is complete.)^
  9.2022 +**
  9.2023 +** The input to [sqlite3_complete()] must be a zero-terminated
  9.2024 +** UTF-8 string.
  9.2025 +**
  9.2026 +** The input to [sqlite3_complete16()] must be a zero-terminated
  9.2027 +** UTF-16 string in native byte order.
  9.2028 +*/
  9.2029 +SQLITE_API int sqlite3_complete(const char *sql);
  9.2030 +SQLITE_API int sqlite3_complete16(const void *sql);
  9.2031 +
  9.2032 +/*
  9.2033 +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  9.2034 +**
  9.2035 +** ^This routine sets a callback function that might be invoked whenever
  9.2036 +** an attempt is made to open a database table that another thread
  9.2037 +** or process has locked.
  9.2038 +**
  9.2039 +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  9.2040 +** is returned immediately upon encountering the lock.  ^If the busy callback
  9.2041 +** is not NULL, then the callback might be invoked with two arguments.
  9.2042 +**
  9.2043 +** ^The first argument to the busy handler is a copy of the void* pointer which
  9.2044 +** is the third argument to sqlite3_busy_handler().  ^The second argument to
  9.2045 +** the busy handler callback is the number of times that the busy handler has
  9.2046 +** been invoked for this locking event.  ^If the
  9.2047 +** busy callback returns 0, then no additional attempts are made to
  9.2048 +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  9.2049 +** ^If the callback returns non-zero, then another attempt
  9.2050 +** is made to open the database for reading and the cycle repeats.
  9.2051 +**
  9.2052 +** The presence of a busy handler does not guarantee that it will be invoked
  9.2053 +** when there is lock contention. ^If SQLite determines that invoking the busy
  9.2054 +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  9.2055 +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  9.2056 +** Consider a scenario where one process is holding a read lock that
  9.2057 +** it is trying to promote to a reserved lock and
  9.2058 +** a second process is holding a reserved lock that it is trying
  9.2059 +** to promote to an exclusive lock.  The first process cannot proceed
  9.2060 +** because it is blocked by the second and the second process cannot
  9.2061 +** proceed because it is blocked by the first.  If both processes
  9.2062 +** invoke the busy handlers, neither will make any progress.  Therefore,
  9.2063 +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  9.2064 +** will induce the first process to release its read lock and allow
  9.2065 +** the second process to proceed.
  9.2066 +**
  9.2067 +** ^The default busy callback is NULL.
  9.2068 +**
  9.2069 +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  9.2070 +** when SQLite is in the middle of a large transaction where all the
  9.2071 +** changes will not fit into the in-memory cache.  SQLite will
  9.2072 +** already hold a RESERVED lock on the database file, but it needs
  9.2073 +** to promote this lock to EXCLUSIVE so that it can spill cache
  9.2074 +** pages into the database file without harm to concurrent
  9.2075 +** readers.  ^If it is unable to promote the lock, then the in-memory
  9.2076 +** cache will be left in an inconsistent state and so the error
  9.2077 +** code is promoted from the relatively benign [SQLITE_BUSY] to
  9.2078 +** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
  9.2079 +** forces an automatic rollback of the changes.  See the
  9.2080 +** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  9.2081 +** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  9.2082 +** this is important.
  9.2083 +**
  9.2084 +** ^(There can only be a single busy handler defined for each
  9.2085 +** [database connection].  Setting a new busy handler clears any
  9.2086 +** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
  9.2087 +** will also set or clear the busy handler.
  9.2088 +**
  9.2089 +** The busy callback should not take any actions which modify the
  9.2090 +** database connection that invoked the busy handler.  Any such actions
  9.2091 +** result in undefined behavior.
  9.2092 +** 
  9.2093 +** A busy handler must not close the database connection
  9.2094 +** or [prepared statement] that invoked the busy handler.
  9.2095 +*/
  9.2096 +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  9.2097 +
  9.2098 +/*
  9.2099 +** CAPI3REF: Set A Busy Timeout
  9.2100 +**
  9.2101 +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  9.2102 +** for a specified amount of time when a table is locked.  ^The handler
  9.2103 +** will sleep multiple times until at least "ms" milliseconds of sleeping
  9.2104 +** have accumulated.  ^After at least "ms" milliseconds of sleeping,
  9.2105 +** the handler returns 0 which causes [sqlite3_step()] to return
  9.2106 +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  9.2107 +**
  9.2108 +** ^Calling this routine with an argument less than or equal to zero
  9.2109 +** turns off all busy handlers.
  9.2110 +**
  9.2111 +** ^(There can only be a single busy handler for a particular
  9.2112 +** [database connection] any any given moment.  If another busy handler
  9.2113 +** was defined  (using [sqlite3_busy_handler()]) prior to calling
  9.2114 +** this routine, that other busy handler is cleared.)^
  9.2115 +*/
  9.2116 +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  9.2117 +
  9.2118 +/*
  9.2119 +** CAPI3REF: Convenience Routines For Running Queries
  9.2120 +**
  9.2121 +** This is a legacy interface that is preserved for backwards compatibility.
  9.2122 +** Use of this interface is not recommended.
  9.2123 +**
  9.2124 +** Definition: A <b>result table</b> is memory data structure created by the
  9.2125 +** [sqlite3_get_table()] interface.  A result table records the
  9.2126 +** complete query results from one or more queries.
  9.2127 +**
  9.2128 +** The table conceptually has a number of rows and columns.  But
  9.2129 +** these numbers are not part of the result table itself.  These
  9.2130 +** numbers are obtained separately.  Let N be the number of rows
  9.2131 +** and M be the number of columns.
  9.2132 +**
  9.2133 +** A result table is an array of pointers to zero-terminated UTF-8 strings.
  9.2134 +** There are (N+1)*M elements in the array.  The first M pointers point
  9.2135 +** to zero-terminated strings that  contain the names of the columns.
  9.2136 +** The remaining entries all point to query results.  NULL values result
  9.2137 +** in NULL pointers.  All other values are in their UTF-8 zero-terminated
  9.2138 +** string representation as returned by [sqlite3_column_text()].
  9.2139 +**
  9.2140 +** A result table might consist of one or more memory allocations.
  9.2141 +** It is not safe to pass a result table directly to [sqlite3_free()].
  9.2142 +** A result table should be deallocated using [sqlite3_free_table()].
  9.2143 +**
  9.2144 +** ^(As an example of the result table format, suppose a query result
  9.2145 +** is as follows:
  9.2146 +**
  9.2147 +** <blockquote><pre>
  9.2148 +**        Name        | Age
  9.2149 +**        -----------------------
  9.2150 +**        Alice       | 43
  9.2151 +**        Bob         | 28
  9.2152 +**        Cindy       | 21
  9.2153 +** </pre></blockquote>
  9.2154 +**
  9.2155 +** There are two column (M==2) and three rows (N==3).  Thus the
  9.2156 +** result table has 8 entries.  Suppose the result table is stored
  9.2157 +** in an array names azResult.  Then azResult holds this content:
  9.2158 +**
  9.2159 +** <blockquote><pre>
  9.2160 +**        azResult&#91;0] = "Name";
  9.2161 +**        azResult&#91;1] = "Age";
  9.2162 +**        azResult&#91;2] = "Alice";
  9.2163 +**        azResult&#91;3] = "43";
  9.2164 +**        azResult&#91;4] = "Bob";
  9.2165 +**        azResult&#91;5] = "28";
  9.2166 +**        azResult&#91;6] = "Cindy";
  9.2167 +**        azResult&#91;7] = "21";
  9.2168 +** </pre></blockquote>)^
  9.2169 +**
  9.2170 +** ^The sqlite3_get_table() function evaluates one or more
  9.2171 +** semicolon-separated SQL statements in the zero-terminated UTF-8
  9.2172 +** string of its 2nd parameter and returns a result table to the
  9.2173 +** pointer given in its 3rd parameter.
  9.2174 +**
  9.2175 +** After the application has finished with the result from sqlite3_get_table(),
  9.2176 +** it must pass the result table pointer to sqlite3_free_table() in order to
  9.2177 +** release the memory that was malloced.  Because of the way the
  9.2178 +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  9.2179 +** function must not try to call [sqlite3_free()] directly.  Only
  9.2180 +** [sqlite3_free_table()] is able to release the memory properly and safely.
  9.2181 +**
  9.2182 +** The sqlite3_get_table() interface is implemented as a wrapper around
  9.2183 +** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
  9.2184 +** to any internal data structures of SQLite.  It uses only the public
  9.2185 +** interface defined here.  As a consequence, errors that occur in the
  9.2186 +** wrapper layer outside of the internal [sqlite3_exec()] call are not
  9.2187 +** reflected in subsequent calls to [sqlite3_errcode()] or
  9.2188 +** [sqlite3_errmsg()].
  9.2189 +*/
  9.2190 +SQLITE_API int sqlite3_get_table(
  9.2191 +  sqlite3 *db,          /* An open database */
  9.2192 +  const char *zSql,     /* SQL to be evaluated */
  9.2193 +  char ***pazResult,    /* Results of the query */
  9.2194 +  int *pnRow,           /* Number of result rows written here */
  9.2195 +  int *pnColumn,        /* Number of result columns written here */
  9.2196 +  char **pzErrmsg       /* Error msg written here */
  9.2197 +);
  9.2198 +SQLITE_API void sqlite3_free_table(char **result);
  9.2199 +
  9.2200 +/*
  9.2201 +** CAPI3REF: Formatted String Printing Functions
  9.2202 +**
  9.2203 +** These routines are work-alikes of the "printf()" family of functions
  9.2204 +** from the standard C library.
  9.2205 +**
  9.2206 +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  9.2207 +** results into memory obtained from [sqlite3_malloc()].
  9.2208 +** The strings returned by these two routines should be
  9.2209 +** released by [sqlite3_free()].  ^Both routines return a
  9.2210 +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  9.2211 +** memory to hold the resulting string.
  9.2212 +**
  9.2213 +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  9.2214 +** the standard C library.  The result is written into the
  9.2215 +** buffer supplied as the second parameter whose size is given by
  9.2216 +** the first parameter. Note that the order of the
  9.2217 +** first two parameters is reversed from snprintf().)^  This is an
  9.2218 +** historical accident that cannot be fixed without breaking
  9.2219 +** backwards compatibility.  ^(Note also that sqlite3_snprintf()
  9.2220 +** returns a pointer to its buffer instead of the number of
  9.2221 +** characters actually written into the buffer.)^  We admit that
  9.2222 +** the number of characters written would be a more useful return
  9.2223 +** value but we cannot change the implementation of sqlite3_snprintf()
  9.2224 +** now without breaking compatibility.
  9.2225 +**
  9.2226 +** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  9.2227 +** guarantees that the buffer is always zero-terminated.  ^The first
  9.2228 +** parameter "n" is the total size of the buffer, including space for
  9.2229 +** the zero terminator.  So the longest string that can be completely
  9.2230 +** written will be n-1 characters.
  9.2231 +**
  9.2232 +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  9.2233 +**
  9.2234 +** These routines all implement some additional formatting
  9.2235 +** options that are useful for constructing SQL statements.
  9.2236 +** All of the usual printf() formatting options apply.  In addition, there
  9.2237 +** is are "%q", "%Q", and "%z" options.
  9.2238 +**
  9.2239 +** ^(The %q option works like %s in that it substitutes a nul-terminated
  9.2240 +** string from the argument list.  But %q also doubles every '\'' character.
  9.2241 +** %q is designed for use inside a string literal.)^  By doubling each '\''
  9.2242 +** character it escapes that character and allows it to be inserted into
  9.2243 +** the string.
  9.2244 +**
  9.2245 +** For example, assume the string variable zText contains text as follows:
  9.2246 +**
  9.2247 +** <blockquote><pre>
  9.2248 +**  char *zText = "It's a happy day!";
  9.2249 +** </pre></blockquote>
  9.2250 +**
  9.2251 +** One can use this text in an SQL statement as follows:
  9.2252 +**
  9.2253 +** <blockquote><pre>
  9.2254 +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  9.2255 +**  sqlite3_exec(db, zSQL, 0, 0, 0);
  9.2256 +**  sqlite3_free(zSQL);
  9.2257 +** </pre></blockquote>
  9.2258 +**
  9.2259 +** Because the %q format string is used, the '\'' character in zText
  9.2260 +** is escaped and the SQL generated is as follows:
  9.2261 +**
  9.2262 +** <blockquote><pre>
  9.2263 +**  INSERT INTO table1 VALUES('It''s a happy day!')
  9.2264 +** </pre></blockquote>
  9.2265 +**
  9.2266 +** This is correct.  Had we used %s instead of %q, the generated SQL
  9.2267 +** would have looked like this:
  9.2268 +**
  9.2269 +** <blockquote><pre>
  9.2270 +**  INSERT INTO table1 VALUES('It's a happy day!');
  9.2271 +** </pre></blockquote>
  9.2272 +**
  9.2273 +** This second example is an SQL syntax error.  As a general rule you should
  9.2274 +** always use %q instead of %s when inserting text into a string literal.
  9.2275 +**
  9.2276 +** ^(The %Q option works like %q except it also adds single quotes around
  9.2277 +** the outside of the total string.  Additionally, if the parameter in the
  9.2278 +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  9.2279 +** single quotes).)^  So, for example, one could say:
  9.2280 +**
  9.2281 +** <blockquote><pre>
  9.2282 +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  9.2283 +**  sqlite3_exec(db, zSQL, 0, 0, 0);
  9.2284 +**  sqlite3_free(zSQL);
  9.2285 +** </pre></blockquote>
  9.2286 +**
  9.2287 +** The code above will render a correct SQL statement in the zSQL
  9.2288 +** variable even if the zText variable is a NULL pointer.
  9.2289 +**
  9.2290 +** ^(The "%z" formatting option works like "%s" but with the
  9.2291 +** addition that after the string has been read and copied into
  9.2292 +** the result, [sqlite3_free()] is called on the input string.)^
  9.2293 +*/
  9.2294 +SQLITE_API char *sqlite3_mprintf(const char*,...);
  9.2295 +SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  9.2296 +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  9.2297 +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  9.2298 +
  9.2299 +/*
  9.2300 +** CAPI3REF: Memory Allocation Subsystem
  9.2301 +**
  9.2302 +** The SQLite core uses these three routines for all of its own
  9.2303 +** internal memory allocation needs. "Core" in the previous sentence
  9.2304 +** does not include operating-system specific VFS implementation.  The
  9.2305 +** Windows VFS uses native malloc() and free() for some operations.
  9.2306 +**
  9.2307 +** ^The sqlite3_malloc() routine returns a pointer to a block
  9.2308 +** of memory at least N bytes in length, where N is the parameter.
  9.2309 +** ^If sqlite3_malloc() is unable to obtain sufficient free
  9.2310 +** memory, it returns a NULL pointer.  ^If the parameter N to
  9.2311 +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  9.2312 +** a NULL pointer.
  9.2313 +**
  9.2314 +** ^Calling sqlite3_free() with a pointer previously returned
  9.2315 +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  9.2316 +** that it might be reused.  ^The sqlite3_free() routine is
  9.2317 +** a no-op if is called with a NULL pointer.  Passing a NULL pointer
  9.2318 +** to sqlite3_free() is harmless.  After being freed, memory
  9.2319 +** should neither be read nor written.  Even reading previously freed
  9.2320 +** memory might result in a segmentation fault or other severe error.
  9.2321 +** Memory corruption, a segmentation fault, or other severe error
  9.2322 +** might result if sqlite3_free() is called with a non-NULL pointer that
  9.2323 +** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  9.2324 +**
  9.2325 +** ^(The sqlite3_realloc() interface attempts to resize a
  9.2326 +** prior memory allocation to be at least N bytes, where N is the
  9.2327 +** second parameter.  The memory allocation to be resized is the first
  9.2328 +** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  9.2329 +** is a NULL pointer then its behavior is identical to calling
  9.2330 +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  9.2331 +** ^If the second parameter to sqlite3_realloc() is zero or
  9.2332 +** negative then the behavior is exactly the same as calling
  9.2333 +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  9.2334 +** ^sqlite3_realloc() returns a pointer to a memory allocation
  9.2335 +** of at least N bytes in size or NULL if sufficient memory is unavailable.
  9.2336 +** ^If M is the size of the prior allocation, then min(N,M) bytes
  9.2337 +** of the prior allocation are copied into the beginning of buffer returned
  9.2338 +** by sqlite3_realloc() and the prior allocation is freed.
  9.2339 +** ^If sqlite3_realloc() returns NULL, then the prior allocation
  9.2340 +** is not freed.
  9.2341 +**
  9.2342 +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  9.2343 +** is always aligned to at least an 8 byte boundary, or to a
  9.2344 +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  9.2345 +** option is used.
  9.2346 +**
  9.2347 +** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  9.2348 +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  9.2349 +** implementation of these routines to be omitted.  That capability
  9.2350 +** is no longer provided.  Only built-in memory allocators can be used.
  9.2351 +**
  9.2352 +** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  9.2353 +** the system malloc() and free() directly when converting
  9.2354 +** filenames between the UTF-8 encoding used by SQLite
  9.2355 +** and whatever filename encoding is used by the particular Windows
  9.2356 +** installation.  Memory allocation errors were detected, but
  9.2357 +** they were reported back as [SQLITE_CANTOPEN] or
  9.2358 +** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  9.2359 +**
  9.2360 +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  9.2361 +** must be either NULL or else pointers obtained from a prior
  9.2362 +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  9.2363 +** not yet been released.
  9.2364 +**
  9.2365 +** The application must not read or write any part of
  9.2366 +** a block of memory after it has been released using
  9.2367 +** [sqlite3_free()] or [sqlite3_realloc()].
  9.2368 +*/
  9.2369 +SQLITE_API void *sqlite3_malloc(int);
  9.2370 +SQLITE_API void *sqlite3_realloc(void*, int);
  9.2371 +SQLITE_API void sqlite3_free(void*);
  9.2372 +
  9.2373 +/*
  9.2374 +** CAPI3REF: Memory Allocator Statistics
  9.2375 +**
  9.2376 +** SQLite provides these two interfaces for reporting on the status
  9.2377 +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  9.2378 +** routines, which form the built-in memory allocation subsystem.
  9.2379 +**
  9.2380 +** ^The [sqlite3_memory_used()] routine returns the number of bytes
  9.2381 +** of memory currently outstanding (malloced but not freed).
  9.2382 +** ^The [sqlite3_memory_highwater()] routine returns the maximum
  9.2383 +** value of [sqlite3_memory_used()] since the high-water mark
  9.2384 +** was last reset.  ^The values returned by [sqlite3_memory_used()] and
  9.2385 +** [sqlite3_memory_highwater()] include any overhead
  9.2386 +** added by SQLite in its implementation of [sqlite3_malloc()],
  9.2387 +** but not overhead added by the any underlying system library
  9.2388 +** routines that [sqlite3_malloc()] may call.
  9.2389 +**
  9.2390 +** ^The memory high-water mark is reset to the current value of
  9.2391 +** [sqlite3_memory_used()] if and only if the parameter to
  9.2392 +** [sqlite3_memory_highwater()] is true.  ^The value returned
  9.2393 +** by [sqlite3_memory_highwater(1)] is the high-water mark
  9.2394 +** prior to the reset.
  9.2395 +*/
  9.2396 +SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  9.2397 +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  9.2398 +
  9.2399 +/*
  9.2400 +** CAPI3REF: Pseudo-Random Number Generator
  9.2401 +**
  9.2402 +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  9.2403 +** select random [ROWID | ROWIDs] when inserting new records into a table that
  9.2404 +** already uses the largest possible [ROWID].  The PRNG is also used for
  9.2405 +** the build-in random() and randomblob() SQL functions.  This interface allows
  9.2406 +** applications to access the same PRNG for other purposes.
  9.2407 +**
  9.2408 +** ^A call to this routine stores N bytes of randomness into buffer P.
  9.2409 +**
  9.2410 +** ^The first time this routine is invoked (either internally or by
  9.2411 +** the application) the PRNG is seeded using randomness obtained
  9.2412 +** from the xRandomness method of the default [sqlite3_vfs] object.
  9.2413 +** ^On all subsequent invocations, the pseudo-randomness is generated
  9.2414 +** internally and without recourse to the [sqlite3_vfs] xRandomness
  9.2415 +** method.
  9.2416 +*/
  9.2417 +SQLITE_API void sqlite3_randomness(int N, void *P);
  9.2418 +
  9.2419 +/*
  9.2420 +** CAPI3REF: Compile-Time Authorization Callbacks
  9.2421 +**
  9.2422 +** ^This routine registers an authorizer callback with a particular
  9.2423 +** [database connection], supplied in the first argument.
  9.2424 +** ^The authorizer callback is invoked as SQL statements are being compiled
  9.2425 +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  9.2426 +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
  9.2427 +** points during the compilation process, as logic is being created
  9.2428 +** to perform various actions, the authorizer callback is invoked to
  9.2429 +** see if those actions are allowed.  ^The authorizer callback should
  9.2430 +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  9.2431 +** specific action but allow the SQL statement to continue to be
  9.2432 +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  9.2433 +** rejected with an error.  ^If the authorizer callback returns
  9.2434 +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  9.2435 +** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  9.2436 +** the authorizer will fail with an error message.
  9.2437 +**
  9.2438 +** When the callback returns [SQLITE_OK], that means the operation
  9.2439 +** requested is ok.  ^When the callback returns [SQLITE_DENY], the
  9.2440 +** [sqlite3_prepare_v2()] or equivalent call that triggered the
  9.2441 +** authorizer will fail with an error message explaining that
  9.2442 +** access is denied. 
  9.2443 +**
  9.2444 +** ^The first parameter to the authorizer callback is a copy of the third
  9.2445 +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  9.2446 +** to the callback is an integer [SQLITE_COPY | action code] that specifies
  9.2447 +** the particular action to be authorized. ^The third through sixth parameters
  9.2448 +** to the callback are zero-terminated strings that contain additional
  9.2449 +** details about the action to be authorized.
  9.2450 +**
  9.2451 +** ^If the action code is [SQLITE_READ]
  9.2452 +** and the callback returns [SQLITE_IGNORE] then the
  9.2453 +** [prepared statement] statement is constructed to substitute
  9.2454 +** a NULL value in place of the table column that would have
  9.2455 +** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
  9.2456 +** return can be used to deny an untrusted user access to individual
  9.2457 +** columns of a table.
  9.2458 +** ^If the action code is [SQLITE_DELETE] and the callback returns
  9.2459 +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  9.2460 +** [truncate optimization] is disabled and all rows are deleted individually.
  9.2461 +**
  9.2462 +** An authorizer is used when [sqlite3_prepare | preparing]
  9.2463 +** SQL statements from an untrusted source, to ensure that the SQL statements
  9.2464 +** do not try to access data they are not allowed to see, or that they do not
  9.2465 +** try to execute malicious statements that damage the database.  For
  9.2466 +** example, an application may allow a user to enter arbitrary
  9.2467 +** SQL queries for evaluation by a database.  But the application does
  9.2468 +** not want the user to be able to make arbitrary changes to the
  9.2469 +** database.  An authorizer could then be put in place while the
  9.2470 +** user-entered SQL is being [sqlite3_prepare | prepared] that
  9.2471 +** disallows everything except [SELECT] statements.
  9.2472 +**
  9.2473 +** Applications that need to process SQL from untrusted sources
  9.2474 +** might also consider lowering resource limits using [sqlite3_limit()]
  9.2475 +** and limiting database size using the [max_page_count] [PRAGMA]
  9.2476 +** in addition to using an authorizer.
  9.2477 +**
  9.2478 +** ^(Only a single authorizer can be in place on a database connection
  9.2479 +** at a time.  Each call to sqlite3_set_authorizer overrides the
  9.2480 +** previous call.)^  ^Disable the authorizer by installing a NULL callback.
  9.2481 +** The authorizer is disabled by default.
  9.2482 +**
  9.2483 +** The authorizer callback must not do anything that will modify
  9.2484 +** the database connection that invoked the authorizer callback.
  9.2485 +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  9.2486 +** database connections for the meaning of "modify" in this paragraph.
  9.2487 +**
  9.2488 +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  9.2489 +** statement might be re-prepared during [sqlite3_step()] due to a 
  9.2490 +** schema change.  Hence, the application should ensure that the
  9.2491 +** correct authorizer callback remains in place during the [sqlite3_step()].
  9.2492 +**
  9.2493 +** ^Note that the authorizer callback is invoked only during
  9.2494 +** [sqlite3_prepare()] or its variants.  Authorization is not
  9.2495 +** performed during statement evaluation in [sqlite3_step()], unless
  9.2496 +** as stated in the previous paragraph, sqlite3_step() invokes
  9.2497 +** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  9.2498 +*/
  9.2499 +SQLITE_API int sqlite3_set_authorizer(
  9.2500 +  sqlite3*,
  9.2501 +  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  9.2502 +  void *pUserData
  9.2503 +);
  9.2504 +
  9.2505 +/*
  9.2506 +** CAPI3REF: Authorizer Return Codes
  9.2507 +**
  9.2508 +** The [sqlite3_set_authorizer | authorizer callback function] must
  9.2509 +** return either [SQLITE_OK] or one of these two constants in order
  9.2510 +** to signal SQLite whether or not the action is permitted.  See the
  9.2511 +** [sqlite3_set_authorizer | authorizer documentation] for additional
  9.2512 +** information.
  9.2513 +**
  9.2514 +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  9.2515 +** from the [sqlite3_vtab_on_conflict()] interface.
  9.2516 +*/
  9.2517 +#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
  9.2518 +#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
  9.2519 +
  9.2520 +/*
  9.2521 +** CAPI3REF: Authorizer Action Codes
  9.2522 +**
  9.2523 +** The [sqlite3_set_authorizer()] interface registers a callback function
  9.2524 +** that is invoked to authorize certain SQL statement actions.  The
  9.2525 +** second parameter to the callback is an integer code that specifies
  9.2526 +** what action is being authorized.  These are the integer action codes that
  9.2527 +** the authorizer callback may be passed.
  9.2528 +**
  9.2529 +** These action code values signify what kind of operation is to be
  9.2530 +** authorized.  The 3rd and 4th parameters to the authorization
  9.2531 +** callback function will be parameters or NULL depending on which of these
  9.2532 +** codes is used as the second parameter.  ^(The 5th parameter to the
  9.2533 +** authorizer callback is the name of the database ("main", "temp",
  9.2534 +** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
  9.2535 +** is the name of the inner-most trigger or view that is responsible for
  9.2536 +** the access attempt or NULL if this access attempt is directly from
  9.2537 +** top-level SQL code.
  9.2538 +*/
  9.2539 +/******************************************* 3rd ************ 4th ***********/
  9.2540 +#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
  9.2541 +#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
  9.2542 +#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
  9.2543 +#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
  9.2544 +#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
  9.2545 +#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
  9.2546 +#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
  9.2547 +#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
  9.2548 +#define SQLITE_DELETE                9   /* Table Name      NULL            */
  9.2549 +#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
  9.2550 +#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
  9.2551 +#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
  9.2552 +#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
  9.2553 +#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
  9.2554 +#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
  9.2555 +#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
  9.2556 +#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
  9.2557 +#define SQLITE_INSERT               18   /* Table Name      NULL            */
  9.2558 +#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
  9.2559 +#define SQLITE_READ                 20   /* Table Name      Column Name     */
  9.2560 +#define SQLITE_SELECT               21   /* NULL            NULL            */
  9.2561 +#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
  9.2562 +#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
  9.2563 +#define SQLITE_ATTACH               24   /* Filename        NULL            */
  9.2564 +#define SQLITE_DETACH               25   /* Database Name   NULL            */
  9.2565 +#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
  9.2566 +#define SQLITE_REINDEX              27   /* Index Name      NULL            */
  9.2567 +#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
  9.2568 +#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
  9.2569 +#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
  9.2570 +#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
  9.2571 +#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
  9.2572 +#define SQLITE_COPY                  0   /* No longer used */
  9.2573 +
  9.2574 +/*
  9.2575 +** CAPI3REF: Tracing And Profiling Functions
  9.2576 +**
  9.2577 +** These routines register callback functions that can be used for
  9.2578 +** tracing and profiling the execution of SQL statements.
  9.2579 +**
  9.2580 +** ^The callback function registered by sqlite3_trace() is invoked at
  9.2581 +** various times when an SQL statement is being run by [sqlite3_step()].
  9.2582 +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  9.2583 +** SQL statement text as the statement first begins executing.
  9.2584 +** ^(Additional sqlite3_trace() callbacks might occur
  9.2585 +** as each triggered subprogram is entered.  The callbacks for triggers
  9.2586 +** contain a UTF-8 SQL comment that identifies the trigger.)^
  9.2587 +**
  9.2588 +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  9.2589 +** the length of [bound parameter] expansion in the output of sqlite3_trace().
  9.2590 +**
  9.2591 +** ^The callback function registered by sqlite3_profile() is invoked
  9.2592 +** as each SQL statement finishes.  ^The profile callback contains
  9.2593 +** the original statement text and an estimate of wall-clock time
  9.2594 +** of how long that statement took to run.  ^The profile callback
  9.2595 +** time is in units of nanoseconds, however the current implementation
  9.2596 +** is only capable of millisecond resolution so the six least significant
  9.2597 +** digits in the time are meaningless.  Future versions of SQLite
  9.2598 +** might provide greater resolution on the profiler callback.  The
  9.2599 +** sqlite3_profile() function is considered experimental and is
  9.2600 +** subject to change in future versions of SQLite.
  9.2601 +*/
  9.2602 +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  9.2603 +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  9.2604 +   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  9.2605 +
  9.2606 +/*
  9.2607 +** CAPI3REF: Query Progress Callbacks
  9.2608 +**
  9.2609 +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  9.2610 +** function X to be invoked periodically during long running calls to
  9.2611 +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  9.2612 +** database connection D.  An example use for this
  9.2613 +** interface is to keep a GUI updated during a large query.
  9.2614 +**
  9.2615 +** ^The parameter P is passed through as the only parameter to the 
  9.2616 +** callback function X.  ^The parameter N is the approximate number of 
  9.2617 +** [virtual machine instructions] that are evaluated between successive
  9.2618 +** invocations of the callback X.  ^If N is less than one then the progress
  9.2619 +** handler is disabled.
  9.2620 +**
  9.2621 +** ^Only a single progress handler may be defined at one time per
  9.2622 +** [database connection]; setting a new progress handler cancels the
  9.2623 +** old one.  ^Setting parameter X to NULL disables the progress handler.
  9.2624 +** ^The progress handler is also disabled by setting N to a value less
  9.2625 +** than 1.
  9.2626 +**
  9.2627 +** ^If the progress callback returns non-zero, the operation is
  9.2628 +** interrupted.  This feature can be used to implement a
  9.2629 +** "Cancel" button on a GUI progress dialog box.
  9.2630 +**
  9.2631 +** The progress handler callback must not do anything that will modify
  9.2632 +** the database connection that invoked the progress handler.
  9.2633 +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  9.2634 +** database connections for the meaning of "modify" in this paragraph.
  9.2635 +**
  9.2636 +*/
  9.2637 +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  9.2638 +
  9.2639 +/*
  9.2640 +** CAPI3REF: Opening A New Database Connection
  9.2641 +**
  9.2642 +** ^These routines open an SQLite database file as specified by the 
  9.2643 +** filename argument. ^The filename argument is interpreted as UTF-8 for
  9.2644 +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  9.2645 +** order for sqlite3_open16(). ^(A [database connection] handle is usually
  9.2646 +** returned in *ppDb, even if an error occurs.  The only exception is that
  9.2647 +** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  9.2648 +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  9.2649 +** object.)^ ^(If the database is opened (and/or created) successfully, then
  9.2650 +** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
  9.2651 +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  9.2652 +** an English language description of the error following a failure of any
  9.2653 +** of the sqlite3_open() routines.
  9.2654 +**
  9.2655 +** ^The default encoding for the database will be UTF-8 if
  9.2656 +** sqlite3_open() or sqlite3_open_v2() is called and
  9.2657 +** UTF-16 in the native byte order if sqlite3_open16() is used.
  9.2658 +**
  9.2659 +** Whether or not an error occurs when it is opened, resources
  9.2660 +** associated with the [database connection] handle should be released by
  9.2661 +** passing it to [sqlite3_close()] when it is no longer required.
  9.2662 +**
  9.2663 +** The sqlite3_open_v2() interface works like sqlite3_open()
  9.2664 +** except that it accepts two additional parameters for additional control
  9.2665 +** over the new database connection.  ^(The flags parameter to
  9.2666 +** sqlite3_open_v2() can take one of
  9.2667 +** the following three values, optionally combined with the 
  9.2668 +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  9.2669 +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  9.2670 +**
  9.2671 +** <dl>
  9.2672 +** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  9.2673 +** <dd>The database is opened in read-only mode.  If the database does not
  9.2674 +** already exist, an error is returned.</dd>)^
  9.2675 +**
  9.2676 +** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  9.2677 +** <dd>The database is opened for reading and writing if possible, or reading
  9.2678 +** only if the file is write protected by the operating system.  In either
  9.2679 +** case the database must already exist, otherwise an error is returned.</dd>)^
  9.2680 +**
  9.2681 +** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  9.2682 +** <dd>The database is opened for reading and writing, and is created if
  9.2683 +** it does not already exist. This is the behavior that is always used for
  9.2684 +** sqlite3_open() and sqlite3_open16().</dd>)^
  9.2685 +** </dl>
  9.2686 +**
  9.2687 +** If the 3rd parameter to sqlite3_open_v2() is not one of the
  9.2688 +** combinations shown above optionally combined with other
  9.2689 +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  9.2690 +** then the behavior is undefined.
  9.2691 +**
  9.2692 +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  9.2693 +** opens in the multi-thread [threading mode] as long as the single-thread
  9.2694 +** mode has not been set at compile-time or start-time.  ^If the
  9.2695 +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  9.2696 +** in the serialized [threading mode] unless single-thread was
  9.2697 +** previously selected at compile-time or start-time.
  9.2698 +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  9.2699 +** eligible to use [shared cache mode], regardless of whether or not shared
  9.2700 +** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
  9.2701 +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  9.2702 +** participate in [shared cache mode] even if it is enabled.
  9.2703 +**
  9.2704 +** ^The fourth parameter to sqlite3_open_v2() is the name of the
  9.2705 +** [sqlite3_vfs] object that defines the operating system interface that
  9.2706 +** the new database connection should use.  ^If the fourth parameter is
  9.2707 +** a NULL pointer then the default [sqlite3_vfs] object is used.
  9.2708 +**
  9.2709 +** ^If the filename is ":memory:", then a private, temporary in-memory database
  9.2710 +** is created for the connection.  ^This in-memory database will vanish when
  9.2711 +** the database connection is closed.  Future versions of SQLite might
  9.2712 +** make use of additional special filenames that begin with the ":" character.
  9.2713 +** It is recommended that when a database filename actually does begin with
  9.2714 +** a ":" character you should prefix the filename with a pathname such as
  9.2715 +** "./" to avoid ambiguity.
  9.2716 +**
  9.2717 +** ^If the filename is an empty string, then a private, temporary
  9.2718 +** on-disk database will be created.  ^This private database will be
  9.2719 +** automatically deleted as soon as the database connection is closed.
  9.2720 +**
  9.2721 +** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  9.2722 +**
  9.2723 +** ^If [URI filename] interpretation is enabled, and the filename argument
  9.2724 +** begins with "file:", then the filename is interpreted as a URI. ^URI
  9.2725 +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  9.2726 +** set in the fourth argument to sqlite3_open_v2(), or if it has
  9.2727 +** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  9.2728 +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  9.2729 +** As of SQLite version 3.7.7, URI filename interpretation is turned off
  9.2730 +** by default, but future releases of SQLite might enable URI filename
  9.2731 +** interpretation by default.  See "[URI filenames]" for additional
  9.2732 +** information.
  9.2733 +**
  9.2734 +** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  9.2735 +** authority, then it must be either an empty string or the string 
  9.2736 +** "localhost". ^If the authority is not an empty string or "localhost", an 
  9.2737 +** error is returned to the caller. ^The fragment component of a URI, if 
  9.2738 +** present, is ignored.
  9.2739 +**
  9.2740 +** ^SQLite uses the path component of the URI as the name of the disk file
  9.2741 +** which contains the database. ^If the path begins with a '/' character, 
  9.2742 +** then it is interpreted as an absolute path. ^If the path does not begin 
  9.2743 +** with a '/' (meaning that the authority section is omitted from the URI)
  9.2744 +** then the path is interpreted as a relative path. 
  9.2745 +** ^On windows, the first component of an absolute path 
  9.2746 +** is a drive specification (e.g. "C:").
  9.2747 +**
  9.2748 +** [[core URI query parameters]]
  9.2749 +** The query component of a URI may contain parameters that are interpreted
  9.2750 +** either by SQLite itself, or by a [VFS | custom VFS implementation].
  9.2751 +** SQLite interprets the following three query parameters:
  9.2752 +**
  9.2753 +** <ul>
  9.2754 +**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  9.2755 +**     a VFS object that provides the operating system interface that should
  9.2756 +**     be used to access the database file on disk. ^If this option is set to
  9.2757 +**     an empty string the default VFS object is used. ^Specifying an unknown
  9.2758 +**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  9.2759 +**     present, then the VFS specified by the option takes precedence over
  9.2760 +**     the value passed as the fourth parameter to sqlite3_open_v2().
  9.2761 +**
  9.2762 +**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  9.2763 +**     "rwc", or "memory". Attempting to set it to any other value is
  9.2764 +**     an error)^. 
  9.2765 +**     ^If "ro" is specified, then the database is opened for read-only 
  9.2766 +**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
  9.2767 +**     third argument to sqlite3_open_v2(). ^If the mode option is set to 
  9.2768 +**     "rw", then the database is opened for read-write (but not create) 
  9.2769 +**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
  9.2770 +**     been set. ^Value "rwc" is equivalent to setting both 
  9.2771 +**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
  9.2772 +**     set to "memory" then a pure [in-memory database] that never reads
  9.2773 +**     or writes from disk is used. ^It is an error to specify a value for
  9.2774 +**     the mode parameter that is less restrictive than that specified by
  9.2775 +**     the flags passed in the third parameter to sqlite3_open_v2().
  9.2776 +**
  9.2777 +**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  9.2778 +**     "private". ^Setting it to "shared" is equivalent to setting the
  9.2779 +**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  9.2780 +**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
  9.2781 +**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  9.2782 +**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  9.2783 +**     a URI filename, its value overrides any behavior requested by setting
  9.2784 +**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  9.2785 +** </ul>
  9.2786 +**
  9.2787 +** ^Specifying an unknown parameter in the query component of a URI is not an
  9.2788 +** error.  Future versions of SQLite might understand additional query
  9.2789 +** parameters.  See "[query parameters with special meaning to SQLite]" for
  9.2790 +** additional information.
  9.2791 +**
  9.2792 +** [[URI filename examples]] <h3>URI filename examples</h3>
  9.2793 +**
  9.2794 +** <table border="1" align=center cellpadding=5>
  9.2795 +** <tr><th> URI filenames <th> Results
  9.2796 +** <tr><td> file:data.db <td> 
  9.2797 +**          Open the file "data.db" in the current directory.
  9.2798 +** <tr><td> file:/home/fred/data.db<br>
  9.2799 +**          file:///home/fred/data.db <br> 
  9.2800 +**          file://localhost/home/fred/data.db <br> <td> 
  9.2801 +**          Open the database file "/home/fred/data.db".
  9.2802 +** <tr><td> file://darkstar/home/fred/data.db <td> 
  9.2803 +**          An error. "darkstar" is not a recognized authority.
  9.2804 +** <tr><td style="white-space:nowrap"> 
  9.2805 +**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  9.2806 +**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
  9.2807 +**          C:. Note that the %20 escaping in this example is not strictly 
  9.2808 +**          necessary - space characters can be used literally
  9.2809 +**          in URI filenames.
  9.2810 +** <tr><td> file:data.db?mode=ro&cache=private <td> 
  9.2811 +**          Open file "data.db" in the current directory for read-only access.
  9.2812 +**          Regardless of whether or not shared-cache mode is enabled by
  9.2813 +**          default, use a private cache.
  9.2814 +** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  9.2815 +**          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  9.2816 +** <tr><td> file:data.db?mode=readonly <td> 
  9.2817 +**          An error. "readonly" is not a valid option for the "mode" parameter.
  9.2818 +** </table>
  9.2819 +**
  9.2820 +** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  9.2821 +** query components of a URI. A hexadecimal escape sequence consists of a
  9.2822 +** percent sign - "%" - followed by exactly two hexadecimal digits 
  9.2823 +** specifying an octet value. ^Before the path or query components of a
  9.2824 +** URI filename are interpreted, they are encoded using UTF-8 and all 
  9.2825 +** hexadecimal escape sequences replaced by a single byte containing the
  9.2826 +** corresponding octet. If this process generates an invalid UTF-8 encoding,
  9.2827 +** the results are undefined.
  9.2828 +**
  9.2829 +** <b>Note to Windows users:</b>  The encoding used for the filename argument
  9.2830 +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  9.2831 +** codepage is currently defined.  Filenames containing international
  9.2832 +** characters must be converted to UTF-8 prior to passing them into
  9.2833 +** sqlite3_open() or sqlite3_open_v2().
  9.2834 +**
  9.2835 +** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  9.2836 +** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
  9.2837 +** features that require the use of temporary files may fail.
  9.2838 +**
  9.2839 +** See also: [sqlite3_temp_directory]
  9.2840 +*/
  9.2841 +SQLITE_API int sqlite3_open(
  9.2842 +  const char *filename,   /* Database filename (UTF-8) */
  9.2843 +  sqlite3 **ppDb          /* OUT: SQLite db handle */
  9.2844 +);
  9.2845 +SQLITE_API int sqlite3_open16(
  9.2846 +  const void *filename,   /* Database filename (UTF-16) */
  9.2847 +  sqlite3 **ppDb          /* OUT: SQLite db handle */
  9.2848 +);
  9.2849 +SQLITE_API int sqlite3_open_v2(
  9.2850 +  const char *filename,   /* Database filename (UTF-8) */
  9.2851 +  sqlite3 **ppDb,         /* OUT: SQLite db handle */
  9.2852 +  int flags,              /* Flags */
  9.2853 +  const char *zVfs        /* Name of VFS module to use */
  9.2854 +);
  9.2855 +
  9.2856 +/*
  9.2857 +** CAPI3REF: Obtain Values For URI Parameters
  9.2858 +**
  9.2859 +** These are utility routines, useful to VFS implementations, that check
  9.2860 +** to see if a database file was a URI that contained a specific query 
  9.2861 +** parameter, and if so obtains the value of that query parameter.
  9.2862 +**
  9.2863 +** If F is the database filename pointer passed into the xOpen() method of 
  9.2864 +** a VFS implementation when the flags parameter to xOpen() has one or 
  9.2865 +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  9.2866 +** P is the name of the query parameter, then
  9.2867 +** sqlite3_uri_parameter(F,P) returns the value of the P
  9.2868 +** parameter if it exists or a NULL pointer if P does not appear as a 
  9.2869 +** query parameter on F.  If P is a query parameter of F
  9.2870 +** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  9.2871 +** a pointer to an empty string.
  9.2872 +**
  9.2873 +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  9.2874 +** parameter and returns true (1) or false (0) according to the value
  9.2875 +** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  9.2876 +** value of query parameter P is one of "yes", "true", or "on" in any
  9.2877 +** case or if the value begins with a non-zero number.  The 
  9.2878 +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  9.2879 +** query parameter P is one of "no", "false", or "off" in any case or
  9.2880 +** if the value begins with a numeric zero.  If P is not a query
  9.2881 +** parameter on F or if the value of P is does not match any of the
  9.2882 +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  9.2883 +**
  9.2884 +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  9.2885 +** 64-bit signed integer and returns that integer, or D if P does not
  9.2886 +** exist.  If the value of P is something other than an integer, then
  9.2887 +** zero is returned.
  9.2888 +** 
  9.2889 +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  9.2890 +** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
  9.2891 +** is not a database file pathname pointer that SQLite passed into the xOpen
  9.2892 +** VFS method, then the behavior of this routine is undefined and probably
  9.2893 +** undesirable.
  9.2894 +*/
  9.2895 +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  9.2896 +SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  9.2897 +SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  9.2898 +
  9.2899 +
  9.2900 +/*
  9.2901 +** CAPI3REF: Error Codes And Messages
  9.2902 +**
  9.2903 +** ^The sqlite3_errcode() interface returns the numeric [result code] or
  9.2904 +** [extended result code] for the most recent failed sqlite3_* API call
  9.2905 +** associated with a [database connection]. If a prior API call failed
  9.2906 +** but the most recent API call succeeded, the return value from
  9.2907 +** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
  9.2908 +** interface is the same except that it always returns the 
  9.2909 +** [extended result code] even when extended result codes are
  9.2910 +** disabled.
  9.2911 +**
  9.2912 +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  9.2913 +** text that describes the error, as either UTF-8 or UTF-16 respectively.
  9.2914 +** ^(Memory to hold the error message string is managed internally.
  9.2915 +** The application does not need to worry about freeing the result.
  9.2916 +** However, the error string might be overwritten or deallocated by
  9.2917 +** subsequent calls to other SQLite interface functions.)^
  9.2918 +**
  9.2919 +** ^The sqlite3_errstr() interface returns the English-language text
  9.2920 +** that describes the [result code], as UTF-8.
  9.2921 +** ^(Memory to hold the error message string is managed internally
  9.2922 +** and must not be freed by the application)^.
  9.2923 +**
  9.2924 +** When the serialized [threading mode] is in use, it might be the
  9.2925 +** case that a second error occurs on a separate thread in between
  9.2926 +** the time of the first error and the call to these interfaces.
  9.2927 +** When that happens, the second error will be reported since these
  9.2928 +** interfaces always report the most recent result.  To avoid
  9.2929 +** this, each thread can obtain exclusive use of the [database connection] D
  9.2930 +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  9.2931 +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  9.2932 +** all calls to the interfaces listed here are completed.
  9.2933 +**
  9.2934 +** If an interface fails with SQLITE_MISUSE, that means the interface
  9.2935 +** was invoked incorrectly by the application.  In that case, the
  9.2936 +** error code and message may or may not be set.
  9.2937 +*/
  9.2938 +SQLITE_API int sqlite3_errcode(sqlite3 *db);
  9.2939 +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  9.2940 +SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  9.2941 +SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  9.2942 +SQLITE_API const char *sqlite3_errstr(int);
  9.2943 +
  9.2944 +/*
  9.2945 +** CAPI3REF: SQL Statement Object
  9.2946 +** KEYWORDS: {prepared statement} {prepared statements}
  9.2947 +**
  9.2948 +** An instance of this object represents a single SQL statement.
  9.2949 +** This object is variously known as a "prepared statement" or a
  9.2950 +** "compiled SQL statement" or simply as a "statement".
  9.2951 +**
  9.2952 +** The life of a statement object goes something like this:
  9.2953 +**
  9.2954 +** <ol>
  9.2955 +** <li> Create the object using [sqlite3_prepare_v2()] or a related
  9.2956 +**      function.
  9.2957 +** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  9.2958 +**      interfaces.
  9.2959 +** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  9.2960 +** <li> Reset the statement using [sqlite3_reset()] then go back
  9.2961 +**      to step 2.  Do this zero or more times.
  9.2962 +** <li> Destroy the object using [sqlite3_finalize()].
  9.2963 +** </ol>
  9.2964 +**
  9.2965 +** Refer to documentation on individual methods above for additional
  9.2966 +** information.
  9.2967 +*/
  9.2968 +typedef struct sqlite3_stmt sqlite3_stmt;
  9.2969 +
  9.2970 +/*
  9.2971 +** CAPI3REF: Run-time Limits
  9.2972 +**
  9.2973 +** ^(This interface allows the size of various constructs to be limited
  9.2974 +** on a connection by connection basis.  The first parameter is the
  9.2975 +** [database connection] whose limit is to be set or queried.  The
  9.2976 +** second parameter is one of the [limit categories] that define a
  9.2977 +** class of constructs to be size limited.  The third parameter is the
  9.2978 +** new limit for that construct.)^
  9.2979 +**
  9.2980 +** ^If the new limit is a negative number, the limit is unchanged.
  9.2981 +** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
  9.2982 +** [limits | hard upper bound]
  9.2983 +** set at compile-time by a C preprocessor macro called
  9.2984 +** [limits | SQLITE_MAX_<i>NAME</i>].
  9.2985 +** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  9.2986 +** ^Attempts to increase a limit above its hard upper bound are
  9.2987 +** silently truncated to the hard upper bound.
  9.2988 +**
  9.2989 +** ^Regardless of whether or not the limit was changed, the 
  9.2990 +** [sqlite3_limit()] interface returns the prior value of the limit.
  9.2991 +** ^Hence, to find the current value of a limit without changing it,
  9.2992 +** simply invoke this interface with the third parameter set to -1.
  9.2993 +**
  9.2994 +** Run-time limits are intended for use in applications that manage
  9.2995 +** both their own internal database and also databases that are controlled
  9.2996 +** by untrusted external sources.  An example application might be a
  9.2997 +** web browser that has its own databases for storing history and
  9.2998 +** separate databases controlled by JavaScript applications downloaded
  9.2999 +** off the Internet.  The internal databases can be given the
  9.3000 +** large, default limits.  Databases managed by external sources can
  9.3001 +** be given much smaller limits designed to prevent a denial of service
  9.3002 +** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
  9.3003 +** interface to further control untrusted SQL.  The size of the database
  9.3004 +** created by an untrusted script can be contained using the
  9.3005 +** [max_page_count] [PRAGMA].
  9.3006 +**
  9.3007 +** New run-time limit categories may be added in future releases.
  9.3008 +*/
  9.3009 +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  9.3010 +
  9.3011 +/*
  9.3012 +** CAPI3REF: Run-Time Limit Categories
  9.3013 +** KEYWORDS: {limit category} {*limit categories}
  9.3014 +**
  9.3015 +** These constants define various performance limits
  9.3016 +** that can be lowered at run-time using [sqlite3_limit()].
  9.3017 +** The synopsis of the meanings of the various limits is shown below.
  9.3018 +** Additional information is available at [limits | Limits in SQLite].
  9.3019 +**
  9.3020 +** <dl>
  9.3021 +** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  9.3022 +** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  9.3023 +**
  9.3024 +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  9.3025 +** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  9.3026 +**
  9.3027 +** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  9.3028 +** <dd>The maximum number of columns in a table definition or in the
  9.3029 +** result set of a [SELECT] or the maximum number of columns in an index
  9.3030 +** or in an ORDER BY or GROUP BY clause.</dd>)^
  9.3031 +**
  9.3032 +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  9.3033 +** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  9.3034 +**
  9.3035 +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  9.3036 +** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  9.3037 +**
  9.3038 +** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  9.3039 +** <dd>The maximum number of instructions in a virtual machine program
  9.3040 +** used to implement an SQL statement.  This limit is not currently
  9.3041 +** enforced, though that might be added in some future release of
  9.3042 +** SQLite.</dd>)^
  9.3043 +**
  9.3044 +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  9.3045 +** <dd>The maximum number of arguments on a function.</dd>)^
  9.3046 +**
  9.3047 +** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  9.3048 +** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  9.3049 +**
  9.3050 +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  9.3051 +** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  9.3052 +** <dd>The maximum length of the pattern argument to the [LIKE] or
  9.3053 +** [GLOB] operators.</dd>)^
  9.3054 +**
  9.3055 +** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  9.3056 +** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  9.3057 +** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  9.3058 +**
  9.3059 +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  9.3060 +** <dd>The maximum depth of recursion for triggers.</dd>)^
  9.3061 +** </dl>
  9.3062 +*/
  9.3063 +#define SQLITE_LIMIT_LENGTH                    0
  9.3064 +#define SQLITE_LIMIT_SQL_LENGTH                1
  9.3065 +#define SQLITE_LIMIT_COLUMN                    2
  9.3066 +#define SQLITE_LIMIT_EXPR_DEPTH                3
  9.3067 +#define SQLITE_LIMIT_COMPOUND_SELECT           4
  9.3068 +#define SQLITE_LIMIT_VDBE_OP                   5
  9.3069 +#define SQLITE_LIMIT_FUNCTION_ARG              6
  9.3070 +#define SQLITE_LIMIT_ATTACHED                  7
  9.3071 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
  9.3072 +#define SQLITE_LIMIT_VARIABLE_NUMBER           9
  9.3073 +#define SQLITE_LIMIT_TRIGGER_DEPTH            10
  9.3074 +
  9.3075 +/*
  9.3076 +** CAPI3REF: Compiling An SQL Statement
  9.3077 +** KEYWORDS: {SQL statement compiler}
  9.3078 +**
  9.3079 +** To execute an SQL query, it must first be compiled into a byte-code
  9.3080 +** program using one of these routines.
  9.3081 +**
  9.3082 +** The first argument, "db", is a [database connection] obtained from a
  9.3083 +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  9.3084 +** [sqlite3_open16()].  The database connection must not have been closed.
  9.3085 +**
  9.3086 +** The second argument, "zSql", is the statement to be compiled, encoded
  9.3087 +** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
  9.3088 +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  9.3089 +** use UTF-16.
  9.3090 +**
  9.3091 +** ^If the nByte argument is less than zero, then zSql is read up to the
  9.3092 +** first zero terminator. ^If nByte is non-negative, then it is the maximum
  9.3093 +** number of  bytes read from zSql.  ^When nByte is non-negative, the
  9.3094 +** zSql string ends at either the first '\000' or '\u0000' character or
  9.3095 +** the nByte-th byte, whichever comes first. If the caller knows
  9.3096 +** that the supplied string is nul-terminated, then there is a small
  9.3097 +** performance advantage to be gained by passing an nByte parameter that
  9.3098 +** is equal to the number of bytes in the input string <i>including</i>
  9.3099 +** the nul-terminator bytes as this saves SQLite from having to
  9.3100 +** make a copy of the input string.
  9.3101 +**
  9.3102 +** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  9.3103 +** past the end of the first SQL statement in zSql.  These routines only
  9.3104 +** compile the first statement in zSql, so *pzTail is left pointing to
  9.3105 +** what remains uncompiled.
  9.3106 +**
  9.3107 +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  9.3108 +** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
  9.3109 +** to NULL.  ^If the input text contains no SQL (if the input is an empty
  9.3110 +** string or a comment) then *ppStmt is set to NULL.
  9.3111 +** The calling procedure is responsible for deleting the compiled
  9.3112 +** SQL statement using [sqlite3_finalize()] after it has finished with it.
  9.3113 +** ppStmt may not be NULL.
  9.3114 +**
  9.3115 +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  9.3116 +** otherwise an [error code] is returned.
  9.3117 +**
  9.3118 +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  9.3119 +** recommended for all new programs. The two older interfaces are retained
  9.3120 +** for backwards compatibility, but their use is discouraged.
  9.3121 +** ^In the "v2" interfaces, the prepared statement
  9.3122 +** that is returned (the [sqlite3_stmt] object) contains a copy of the
  9.3123 +** original SQL text. This causes the [sqlite3_step()] interface to
  9.3124 +** behave differently in three ways:
  9.3125 +**
  9.3126 +** <ol>
  9.3127 +** <li>
  9.3128 +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  9.3129 +** always used to do, [sqlite3_step()] will automatically recompile the SQL
  9.3130 +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  9.3131 +** retries will occur before sqlite3_step() gives up and returns an error.
  9.3132 +** </li>
  9.3133 +**
  9.3134 +** <li>
  9.3135 +** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  9.3136 +** [error codes] or [extended error codes].  ^The legacy behavior was that
  9.3137 +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  9.3138 +** and the application would have to make a second call to [sqlite3_reset()]
  9.3139 +** in order to find the underlying cause of the problem. With the "v2" prepare
  9.3140 +** interfaces, the underlying reason for the error is returned immediately.
  9.3141 +** </li>
  9.3142 +**
  9.3143 +** <li>
  9.3144 +** ^If the specific value bound to [parameter | host parameter] in the 
  9.3145 +** WHERE clause might influence the choice of query plan for a statement,
  9.3146 +** then the statement will be automatically recompiled, as if there had been 
  9.3147 +** a schema change, on the first  [sqlite3_step()] call following any change
  9.3148 +** to the [sqlite3_bind_text | bindings] of that [parameter]. 
  9.3149 +** ^The specific value of WHERE-clause [parameter] might influence the 
  9.3150 +** choice of query plan if the parameter is the left-hand side of a [LIKE]
  9.3151 +** or [GLOB] operator or if the parameter is compared to an indexed column
  9.3152 +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  9.3153 +** </li>
  9.3154 +** </ol>
  9.3155 +*/
  9.3156 +SQLITE_API int sqlite3_prepare(
  9.3157 +  sqlite3 *db,            /* Database handle */
  9.3158 +  const char *zSql,       /* SQL statement, UTF-8 encoded */
  9.3159 +  int nByte,              /* Maximum length of zSql in bytes. */
  9.3160 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  9.3161 +  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  9.3162 +);
  9.3163 +SQLITE_API int sqlite3_prepare_v2(
  9.3164 +  sqlite3 *db,            /* Database handle */
  9.3165 +  const char *zSql,       /* SQL statement, UTF-8 encoded */
  9.3166 +  int nByte,              /* Maximum length of zSql in bytes. */
  9.3167 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  9.3168 +  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  9.3169 +);
  9.3170 +SQLITE_API int sqlite3_prepare16(
  9.3171 +  sqlite3 *db,            /* Database handle */
  9.3172 +  const void *zSql,       /* SQL statement, UTF-16 encoded */
  9.3173 +  int nByte,              /* Maximum length of zSql in bytes. */
  9.3174 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  9.3175 +  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  9.3176 +);
  9.3177 +SQLITE_API int sqlite3_prepare16_v2(
  9.3178 +  sqlite3 *db,            /* Database handle */
  9.3179 +  const void *zSql,       /* SQL statement, UTF-16 encoded */
  9.3180 +  int nByte,              /* Maximum length of zSql in bytes. */
  9.3181 +  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  9.3182 +  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  9.3183 +);
  9.3184 +
  9.3185 +/*
  9.3186 +** CAPI3REF: Retrieving Statement SQL
  9.3187 +**
  9.3188 +** ^This interface can be used to retrieve a saved copy of the original
  9.3189 +** SQL text used to create a [prepared statement] if that statement was
  9.3190 +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  9.3191 +*/
  9.3192 +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  9.3193 +
  9.3194 +/*
  9.3195 +** CAPI3REF: Determine If An SQL Statement Writes The Database
  9.3196 +**
  9.3197 +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  9.3198 +** and only if the [prepared statement] X makes no direct changes to
  9.3199 +** the content of the database file.
  9.3200 +**
  9.3201 +** Note that [application-defined SQL functions] or
  9.3202 +** [virtual tables] might change the database indirectly as a side effect.  
  9.3203 +** ^(For example, if an application defines a function "eval()" that 
  9.3204 +** calls [sqlite3_exec()], then the following SQL statement would
  9.3205 +** change the database file through side-effects:
  9.3206 +**
  9.3207 +** <blockquote><pre>
  9.3208 +**    SELECT eval('DELETE FROM t1') FROM t2;
  9.3209 +** </pre></blockquote>
  9.3210 +**
  9.3211 +** But because the [SELECT] statement does not change the database file
  9.3212 +** directly, sqlite3_stmt_readonly() would still return true.)^
  9.3213 +**
  9.3214 +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  9.3215 +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  9.3216 +** since the statements themselves do not actually modify the database but
  9.3217 +** rather they control the timing of when other statements modify the 
  9.3218 +** database.  ^The [ATTACH] and [DETACH] statements also cause
  9.3219 +** sqlite3_stmt_readonly() to return true since, while those statements
  9.3220 +** change the configuration of a database connection, they do not make 
  9.3221 +** changes to the content of the database files on disk.
  9.3222 +*/
  9.3223 +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  9.3224 +
  9.3225 +/*
  9.3226 +** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  9.3227 +**
  9.3228 +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  9.3229 +** [prepared statement] S has been stepped at least once using 
  9.3230 +** [sqlite3_step(S)] but has not run to completion and/or has not 
  9.3231 +** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
  9.3232 +** interface returns false if S is a NULL pointer.  If S is not a 
  9.3233 +** NULL pointer and is not a pointer to a valid [prepared statement]
  9.3234 +** object, then the behavior is undefined and probably undesirable.
  9.3235 +**
  9.3236 +** This interface can be used in combination [sqlite3_next_stmt()]
  9.3237 +** to locate all prepared statements associated with a database 
  9.3238 +** connection that are in need of being reset.  This can be used,
  9.3239 +** for example, in diagnostic routines to search for prepared 
  9.3240 +** statements that are holding a transaction open.
  9.3241 +*/
  9.3242 +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  9.3243 +
  9.3244 +/*
  9.3245 +** CAPI3REF: Dynamically Typed Value Object
  9.3246 +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  9.3247 +**
  9.3248 +** SQLite uses the sqlite3_value object to represent all values
  9.3249 +** that can be stored in a database table. SQLite uses dynamic typing
  9.3250 +** for the values it stores.  ^Values stored in sqlite3_value objects
  9.3251 +** can be integers, floating point values, strings, BLOBs, or NULL.
  9.3252 +**
  9.3253 +** An sqlite3_value object may be either "protected" or "unprotected".
  9.3254 +** Some interfaces require a protected sqlite3_value.  Other interfaces
  9.3255 +** will accept either a protected or an unprotected sqlite3_value.
  9.3256 +** Every interface that accepts sqlite3_value arguments specifies
  9.3257 +** whether or not it requires a protected sqlite3_value.
  9.3258 +**
  9.3259 +** The terms "protected" and "unprotected" refer to whether or not
  9.3260 +** a mutex is held.  An internal mutex is held for a protected
  9.3261 +** sqlite3_value object but no mutex is held for an unprotected
  9.3262 +** sqlite3_value object.  If SQLite is compiled to be single-threaded
  9.3263 +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  9.3264 +** or if SQLite is run in one of reduced mutex modes 
  9.3265 +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  9.3266 +** then there is no distinction between protected and unprotected
  9.3267 +** sqlite3_value objects and they can be used interchangeably.  However,
  9.3268 +** for maximum code portability it is recommended that applications
  9.3269 +** still make the distinction between protected and unprotected
  9.3270 +** sqlite3_value objects even when not strictly required.
  9.3271 +**
  9.3272 +** ^The sqlite3_value objects that are passed as parameters into the
  9.3273 +** implementation of [application-defined SQL functions] are protected.
  9.3274 +** ^The sqlite3_value object returned by
  9.3275 +** [sqlite3_column_value()] is unprotected.
  9.3276 +** Unprotected sqlite3_value objects may only be used with
  9.3277 +** [sqlite3_result_value()] and [sqlite3_bind_value()].
  9.3278 +** The [sqlite3_value_blob | sqlite3_value_type()] family of
  9.3279 +** interfaces require protected sqlite3_value objects.
  9.3280 +*/
  9.3281 +typedef struct Mem sqlite3_value;
  9.3282 +
  9.3283 +/*
  9.3284 +** CAPI3REF: SQL Function Context Object
  9.3285 +**
  9.3286 +** The context in which an SQL function executes is stored in an
  9.3287 +** sqlite3_context object.  ^A pointer to an sqlite3_context object
  9.3288 +** is always first parameter to [application-defined SQL functions].
  9.3289 +** The application-defined SQL function implementation will pass this
  9.3290 +** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  9.3291 +** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  9.3292 +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  9.3293 +** and/or [sqlite3_set_auxdata()].
  9.3294 +*/
  9.3295 +typedef struct sqlite3_context sqlite3_context;
  9.3296 +
  9.3297 +/*
  9.3298 +** CAPI3REF: Binding Values To Prepared Statements
  9.3299 +** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  9.3300 +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  9.3301 +**
  9.3302 +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  9.3303 +** literals may be replaced by a [parameter] that matches one of following
  9.3304 +** templates:
  9.3305 +**
  9.3306 +** <ul>
  9.3307 +** <li>  ?
  9.3308 +** <li>  ?NNN
  9.3309 +** <li>  :VVV
  9.3310 +** <li>  @VVV
  9.3311 +** <li>  $VVV
  9.3312 +** </ul>
  9.3313 +**
  9.3314 +** In the templates above, NNN represents an integer literal,
  9.3315 +** and VVV represents an alphanumeric identifier.)^  ^The values of these
  9.3316 +** parameters (also called "host parameter names" or "SQL parameters")
  9.3317 +** can be set using the sqlite3_bind_*() routines defined here.
  9.3318 +**
  9.3319 +** ^The first argument to the sqlite3_bind_*() routines is always
  9.3320 +** a pointer to the [sqlite3_stmt] object returned from
  9.3321 +** [sqlite3_prepare_v2()] or its variants.
  9.3322 +**
  9.3323 +** ^The second argument is the index of the SQL parameter to be set.
  9.3324 +** ^The leftmost SQL parameter has an index of 1.  ^When the same named
  9.3325 +** SQL parameter is used more than once, second and subsequent
  9.3326 +** occurrences have the same index as the first occurrence.
  9.3327 +** ^The index for named parameters can be looked up using the
  9.3328 +** [sqlite3_bind_parameter_index()] API if desired.  ^The index
  9.3329 +** for "?NNN" parameters is the value of NNN.
  9.3330 +** ^The NNN value must be between 1 and the [sqlite3_limit()]
  9.3331 +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  9.3332 +**
  9.3333 +** ^The third argument is the value to bind to the parameter.
  9.3334 +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  9.3335 +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  9.3336 +** is ignored and the end result is the same as sqlite3_bind_null().
  9.3337 +**
  9.3338 +** ^(In those routines that have a fourth argument, its value is the
  9.3339 +** number of bytes in the parameter.  To be clear: the value is the
  9.3340 +** number of <u>bytes</u> in the value, not the number of characters.)^
  9.3341 +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  9.3342 +** is negative, then the length of the string is
  9.3343 +** the number of bytes up to the first zero terminator.
  9.3344 +** If the fourth parameter to sqlite3_bind_blob() is negative, then
  9.3345 +** the behavior is undefined.
  9.3346 +** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  9.3347 +** or sqlite3_bind_text16() then that parameter must be the byte offset
  9.3348 +** where the NUL terminator would occur assuming the string were NUL
  9.3349 +** terminated.  If any NUL characters occur at byte offsets less than 
  9.3350 +** the value of the fourth parameter then the resulting string value will
  9.3351 +** contain embedded NULs.  The result of expressions involving strings
  9.3352 +** with embedded NULs is undefined.
  9.3353 +**
  9.3354 +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  9.3355 +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  9.3356 +** string after SQLite has finished with it.  ^The destructor is called
  9.3357 +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  9.3358 +** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
  9.3359 +** ^If the fifth argument is
  9.3360 +** the special value [SQLITE_STATIC], then SQLite assumes that the
  9.3361 +** information is in static, unmanaged space and does not need to be freed.
  9.3362 +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  9.3363 +** SQLite makes its own private copy of the data immediately, before
  9.3364 +** the sqlite3_bind_*() routine returns.
  9.3365 +**
  9.3366 +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  9.3367 +** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
  9.3368 +** (just an integer to hold its size) while it is being processed.
  9.3369 +** Zeroblobs are intended to serve as placeholders for BLOBs whose
  9.3370 +** content is later written using
  9.3371 +** [sqlite3_blob_open | incremental BLOB I/O] routines.
  9.3372 +** ^A negative value for the zeroblob results in a zero-length BLOB.
  9.3373 +**
  9.3374 +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  9.3375 +** for the [prepared statement] or with a prepared statement for which
  9.3376 +** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  9.3377 +** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
  9.3378 +** routine is passed a [prepared statement] that has been finalized, the
  9.3379 +** result is undefined and probably harmful.
  9.3380 +**
  9.3381 +** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  9.3382 +** ^Unbound parameters are interpreted as NULL.
  9.3383 +**
  9.3384 +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  9.3385 +** [error code] if anything goes wrong.
  9.3386 +** ^[SQLITE_RANGE] is returned if the parameter
  9.3387 +** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
  9.3388 +**
  9.3389 +** See also: [sqlite3_bind_parameter_count()],
  9.3390 +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  9.3391 +*/
  9.3392 +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  9.3393 +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  9.3394 +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  9.3395 +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  9.3396 +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  9.3397 +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  9.3398 +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  9.3399 +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  9.3400 +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  9.3401 +
  9.3402 +/*
  9.3403 +** CAPI3REF: Number Of SQL Parameters
  9.3404 +**
  9.3405 +** ^This routine can be used to find the number of [SQL parameters]
  9.3406 +** in a [prepared statement].  SQL parameters are tokens of the
  9.3407 +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  9.3408 +** placeholders for values that are [sqlite3_bind_blob | bound]
  9.3409 +** to the parameters at a later time.
  9.3410 +**
  9.3411 +** ^(This routine actually returns the index of the largest (rightmost)
  9.3412 +** parameter. For all forms except ?NNN, this will correspond to the
  9.3413 +** number of unique parameters.  If parameters of the ?NNN form are used,
  9.3414 +** there may be gaps in the list.)^
  9.3415 +**
  9.3416 +** See also: [sqlite3_bind_blob|sqlite3_bind()],
  9.3417 +** [sqlite3_bind_parameter_name()], and
  9.3418 +** [sqlite3_bind_parameter_index()].
  9.3419 +*/
  9.3420 +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  9.3421 +
  9.3422 +/*
  9.3423 +** CAPI3REF: Name Of A Host Parameter
  9.3424 +**
  9.3425 +** ^The sqlite3_bind_parameter_name(P,N) interface returns
  9.3426 +** the name of the N-th [SQL parameter] in the [prepared statement] P.
  9.3427 +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  9.3428 +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  9.3429 +** respectively.
  9.3430 +** In other words, the initial ":" or "$" or "@" or "?"
  9.3431 +** is included as part of the name.)^
  9.3432 +** ^Parameters of the form "?" without a following integer have no name
  9.3433 +** and are referred to as "nameless" or "anonymous parameters".
  9.3434 +**
  9.3435 +** ^The first host parameter has an index of 1, not 0.
  9.3436 +**
  9.3437 +** ^If the value N is out of range or if the N-th parameter is
  9.3438 +** nameless, then NULL is returned.  ^The returned string is
  9.3439 +** always in UTF-8 encoding even if the named parameter was
  9.3440 +** originally specified as UTF-16 in [sqlite3_prepare16()] or
  9.3441 +** [sqlite3_prepare16_v2()].
  9.3442 +**
  9.3443 +** See also: [sqlite3_bind_blob|sqlite3_bind()],
  9.3444 +** [sqlite3_bind_parameter_count()], and
  9.3445 +** [sqlite3_bind_parameter_index()].
  9.3446 +*/
  9.3447 +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  9.3448 +
  9.3449 +/*
  9.3450 +** CAPI3REF: Index Of A Parameter With A Given Name
  9.3451 +**
  9.3452 +** ^Return the index of an SQL parameter given its name.  ^The
  9.3453 +** index value returned is suitable for use as the second
  9.3454 +** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
  9.3455 +** is returned if no matching parameter is found.  ^The parameter
  9.3456 +** name must be given in UTF-8 even if the original statement
  9.3457 +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  9.3458 +**
  9.3459 +** See also: [sqlite3_bind_blob|sqlite3_bind()],
  9.3460 +** [sqlite3_bind_parameter_count()], and
  9.3461 +** [sqlite3_bind_parameter_index()].
  9.3462 +*/
  9.3463 +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  9.3464 +
  9.3465 +/*
  9.3466 +** CAPI3REF: Reset All Bindings On A Prepared Statement
  9.3467 +**
  9.3468 +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  9.3469 +** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  9.3470 +** ^Use this routine to reset all host parameters to NULL.
  9.3471 +*/
  9.3472 +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  9.3473 +
  9.3474 +/*
  9.3475 +** CAPI3REF: Number Of Columns In A Result Set
  9.3476 +**
  9.3477 +** ^Return the number of columns in the result set returned by the
  9.3478 +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  9.3479 +** statement that does not return data (for example an [UPDATE]).
  9.3480 +**
  9.3481 +** See also: [sqlite3_data_count()]
  9.3482 +*/
  9.3483 +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  9.3484 +
  9.3485 +/*
  9.3486 +** CAPI3REF: Column Names In A Result Set
  9.3487 +**
  9.3488 +** ^These routines return the name assigned to a particular column
  9.3489 +** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
  9.3490 +** interface returns a pointer to a zero-terminated UTF-8 string
  9.3491 +** and sqlite3_column_name16() returns a pointer to a zero-terminated
  9.3492 +** UTF-16 string.  ^The first parameter is the [prepared statement]
  9.3493 +** that implements the [SELECT] statement. ^The second parameter is the
  9.3494 +** column number.  ^The leftmost column is number 0.
  9.3495 +**
  9.3496 +** ^The returned string pointer is valid until either the [prepared statement]
  9.3497 +** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  9.3498 +** reprepared by the first call to [sqlite3_step()] for a particular run
  9.3499 +** or until the next call to
  9.3500 +** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  9.3501 +**
  9.3502 +** ^If sqlite3_malloc() fails during the processing of either routine
  9.3503 +** (for example during a conversion from UTF-8 to UTF-16) then a
  9.3504 +** NULL pointer is returned.
  9.3505 +**
  9.3506 +** ^The name of a result column is the value of the "AS" clause for
  9.3507 +** that column, if there is an AS clause.  If there is no AS clause
  9.3508 +** then the name of the column is unspecified and may change from
  9.3509 +** one release of SQLite to the next.
  9.3510 +*/
  9.3511 +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  9.3512 +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  9.3513 +
  9.3514 +/*
  9.3515 +** CAPI3REF: Source Of Data In A Query Result
  9.3516 +**
  9.3517 +** ^These routines provide a means to determine the database, table, and
  9.3518 +** table column that is the origin of a particular result column in
  9.3519 +** [SELECT] statement.
  9.3520 +** ^The name of the database or table or column can be returned as
  9.3521 +** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
  9.3522 +** the database name, the _table_ routines return the table name, and
  9.3523 +** the origin_ routines return the column name.
  9.3524 +** ^The returned string is valid until the [prepared statement] is destroyed
  9.3525 +** using [sqlite3_finalize()] or until the statement is automatically
  9.3526 +** reprepared by the first call to [sqlite3_step()] for a particular run
  9.3527 +** or until the same information is requested
  9.3528 +** again in a different encoding.
  9.3529 +**
  9.3530 +** ^The names returned are the original un-aliased names of the
  9.3531 +** database, table, and column.
  9.3532 +**
  9.3533 +** ^The first argument to these interfaces is a [prepared statement].
  9.3534 +** ^These functions return information about the Nth result column returned by
  9.3535 +** the statement, where N is the second function argument.
  9.3536 +** ^The left-most column is column 0 for these routines.
  9.3537 +**
  9.3538 +** ^If the Nth column returned by the statement is an expression or
  9.3539 +** subquery and is not a column value, then all of these functions return
  9.3540 +** NULL.  ^These routine might also return NULL if a memory allocation error
  9.3541 +** occurs.  ^Otherwise, they return the name of the attached database, table,
  9.3542 +** or column that query result column was extracted from.
  9.3543 +**
  9.3544 +** ^As with all other SQLite APIs, those whose names end with "16" return
  9.3545 +** UTF-16 encoded strings and the other functions return UTF-8.
  9.3546 +**
  9.3547 +** ^These APIs are only available if the library was compiled with the
  9.3548 +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  9.3549 +**
  9.3550 +** If two or more threads call one or more of these routines against the same
  9.3551 +** prepared statement and column at the same time then the results are
  9.3552 +** undefined.
  9.3553 +**
  9.3554 +** If two or more threads call one or more
  9.3555 +** [sqlite3_column_database_name | column metadata interfaces]
  9.3556 +** for the same [prepared statement] and result column
  9.3557 +** at the same time then the results are undefined.
  9.3558 +*/
  9.3559 +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  9.3560 +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  9.3561 +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  9.3562 +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  9.3563 +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  9.3564 +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  9.3565 +
  9.3566 +/*
  9.3567 +** CAPI3REF: Declared Datatype Of A Query Result
  9.3568 +**
  9.3569 +** ^(The first parameter is a [prepared statement].
  9.3570 +** If this statement is a [SELECT] statement and the Nth column of the
  9.3571 +** returned result set of that [SELECT] is a table column (not an
  9.3572 +** expression or subquery) then the declared type of the table
  9.3573 +** column is returned.)^  ^If the Nth column of the result set is an
  9.3574 +** expression or subquery, then a NULL pointer is returned.
  9.3575 +** ^The returned string is always UTF-8 encoded.
  9.3576 +**
  9.3577 +** ^(For example, given the database schema:
  9.3578 +**
  9.3579 +** CREATE TABLE t1(c1 VARIANT);
  9.3580 +**
  9.3581 +** and the following statement to be compiled:
  9.3582 +**
  9.3583 +** SELECT c1 + 1, c1 FROM t1;
  9.3584 +**
  9.3585 +** this routine would return the string "VARIANT" for the second result
  9.3586 +** column (i==1), and a NULL pointer for the first result column (i==0).)^
  9.3587 +**
  9.3588 +** ^SQLite uses dynamic run-time typing.  ^So just because a column
  9.3589 +** is declared to contain a particular type does not mean that the
  9.3590 +** data stored in that column is of the declared type.  SQLite is
  9.3591 +** strongly typed, but the typing is dynamic not static.  ^Type
  9.3592 +** is associated with individual values, not with the containers
  9.3593 +** used to hold those values.
  9.3594 +*/
  9.3595 +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  9.3596 +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  9.3597 +
  9.3598 +/*
  9.3599 +** CAPI3REF: Evaluate An SQL Statement
  9.3600 +**
  9.3601 +** After a [prepared statement] has been prepared using either
  9.3602 +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  9.3603 +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  9.3604 +** must be called one or more times to evaluate the statement.
  9.3605 +**
  9.3606 +** The details of the behavior of the sqlite3_step() interface depend
  9.3607 +** on whether the statement was prepared using the newer "v2" interface
  9.3608 +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  9.3609 +** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
  9.3610 +** new "v2" interface is recommended for new applications but the legacy
  9.3611 +** interface will continue to be supported.
  9.3612 +**
  9.3613 +** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  9.3614 +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  9.3615 +** ^With the "v2" interface, any of the other [result codes] or
  9.3616 +** [extended result codes] might be returned as well.
  9.3617 +**
  9.3618 +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  9.3619 +** database locks it needs to do its job.  ^If the statement is a [COMMIT]
  9.3620 +** or occurs outside of an explicit transaction, then you can retry the
  9.3621 +** statement.  If the statement is not a [COMMIT] and occurs within an
  9.3622 +** explicit transaction then you should rollback the transaction before
  9.3623 +** continuing.
  9.3624 +**
  9.3625 +** ^[SQLITE_DONE] means that the statement has finished executing
  9.3626 +** successfully.  sqlite3_step() should not be called again on this virtual
  9.3627 +** machine without first calling [sqlite3_reset()] to reset the virtual
  9.3628 +** machine back to its initial state.
  9.3629 +**
  9.3630 +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  9.3631 +** is returned each time a new row of data is ready for processing by the
  9.3632 +** caller. The values may be accessed using the [column access functions].
  9.3633 +** sqlite3_step() is called again to retrieve the next row of data.
  9.3634 +**
  9.3635 +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  9.3636 +** violation) has occurred.  sqlite3_step() should not be called again on
  9.3637 +** the VM. More information may be found by calling [sqlite3_errmsg()].
  9.3638 +** ^With the legacy interface, a more specific error code (for example,
  9.3639 +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  9.3640 +** can be obtained by calling [sqlite3_reset()] on the
  9.3641 +** [prepared statement].  ^In the "v2" interface,
  9.3642 +** the more specific error code is returned directly by sqlite3_step().
  9.3643 +**
  9.3644 +** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  9.3645 +** Perhaps it was called on a [prepared statement] that has
  9.3646 +** already been [sqlite3_finalize | finalized] or on one that had
  9.3647 +** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
  9.3648 +** be the case that the same database connection is being used by two or
  9.3649 +** more threads at the same moment in time.
  9.3650 +**
  9.3651 +** For all versions of SQLite up to and including 3.6.23.1, a call to
  9.3652 +** [sqlite3_reset()] was required after sqlite3_step() returned anything
  9.3653 +** other than [SQLITE_ROW] before any subsequent invocation of
  9.3654 +** sqlite3_step().  Failure to reset the prepared statement using 
  9.3655 +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  9.3656 +** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
  9.3657 +** calling [sqlite3_reset()] automatically in this circumstance rather
  9.3658 +** than returning [SQLITE_MISUSE].  This is not considered a compatibility
  9.3659 +** break because any application that ever receives an SQLITE_MISUSE error
  9.3660 +** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
  9.3661 +** can be used to restore the legacy behavior.
  9.3662 +**
  9.3663 +** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  9.3664 +** API always returns a generic error code, [SQLITE_ERROR], following any
  9.3665 +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
  9.3666 +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  9.3667 +** specific [error codes] that better describes the error.
  9.3668 +** We admit that this is a goofy design.  The problem has been fixed
  9.3669 +** with the "v2" interface.  If you prepare all of your SQL statements
  9.3670 +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  9.3671 +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  9.3672 +** then the more specific [error codes] are returned directly
  9.3673 +** by sqlite3_step().  The use of the "v2" interface is recommended.
  9.3674 +*/
  9.3675 +SQLITE_API int sqlite3_step(sqlite3_stmt*);
  9.3676 +
  9.3677 +/*
  9.3678 +** CAPI3REF: Number of columns in a result set
  9.3679 +**
  9.3680 +** ^The sqlite3_data_count(P) interface returns the number of columns in the
  9.3681 +** current row of the result set of [prepared statement] P.
  9.3682 +** ^If prepared statement P does not have results ready to return
  9.3683 +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  9.3684 +** interfaces) then sqlite3_data_count(P) returns 0.
  9.3685 +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  9.3686 +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  9.3687 +** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
  9.3688 +** will return non-zero if previous call to [sqlite3_step](P) returned
  9.3689 +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  9.3690 +** where it always returns zero since each step of that multi-step
  9.3691 +** pragma returns 0 columns of data.
  9.3692 +**
  9.3693 +** See also: [sqlite3_column_count()]
  9.3694 +*/
  9.3695 +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  9.3696 +
  9.3697 +/*
  9.3698 +** CAPI3REF: Fundamental Datatypes
  9.3699 +** KEYWORDS: SQLITE_TEXT
  9.3700 +**
  9.3701 +** ^(Every value in SQLite has one of five fundamental datatypes:
  9.3702 +**
  9.3703 +** <ul>
  9.3704 +** <li> 64-bit signed integer
  9.3705 +** <li> 64-bit IEEE floating point number
  9.3706 +** <li> string
  9.3707 +** <li> BLOB
  9.3708 +** <li> NULL
  9.3709 +** </ul>)^
  9.3710 +**
  9.3711 +** These constants are codes for each of those types.
  9.3712 +**
  9.3713 +** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  9.3714 +** for a completely different meaning.  Software that links against both
  9.3715 +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  9.3716 +** SQLITE_TEXT.
  9.3717 +*/
  9.3718 +#define SQLITE_INTEGER  1
  9.3719 +#define SQLITE_FLOAT    2
  9.3720 +#define SQLITE_BLOB     4
  9.3721 +#define SQLITE_NULL     5
  9.3722 +#ifdef SQLITE_TEXT
  9.3723 +# undef SQLITE_TEXT
  9.3724 +#else
  9.3725 +# define SQLITE_TEXT     3
  9.3726 +#endif
  9.3727 +#define SQLITE3_TEXT     3
  9.3728 +
  9.3729 +/*
  9.3730 +** CAPI3REF: Result Values From A Query
  9.3731 +** KEYWORDS: {column access functions}
  9.3732 +**
  9.3733 +** These routines form the "result set" interface.
  9.3734 +**
  9.3735 +** ^These routines return information about a single column of the current
  9.3736 +** result row of a query.  ^In every case the first argument is a pointer
  9.3737 +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  9.3738 +** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  9.3739 +** and the second argument is the index of the column for which information
  9.3740 +** should be returned. ^The leftmost column of the result set has the index 0.
  9.3741 +** ^The number of columns in the result can be determined using
  9.3742 +** [sqlite3_column_count()].
  9.3743 +**
  9.3744 +** If the SQL statement does not currently point to a valid row, or if the
  9.3745 +** column index is out of range, the result is undefined.
  9.3746 +** These routines may only be called when the most recent call to
  9.3747 +** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  9.3748 +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  9.3749 +** If any of these routines are called after [sqlite3_reset()] or
  9.3750 +** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  9.3751 +** something other than [SQLITE_ROW], the results are undefined.
  9.3752 +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  9.3753 +** are called from a different thread while any of these routines
  9.3754 +** are pending, then the results are undefined.
  9.3755 +**
  9.3756 +** ^The sqlite3_column_type() routine returns the
  9.3757 +** [SQLITE_INTEGER | datatype code] for the initial data type
  9.3758 +** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
  9.3759 +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
  9.3760 +** returned by sqlite3_column_type() is only meaningful if no type
  9.3761 +** conversions have occurred as described below.  After a type conversion,
  9.3762 +** the value returned by sqlite3_column_type() is undefined.  Future
  9.3763 +** versions of SQLite may change the behavior of sqlite3_column_type()
  9.3764 +** following a type conversion.
  9.3765 +**
  9.3766 +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  9.3767 +** routine returns the number of bytes in that BLOB or string.
  9.3768 +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  9.3769 +** the string to UTF-8 and then returns the number of bytes.
  9.3770 +** ^If the result is a numeric value then sqlite3_column_bytes() uses
  9.3771 +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  9.3772 +** the number of bytes in that string.
  9.3773 +** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  9.3774 +**
  9.3775 +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  9.3776 +** routine returns the number of bytes in that BLOB or string.
  9.3777 +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  9.3778 +** the string to UTF-16 and then returns the number of bytes.
  9.3779 +** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  9.3780 +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  9.3781 +** the number of bytes in that string.
  9.3782 +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  9.3783 +**
  9.3784 +** ^The values returned by [sqlite3_column_bytes()] and 
  9.3785 +** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  9.3786 +** of the string.  ^For clarity: the values returned by
  9.3787 +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  9.3788 +** bytes in the string, not the number of characters.
  9.3789 +**
  9.3790 +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  9.3791 +** even empty strings, are always zero-terminated.  ^The return
  9.3792 +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  9.3793 +**
  9.3794 +** ^The object returned by [sqlite3_column_value()] is an
  9.3795 +** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
  9.3796 +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  9.3797 +** If the [unprotected sqlite3_value] object returned by
  9.3798 +** [sqlite3_column_value()] is used in any other way, including calls
  9.3799 +** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  9.3800 +** or [sqlite3_value_bytes()], then the behavior is undefined.
  9.3801 +**
  9.3802 +** These routines attempt to convert the value where appropriate.  ^For
  9.3803 +** example, if the internal representation is FLOAT and a text result
  9.3804 +** is requested, [sqlite3_snprintf()] is used internally to perform the
  9.3805 +** conversion automatically.  ^(The following table details the conversions
  9.3806 +** that are applied:
  9.3807 +**
  9.3808 +** <blockquote>
  9.3809 +** <table border="1">
  9.3810 +** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
  9.3811 +**
  9.3812 +** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
  9.3813 +** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
  9.3814 +** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
  9.3815 +** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
  9.3816 +** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
  9.3817 +** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
  9.3818 +** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
  9.3819 +** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
  9.3820 +** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
  9.3821 +** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
  9.3822 +** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
  9.3823 +** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
  9.3824 +** <tr><td>  TEXT    <td>   BLOB    <td> No change
  9.3825 +** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
  9.3826 +** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
  9.3827 +** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
  9.3828 +** </table>
  9.3829 +** </blockquote>)^
  9.3830 +**
  9.3831 +** The table above makes reference to standard C library functions atoi()
  9.3832 +** and atof().  SQLite does not really use these functions.  It has its
  9.3833 +** own equivalent internal routines.  The atoi() and atof() names are
  9.3834 +** used in the table for brevity and because they are familiar to most
  9.3835 +** C programmers.
  9.3836 +**
  9.3837 +** Note that when type conversions occur, pointers returned by prior
  9.3838 +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  9.3839 +** sqlite3_column_text16() may be invalidated.
  9.3840 +** Type conversions and pointer invalidations might occur
  9.3841 +** in the following cases:
  9.3842 +**
  9.3843 +** <ul>
  9.3844 +** <li> The initial content is a BLOB and sqlite3_column_text() or
  9.3845 +**      sqlite3_column_text16() is called.  A zero-terminator might
  9.3846 +**      need to be added to the string.</li>
  9.3847 +** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  9.3848 +**      sqlite3_column_text16() is called.  The content must be converted
  9.3849 +**      to UTF-16.</li>
  9.3850 +** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  9.3851 +**      sqlite3_column_text() is called.  The content must be converted
  9.3852 +**      to UTF-8.</li>
  9.3853 +** </ul>
  9.3854 +**
  9.3855 +** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  9.3856 +** not invalidate a prior pointer, though of course the content of the buffer
  9.3857 +** that the prior pointer references will have been modified.  Other kinds
  9.3858 +** of conversion are done in place when it is possible, but sometimes they
  9.3859 +** are not possible and in those cases prior pointers are invalidated.
  9.3860 +**
  9.3861 +** The safest and easiest to remember policy is to invoke these routines
  9.3862 +** in one of the following ways:
  9.3863 +**
  9.3864 +** <ul>
  9.3865 +**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  9.3866 +**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  9.3867 +**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  9.3868 +** </ul>
  9.3869 +**
  9.3870 +** In other words, you should call sqlite3_column_text(),
  9.3871 +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  9.3872 +** into the desired format, then invoke sqlite3_column_bytes() or
  9.3873 +** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
  9.3874 +** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  9.3875 +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  9.3876 +** with calls to sqlite3_column_bytes().
  9.3877 +**
  9.3878 +** ^The pointers returned are valid until a type conversion occurs as
  9.3879 +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  9.3880 +** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
  9.3881 +** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
  9.3882 +** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  9.3883 +** [sqlite3_free()].
  9.3884 +**
  9.3885 +** ^(If a memory allocation error occurs during the evaluation of any
  9.3886 +** of these routines, a default value is returned.  The default value
  9.3887 +** is either the integer 0, the floating point number 0.0, or a NULL
  9.3888 +** pointer.  Subsequent calls to [sqlite3_errcode()] will return
  9.3889 +** [SQLITE_NOMEM].)^
  9.3890 +*/
  9.3891 +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  9.3892 +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  9.3893 +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  9.3894 +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  9.3895 +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  9.3896 +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  9.3897 +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  9.3898 +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  9.3899 +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  9.3900 +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  9.3901 +
  9.3902 +/*
  9.3903 +** CAPI3REF: Destroy A Prepared Statement Object
  9.3904 +**
  9.3905 +** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  9.3906 +** ^If the most recent evaluation of the statement encountered no errors
  9.3907 +** or if the statement is never been evaluated, then sqlite3_finalize() returns
  9.3908 +** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
  9.3909 +** sqlite3_finalize(S) returns the appropriate [error code] or
  9.3910 +** [extended error code].
  9.3911 +**
  9.3912 +** ^The sqlite3_finalize(S) routine can be called at any point during
  9.3913 +** the life cycle of [prepared statement] S:
  9.3914 +** before statement S is ever evaluated, after
  9.3915 +** one or more calls to [sqlite3_reset()], or after any call
  9.3916 +** to [sqlite3_step()] regardless of whether or not the statement has
  9.3917 +** completed execution.
  9.3918 +**
  9.3919 +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  9.3920 +**
  9.3921 +** The application must finalize every [prepared statement] in order to avoid
  9.3922 +** resource leaks.  It is a grievous error for the application to try to use
  9.3923 +** a prepared statement after it has been finalized.  Any use of a prepared
  9.3924 +** statement after it has been finalized can result in undefined and
  9.3925 +** undesirable behavior such as segfaults and heap corruption.
  9.3926 +*/
  9.3927 +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  9.3928 +
  9.3929 +/*
  9.3930 +** CAPI3REF: Reset A Prepared Statement Object
  9.3931 +**
  9.3932 +** The sqlite3_reset() function is called to reset a [prepared statement]
  9.3933 +** object back to its initial state, ready to be re-executed.
  9.3934 +** ^Any SQL statement variables that had values bound to them using
  9.3935 +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  9.3936 +** Use [sqlite3_clear_bindings()] to reset the bindings.
  9.3937 +**
  9.3938 +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  9.3939 +** back to the beginning of its program.
  9.3940 +**
  9.3941 +** ^If the most recent call to [sqlite3_step(S)] for the
  9.3942 +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  9.3943 +** or if [sqlite3_step(S)] has never before been called on S,
  9.3944 +** then [sqlite3_reset(S)] returns [SQLITE_OK].
  9.3945 +**
  9.3946 +** ^If the most recent call to [sqlite3_step(S)] for the
  9.3947 +** [prepared statement] S indicated an error, then
  9.3948 +** [sqlite3_reset(S)] returns an appropriate [error code].
  9.3949 +**
  9.3950 +** ^The [sqlite3_reset(S)] interface does not change the values
  9.3951 +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  9.3952 +*/
  9.3953 +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  9.3954 +
  9.3955 +/*
  9.3956 +** CAPI3REF: Create Or Redefine SQL Functions
  9.3957 +** KEYWORDS: {function creation routines}
  9.3958 +** KEYWORDS: {application-defined SQL function}
  9.3959 +** KEYWORDS: {application-defined SQL functions}
  9.3960 +**
  9.3961 +** ^These functions (collectively known as "function creation routines")
  9.3962 +** are used to add SQL functions or aggregates or to redefine the behavior
  9.3963 +** of existing SQL functions or aggregates.  The only differences between
  9.3964 +** these routines are the text encoding expected for
  9.3965 +** the second parameter (the name of the function being created)
  9.3966 +** and the presence or absence of a destructor callback for
  9.3967 +** the application data pointer.
  9.3968 +**
  9.3969 +** ^The first parameter is the [database connection] to which the SQL
  9.3970 +** function is to be added.  ^If an application uses more than one database
  9.3971 +** connection then application-defined SQL functions must be added
  9.3972 +** to each database connection separately.
  9.3973 +**
  9.3974 +** ^The second parameter is the name of the SQL function to be created or
  9.3975 +** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
  9.3976 +** representation, exclusive of the zero-terminator.  ^Note that the name
  9.3977 +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
  9.3978 +** ^Any attempt to create a function with a longer name
  9.3979 +** will result in [SQLITE_MISUSE] being returned.
  9.3980 +**
  9.3981 +** ^The third parameter (nArg)
  9.3982 +** is the number of arguments that the SQL function or
  9.3983 +** aggregate takes. ^If this parameter is -1, then the SQL function or
  9.3984 +** aggregate may take any number of arguments between 0 and the limit
  9.3985 +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
  9.3986 +** parameter is less than -1 or greater than 127 then the behavior is
  9.3987 +** undefined.
  9.3988 +**
  9.3989 +** ^The fourth parameter, eTextRep, specifies what
  9.3990 +** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  9.3991 +** its parameters.  Every SQL function implementation must be able to work
  9.3992 +** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
  9.3993 +** more efficient with one encoding than another.  ^An application may
  9.3994 +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  9.3995 +** times with the same function but with different values of eTextRep.
  9.3996 +** ^When multiple implementations of the same function are available, SQLite
  9.3997 +** will pick the one that involves the least amount of data conversion.
  9.3998 +** If there is only a single implementation which does not care what text
  9.3999 +** encoding is used, then the fourth argument should be [SQLITE_ANY].
  9.4000 +**
  9.4001 +** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
  9.4002 +** function can gain access to this pointer using [sqlite3_user_data()].)^
  9.4003 +**
  9.4004 +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  9.4005 +** pointers to C-language functions that implement the SQL function or
  9.4006 +** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  9.4007 +** callback only; NULL pointers must be passed as the xStep and xFinal
  9.4008 +** parameters. ^An aggregate SQL function requires an implementation of xStep
  9.4009 +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  9.4010 +** SQL function or aggregate, pass NULL pointers for all three function
  9.4011 +** callbacks.
  9.4012 +**
  9.4013 +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  9.4014 +** then it is destructor for the application data pointer. 
  9.4015 +** The destructor is invoked when the function is deleted, either by being
  9.4016 +** overloaded or when the database connection closes.)^
  9.4017 +** ^The destructor is also invoked if the call to
  9.4018 +** sqlite3_create_function_v2() fails.
  9.4019 +** ^When the destructor callback of the tenth parameter is invoked, it
  9.4020 +** is passed a single argument which is a copy of the application data 
  9.4021 +** pointer which was the fifth parameter to sqlite3_create_function_v2().
  9.4022 +**
  9.4023 +** ^It is permitted to register multiple implementations of the same
  9.4024 +** functions with the same name but with either differing numbers of
  9.4025 +** arguments or differing preferred text encodings.  ^SQLite will use
  9.4026 +** the implementation that most closely matches the way in which the
  9.4027 +** SQL function is used.  ^A function implementation with a non-negative
  9.4028 +** nArg parameter is a better match than a function implementation with
  9.4029 +** a negative nArg.  ^A function where the preferred text encoding
  9.4030 +** matches the database encoding is a better
  9.4031 +** match than a function where the encoding is different.  
  9.4032 +** ^A function where the encoding difference is between UTF16le and UTF16be
  9.4033 +** is a closer match than a function where the encoding difference is
  9.4034 +** between UTF8 and UTF16.
  9.4035 +**
  9.4036 +** ^Built-in functions may be overloaded by new application-defined functions.
  9.4037 +**
  9.4038 +** ^An application-defined function is permitted to call other
  9.4039 +** SQLite interfaces.  However, such calls must not
  9.4040 +** close the database connection nor finalize or reset the prepared
  9.4041 +** statement in which the function is running.
  9.4042 +*/
  9.4043 +SQLITE_API int sqlite3_create_function(
  9.4044 +  sqlite3 *db,
  9.4045 +  const char *zFunctionName,
  9.4046 +  int nArg,
  9.4047 +  int eTextRep,
  9.4048 +  void *pApp,
  9.4049 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  9.4050 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  9.4051 +  void (*xFinal)(sqlite3_context*)
  9.4052 +);
  9.4053 +SQLITE_API int sqlite3_create_function16(
  9.4054 +  sqlite3 *db,
  9.4055 +  const void *zFunctionName,
  9.4056 +  int nArg,
  9.4057 +  int eTextRep,
  9.4058 +  void *pApp,
  9.4059 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  9.4060 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  9.4061 +  void (*xFinal)(sqlite3_context*)
  9.4062 +);
  9.4063 +SQLITE_API int sqlite3_create_function_v2(
  9.4064 +  sqlite3 *db,
  9.4065 +  const char *zFunctionName,
  9.4066 +  int nArg,
  9.4067 +  int eTextRep,
  9.4068 +  void *pApp,
  9.4069 +  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  9.4070 +  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  9.4071 +  void (*xFinal)(sqlite3_context*),
  9.4072 +  void(*xDestroy)(void*)
  9.4073 +);
  9.4074 +
  9.4075 +/*
  9.4076 +** CAPI3REF: Text Encodings
  9.4077 +**
  9.4078 +** These constant define integer codes that represent the various
  9.4079 +** text encodings supported by SQLite.
  9.4080 +*/
  9.4081 +#define SQLITE_UTF8           1
  9.4082 +#define SQLITE_UTF16LE        2
  9.4083 +#define SQLITE_UTF16BE        3
  9.4084 +#define SQLITE_UTF16          4    /* Use native byte order */
  9.4085 +#define SQLITE_ANY            5    /* sqlite3_create_function only */
  9.4086 +#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
  9.4087 +
  9.4088 +/*
  9.4089 +** CAPI3REF: Deprecated Functions
  9.4090 +** DEPRECATED
  9.4091 +**
  9.4092 +** These functions are [deprecated].  In order to maintain
  9.4093 +** backwards compatibility with older code, these functions continue 
  9.4094 +** to be supported.  However, new applications should avoid
  9.4095 +** the use of these functions.  To help encourage people to avoid
  9.4096 +** using these functions, we are not going to tell you what they do.
  9.4097 +*/
  9.4098 +#ifndef SQLITE_OMIT_DEPRECATED
  9.4099 +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  9.4100 +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  9.4101 +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  9.4102 +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  9.4103 +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  9.4104 +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  9.4105 +                      void*,sqlite3_int64);
  9.4106 +#endif
  9.4107 +
  9.4108 +/*
  9.4109 +** CAPI3REF: Obtaining SQL Function Parameter Values
  9.4110 +**
  9.4111 +** The C-language implementation of SQL functions and aggregates uses
  9.4112 +** this set of interface routines to access the parameter values on
  9.4113 +** the function or aggregate.
  9.4114 +**
  9.4115 +** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  9.4116 +** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  9.4117 +** define callbacks that implement the SQL functions and aggregates.
  9.4118 +** The 3rd parameter to these callbacks is an array of pointers to
  9.4119 +** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
  9.4120 +** each parameter to the SQL function.  These routines are used to
  9.4121 +** extract values from the [sqlite3_value] objects.
  9.4122 +**
  9.4123 +** These routines work only with [protected sqlite3_value] objects.
  9.4124 +** Any attempt to use these routines on an [unprotected sqlite3_value]
  9.4125 +** object results in undefined behavior.
  9.4126 +**
  9.4127 +** ^These routines work just like the corresponding [column access functions]
  9.4128 +** except that  these routines take a single [protected sqlite3_value] object
  9.4129 +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  9.4130 +**
  9.4131 +** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  9.4132 +** in the native byte-order of the host machine.  ^The
  9.4133 +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  9.4134 +** extract UTF-16 strings as big-endian and little-endian respectively.
  9.4135 +**
  9.4136 +** ^(The sqlite3_value_numeric_type() interface attempts to apply
  9.4137 +** numeric affinity to the value.  This means that an attempt is
  9.4138 +** made to convert the value to an integer or floating point.  If
  9.4139 +** such a conversion is possible without loss of information (in other
  9.4140 +** words, if the value is a string that looks like a number)
  9.4141 +** then the conversion is performed.  Otherwise no conversion occurs.
  9.4142 +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  9.4143 +**
  9.4144 +** Please pay particular attention to the fact that the pointer returned
  9.4145 +** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  9.4146 +** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  9.4147 +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  9.4148 +** or [sqlite3_value_text16()].
  9.4149 +**
  9.4150 +** These routines must be called from the same thread as
  9.4151 +** the SQL function that supplied the [sqlite3_value*] parameters.
  9.4152 +*/
  9.4153 +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  9.4154 +SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  9.4155 +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  9.4156 +SQLITE_API double sqlite3_value_double(sqlite3_value*);
  9.4157 +SQLITE_API int sqlite3_value_int(sqlite3_value*);
  9.4158 +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  9.4159 +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  9.4160 +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  9.4161 +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  9.4162 +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  9.4163 +SQLITE_API int sqlite3_value_type(sqlite3_value*);
  9.4164 +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  9.4165 +
  9.4166 +/*
  9.4167 +** CAPI3REF: Obtain Aggregate Function Context
  9.4168 +**
  9.4169 +** Implementations of aggregate SQL functions use this
  9.4170 +** routine to allocate memory for storing their state.
  9.4171 +**
  9.4172 +** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
  9.4173 +** for a particular aggregate function, SQLite
  9.4174 +** allocates N of memory, zeroes out that memory, and returns a pointer
  9.4175 +** to the new memory. ^On second and subsequent calls to
  9.4176 +** sqlite3_aggregate_context() for the same aggregate function instance,
  9.4177 +** the same buffer is returned.  Sqlite3_aggregate_context() is normally
  9.4178 +** called once for each invocation of the xStep callback and then one
  9.4179 +** last time when the xFinal callback is invoked.  ^(When no rows match
  9.4180 +** an aggregate query, the xStep() callback of the aggregate function
  9.4181 +** implementation is never called and xFinal() is called exactly once.
  9.4182 +** In those cases, sqlite3_aggregate_context() might be called for the
  9.4183 +** first time from within xFinal().)^
  9.4184 +**
  9.4185 +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
  9.4186 +** when first called if N is less than or equal to zero or if a memory
  9.4187 +** allocate error occurs.
  9.4188 +**
  9.4189 +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  9.4190 +** determined by the N parameter on first successful call.  Changing the
  9.4191 +** value of N in subsequent call to sqlite3_aggregate_context() within
  9.4192 +** the same aggregate function instance will not resize the memory
  9.4193 +** allocation.)^  Within the xFinal callback, it is customary to set
  9.4194 +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
  9.4195 +** pointless memory allocations occur.
  9.4196 +**
  9.4197 +** ^SQLite automatically frees the memory allocated by 
  9.4198 +** sqlite3_aggregate_context() when the aggregate query concludes.
  9.4199 +**
  9.4200 +** The first parameter must be a copy of the
  9.4201 +** [sqlite3_context | SQL function context] that is the first parameter
  9.4202 +** to the xStep or xFinal callback routine that implements the aggregate
  9.4203 +** function.
  9.4204 +**
  9.4205 +** This routine must be called from the same thread in which
  9.4206 +** the aggregate SQL function is running.
  9.4207 +*/
  9.4208 +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  9.4209 +
  9.4210 +/*
  9.4211 +** CAPI3REF: User Data For Functions
  9.4212 +**
  9.4213 +** ^The sqlite3_user_data() interface returns a copy of
  9.4214 +** the pointer that was the pUserData parameter (the 5th parameter)
  9.4215 +** of the [sqlite3_create_function()]
  9.4216 +** and [sqlite3_create_function16()] routines that originally
  9.4217 +** registered the application defined function.
  9.4218 +**
  9.4219 +** This routine must be called from the same thread in which
  9.4220 +** the application-defined function is running.
  9.4221 +*/
  9.4222 +SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  9.4223 +
  9.4224 +/*
  9.4225 +** CAPI3REF: Database Connection For Functions
  9.4226 +**
  9.4227 +** ^The sqlite3_context_db_handle() interface returns a copy of
  9.4228 +** the pointer to the [database connection] (the 1st parameter)
  9.4229 +** of the [sqlite3_create_function()]
  9.4230 +** and [sqlite3_create_function16()] routines that originally
  9.4231 +** registered the application defined function.
  9.4232 +*/
  9.4233 +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  9.4234 +
  9.4235 +/*
  9.4236 +** CAPI3REF: Function Auxiliary Data
  9.4237 +**
  9.4238 +** These functions may be used by (non-aggregate) SQL functions to
  9.4239 +** associate metadata with argument values. If the same value is passed to
  9.4240 +** multiple invocations of the same SQL function during query execution, under
  9.4241 +** some circumstances the associated metadata may be preserved.  An example
  9.4242 +** of where this might be useful is in a regular-expression matching
  9.4243 +** function. The compiled version of the regular expression can be stored as
  9.4244 +** metadata associated with the pattern string.  
  9.4245 +** Then as long as the pattern string remains the same,
  9.4246 +** the compiled regular expression can be reused on multiple
  9.4247 +** invocations of the same function.
  9.4248 +**
  9.4249 +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  9.4250 +** associated by the sqlite3_set_auxdata() function with the Nth argument
  9.4251 +** value to the application-defined function. ^If there is no metadata
  9.4252 +** associated with the function argument, this sqlite3_get_auxdata() interface
  9.4253 +** returns a NULL pointer.
  9.4254 +**
  9.4255 +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  9.4256 +** argument of the application-defined function.  ^Subsequent
  9.4257 +** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  9.4258 +** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  9.4259 +** NULL if the metadata has been discarded.
  9.4260 +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  9.4261 +** SQLite will invoke the destructor function X with parameter P exactly
  9.4262 +** once, when the metadata is discarded.
  9.4263 +** SQLite is free to discard the metadata at any time, including: <ul>
  9.4264 +** <li> when the corresponding function parameter changes, or
  9.4265 +** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  9.4266 +**      SQL statement, or
  9.4267 +** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  9.4268 +** <li> during the original sqlite3_set_auxdata() call when a memory 
  9.4269 +**      allocation error occurs. </ul>)^
  9.4270 +**
  9.4271 +** Note the last bullet in particular.  The destructor X in 
  9.4272 +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  9.4273 +** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
  9.4274 +** should be called near the end of the function implementation and the
  9.4275 +** function implementation should not make any use of P after
  9.4276 +** sqlite3_set_auxdata() has been called.
  9.4277 +**
  9.4278 +** ^(In practice, metadata is preserved between function calls for
  9.4279 +** function parameters that are compile-time constants, including literal
  9.4280 +** values and [parameters] and expressions composed from the same.)^
  9.4281 +**
  9.4282 +** These routines must be called from the same thread in which
  9.4283 +** the SQL function is running.
  9.4284 +*/
  9.4285 +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  9.4286 +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  9.4287 +
  9.4288 +
  9.4289 +/*
  9.4290 +** CAPI3REF: Constants Defining Special Destructor Behavior
  9.4291 +**
  9.4292 +** These are special values for the destructor that is passed in as the
  9.4293 +** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
  9.4294 +** argument is SQLITE_STATIC, it means that the content pointer is constant
  9.4295 +** and will never change.  It does not need to be destroyed.  ^The
  9.4296 +** SQLITE_TRANSIENT value means that the content will likely change in
  9.4297 +** the near future and that SQLite should make its own private copy of
  9.4298 +** the content before returning.
  9.4299 +**
  9.4300 +** The typedef is necessary to work around problems in certain
  9.4301 +** C++ compilers.
  9.4302 +*/
  9.4303 +typedef void (*sqlite3_destructor_type)(void*);
  9.4304 +#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
  9.4305 +#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
  9.4306 +
  9.4307 +/*
  9.4308 +** CAPI3REF: Setting The Result Of An SQL Function
  9.4309 +**
  9.4310 +** These routines are used by the xFunc or xFinal callbacks that
  9.4311 +** implement SQL functions and aggregates.  See
  9.4312 +** [sqlite3_create_function()] and [sqlite3_create_function16()]
  9.4313 +** for additional information.
  9.4314 +**
  9.4315 +** These functions work very much like the [parameter binding] family of
  9.4316 +** functions used to bind values to host parameters in prepared statements.
  9.4317 +** Refer to the [SQL parameter] documentation for additional information.
  9.4318 +**
  9.4319 +** ^The sqlite3_result_blob() interface sets the result from
  9.4320 +** an application-defined function to be the BLOB whose content is pointed
  9.4321 +** to by the second parameter and which is N bytes long where N is the
  9.4322 +** third parameter.
  9.4323 +**
  9.4324 +** ^The sqlite3_result_zeroblob() interfaces set the result of
  9.4325 +** the application-defined function to be a BLOB containing all zero
  9.4326 +** bytes and N bytes in size, where N is the value of the 2nd parameter.
  9.4327 +**
  9.4328 +** ^The sqlite3_result_double() interface sets the result from
  9.4329 +** an application-defined function to be a floating point value specified
  9.4330 +** by its 2nd argument.
  9.4331 +**
  9.4332 +** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  9.4333 +** cause the implemented SQL function to throw an exception.
  9.4334 +** ^SQLite uses the string pointed to by the
  9.4335 +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  9.4336 +** as the text of an error message.  ^SQLite interprets the error