2018-11-02 22:13:25 +01:00
#region Disclaimer / License
2015-01-20 21:44:52 +01:00
// Copyright (C) 2015, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
2014-04-07 11:59:33 +02:00
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#endregion
using System ;
2018-06-28 10:50:17 +02:00
using System.IO ;
2020-02-17 09:34:39 -08:00
using Duplicati.Library.Common ;
2014-04-07 11:59:33 +02:00
namespace Duplicati.Library.SQLiteHelper
{
public static class SQLiteLoader
2018-06-28 10:50:17 +02:00
{
2018-06-14 21:43:20 +02:00
/// <summary>
2018-05-15 11:29:08 +02:00
/// The tag used for logging
/// </summary>
2018-06-14 21:43:20 +02:00
private static readonly string LOGTAG = Logging . Log . LogTagFromType ( typeof ( SQLiteLoader ));
2018-05-15 11:29:08 +02:00
2014-04-07 11:59:33 +02:00
/// <summary>
/// A cached copy of the type
/// </summary>
private static Type m_type = null ;
2018-06-21 18:08:52 +02:00
/// <summary>
/// Helper method with logic to handle opening a database in possibly encrypted format
/// </summary>
/// <param name="con">The SQLite connection object</param>
2018-06-28 10:50:17 +02:00
/// <param name="databasePath">The location of Duplicati's database.</param>
2018-06-21 18:08:52 +02:00
/// <param name="useDatabaseEncryption">Specify if database is encrypted</param>
/// <param name="password">Encryption password</param>
2018-06-28 10:50:17 +02:00
public static void OpenDatabase ( System . Data . IDbConnection con , string databasePath , bool useDatabaseEncryption , string password )
2018-06-21 18:08:52 +02:00
{
2018-06-28 10:50:17 +02:00
var setPwdMethod = con . GetType (). GetMethod ( "SetPassword" , new [] { typeof ( string ) });
2018-06-21 18:08:52 +02:00
string attemptedPassword ;
if (! useDatabaseEncryption || string . IsNullOrEmpty ( password ))
attemptedPassword = null ; //No encryption specified, attempt to open without
else
attemptedPassword = password ; //Encryption specified, attempt to open with
if ( setPwdMethod != null )
setPwdMethod . Invoke ( con , new object [] { attemptedPassword });
try
{
//Attempt to open in preferred state
2018-06-28 10:50:17 +02:00
OpenSQLiteFile ( con , databasePath );
2018-06-21 18:58:55 +02:00
TestSQLiteFile ( con );
2018-06-21 18:08:52 +02:00
}
catch
{
try
{
//We can't try anything else without a password
if ( string . IsNullOrEmpty ( password ))
throw ;
//Open failed, now try the reverse
attemptedPassword = attemptedPassword == null ? password : null ;
con . Close ();
if ( setPwdMethod != null )
setPwdMethod . Invoke ( con , new object [] { attemptedPassword });
2018-06-28 10:50:17 +02:00
OpenSQLiteFile ( con , databasePath );
2018-06-21 18:08:52 +02:00
2018-06-21 18:58:55 +02:00
TestSQLiteFile ( con );
2018-06-21 18:08:52 +02:00
}
catch
{
try { con . Close (); }
2018-06-28 10:50:17 +02:00
catch ( Exception ex ) { Logging . Log . WriteExplicitMessage ( LOGTAG , "OpenDatabaseFailed" , ex , "Failed to open the SQLite database: {0}" , databasePath ); }
2018-06-21 18:08:52 +02:00
}
//If the db is not open now, it won't open
if ( con . State != System . Data . ConnectionState . Open )
throw ; //Report original error
//The open method succeeded with the non-default method, now change the password
2018-06-28 10:50:17 +02:00
var changePwdMethod = con . GetType (). GetMethod ( "ChangePassword" , new [] { typeof ( string ) });
2018-06-21 18:08:52 +02:00
changePwdMethod . Invoke ( con , new object [] { useDatabaseEncryption ? password : null });
}
}
2017-01-15 23:09:47 +01:00
/// <summary>
2018-06-11 18:50:11 +02:00
/// Loads an SQLite connection instance and opening the database
2017-01-15 23:09:47 +01:00
/// </summary>
/// <returns>The SQLite connection instance.</returns>
2018-06-11 18:50:11 +02:00
public static System . Data . IDbConnection LoadConnection ()
2017-01-15 23:09:47 +01:00
{
System . Data . IDbConnection con = null ;
2018-06-19 08:41:07 +02:00
SetEnvironmentVariablesForSQLiteTempDir ();
2018-06-14 22:00:59 +02:00
2017-01-15 23:09:47 +01:00
try
{
con = ( System . Data . IDbConnection ) Activator . CreateInstance ( Duplicati . Library . SQLiteHelper . SQLiteLoader . SQLiteConnectionType );
2018-06-11 18:50:11 +02:00
}
2018-06-11 19:10:14 +02:00
catch ( Exception ex )
2018-06-11 18:50:11 +02:00
{
2018-06-11 19:10:14 +02:00
Logging . Log . WriteErrorMessage ( LOGTAG , "FailedToLoadConnectionSQLite" , ex , "Failed to load connection." );
2018-06-11 22:06:06 +02:00
DisposeConnection ( con );
2018-06-11 18:50:11 +02:00
throw ;
2018-06-28 10:50:17 +02:00
}
2018-06-11 18:50:11 +02:00
return con ;
}
/// <summary>
/// Loads an SQLite connection instance and opening the database
/// </summary>
/// <returns>The SQLite connection instance.</returns>
/// <param name="targetpath">The optional path to the database.</param>
public static System . Data . IDbConnection LoadConnection ( string targetpath )
{
2018-06-28 10:50:17 +02:00
if ( string . IsNullOrWhiteSpace ( targetpath ))
throw new ArgumentNullException ( nameof ( targetpath ));
2018-06-11 18:50:11 +02:00
System . Data . IDbConnection con = LoadConnection ();
try
{
2018-06-28 10:50:17 +02:00
OpenSQLiteFile ( con , targetpath );
2017-01-15 23:09:47 +01:00
}
2018-06-11 19:10:14 +02:00
catch ( Exception ex )
2017-01-15 23:09:47 +01:00
{
2018-06-11 19:10:14 +02:00
Logging . Log . WriteErrorMessage ( LOGTAG , "FailedToLoadConnectionSQLite" , ex , @"Failed to load connection with path '{0}'." , targetpath );
2018-06-11 22:06:06 +02:00
DisposeConnection ( con );
2017-01-15 23:09:47 +01:00
throw ;
}
2023-03-19 00:48:10 +01:00
// set custom Sqlite options
var opts = Environment . GetEnvironmentVariable ( "CUSTOMSQLITEOPTIONS_DUPLICATI" );
if ( opts != null ) {
var topts = opts . Split ( new char []{ ';' }, StringSplitOptions . RemoveEmptyEntries );
if ( topts . Length > 0 ) {
using ( var cmd = con . CreateCommand ()) {
foreach ( var opt in topts ) {
Logging . Log . WriteVerboseMessage ( LOGTAG , "CustomSQLiteOption" , @"Setting custom SQLite option '{0}'." , opt );
try
{
cmd . CommandText = string . Format ( "pragma {0}" , opt );
cmd . ExecuteNonQuery ();
}
catch ( Exception ex )
{
Logging . Log . WriteErrorMessage ( LOGTAG , "CustomSQLiteOption" , ex , @"Error setting custom SQLite option '{0}'." , opt );
}
}
}
}
}
2017-01-15 23:09:47 +01:00
return con ;
}
2014-04-07 11:59:33 +02:00
/// <summary>
/// Returns the SQLiteCommand type for the current architecture
/// </summary>
public static Type SQLiteConnectionType
{
get
{
2018-06-14 21:43:20 +02:00
if ( m_type != null )
return m_type ;
2017-03-01 11:10:01 +01:00
2018-06-28 10:50:17 +02:00
var filename = "System.Data.SQLite.dll" ;
var basePath = Path . Combine ( Path . GetDirectoryName ( System . Reflection . Assembly . GetExecutingAssembly (). Location ), "SQLite" );
2014-04-07 11:59:33 +02:00
2018-06-28 10:50:17 +02:00
// Set this to make SQLite preload automatically
Environment . SetEnvironmentVariable ( "PreLoadSQLite_BaseDirectory" , basePath );
2014-04-07 11:59:33 +02:00
2018-06-28 10:50:17 +02:00
//Default is to use the pinvoke version which requires a native .dll/.so
var assemblyPath = Path . Combine ( basePath , "pinvoke" );
2018-06-14 22:00:59 +02:00
var loadMixedModeAssembly = false ;
2018-06-28 10:50:17 +02:00
if (! Duplicati . Library . Utility . Utility . IsMono )
{
//If we run with MS.Net we can use the mixed mode assemblies
if ( Environment . Is64BitProcess )
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
if ( File . Exists ( Path . Combine ( Path . Combine ( basePath , "win64" ), filename )))
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
assemblyPath = Path . Combine ( basePath , "win64" );
2018-06-14 22:00:59 +02:00
loadMixedModeAssembly = true ;
2014-04-07 11:59:33 +02:00
}
2018-06-28 10:50:17 +02:00
}
else
{
if ( File . Exists ( Path . Combine ( Path . Combine ( basePath , "win32" ), filename )))
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
assemblyPath = Path . Combine ( basePath , "win32" );
2018-06-14 22:00:59 +02:00
loadMixedModeAssembly = true ;
2014-04-07 11:59:33 +02:00
}
2018-06-28 10:50:17 +02:00
}
2017-03-01 11:10:01 +01:00
2018-06-28 10:50:17 +02:00
// If we have a new path, try to force load the mixed-mode assembly for the current architecture
// This can be avoided if the preload in SQLite works, but it is easy to do it here as well
if ( loadMixedModeAssembly )
{
2020-02-17 09:34:39 -08:00
try { PInvoke . LoadLibraryEx ( Path . Combine ( assemblyPath , "SQLite.Interop.dll" ), IntPtr . Zero , 0 ); }
catch ( Exception ex ) { Logging . Log . WriteExplicitMessage ( LOGTAG , "LoadMixedModeSQLiteError" , ex , "Failed to load the mixed mode SQLite database: {0}" , Path . Combine ( assemblyPath , "SQLite.Interop.dll" )); }
2018-06-28 10:50:17 +02:00
}
}
else
{
//On Mono, we try to find the Mono version of SQLite
2017-03-01 11:10:01 +01:00
2018-06-28 10:50:17 +02:00
//This secret environment variable can be used to support older installations
var envvalue = System . Environment . GetEnvironmentVariable ( "DISABLE_MONO_DATA_SQLITE" );
if (! Utility . Utility . ParseBool ( envvalue , envvalue != null ))
{
foreach ( var asmversion in new [] { "4.0.0.0" , "2.0.0.0" })
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
var name = string . Format ( "Mono.Data.Sqlite, Version={0}, Culture=neutral, PublicKeyToken=0738eb9f132ed756" , asmversion );
try
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
Type t = System . Reflection . Assembly . Load ( name ). GetType ( "Mono.Data.Sqlite.SqliteConnection" );
if ( t != null && t . GetInterface ( "System.Data.IDbConnection" , false ) != null )
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
Version v = new Version (( string ) t . GetProperty ( "SQLiteVersion" ). GetValue ( null , null ));
if ( v >= new Version ( 3 , 6 , 3 ))
2014-04-07 11:59:33 +02:00
{
2018-06-28 10:50:17 +02:00
return m_type = t ;
}
2014-04-07 11:59:33 +02:00
}
2018-06-28 10:50:17 +02:00
}
catch ( Exception ex )
{
Logging . Log . WriteExplicitMessage ( LOGTAG , "FailedToLoadSQLiteAssembly" , ex , "Failed to load the SQLite assembly: {0}" , name );
}
2014-04-07 11:59:33 +02:00
}
2018-06-28 10:50:17 +02:00
Logging . Log . WriteVerboseMessage ( LOGTAG , "FailedToLoadSQLite" , "Failed to load Mono.Data.Sqlite.SqliteConnection, reverting to built-in." );
}
2014-04-07 11:59:33 +02:00
}
2018-06-28 10:50:17 +02:00
m_type = System . Reflection . Assembly . LoadFile ( Path . Combine ( assemblyPath , filename )). GetType ( "System.Data.SQLite.SQLiteConnection" );
2018-06-14 21:43:20 +02:00
2014-04-07 11:59:33 +02:00
return m_type ;
}
}
2018-06-11 22:06:06 +02:00
2018-06-19 08:41:07 +02:00
/// <summary>
/// Set environment variables to be used by SQLite to determine which folder to use for temporary files.
/// From SQLite's documentation, SQLITE_TMPDIR is used for unix-like systems.
/// For Windows, TMP and TEMP environment variables are used.
/// </summary>
private static void SetEnvironmentVariablesForSQLiteTempDir ()
{
System . Environment . SetEnvironmentVariable ( "SQLITE_TMPDIR" , Library . Utility . TempFolder . SystemTempPath );
System . Environment . SetEnvironmentVariable ( "TMP" , Library . Utility . TempFolder . SystemTempPath );
System . Environment . SetEnvironmentVariable ( "TEMP" , Library . Utility . TempFolder . SystemTempPath );
}
2018-06-11 22:06:06 +02:00
2018-06-28 10:50:17 +02:00
/// <summary>
/// Wrapper to dispose the SQLite connection
/// </summary>
/// <param name="con">The connection to close.</param>
2018-06-11 22:06:06 +02:00
private static void DisposeConnection ( System . Data . IDbConnection con )
{
if ( con != null )
try { con . Dispose (); }
2018-06-28 10:50:17 +02:00
catch ( Exception ex ) { Logging . Log . WriteExplicitMessage ( LOGTAG , "ConnectionDisposeError" , ex , "Failed to dispose connection" ); }
}
2018-06-27 13:36:08 +02:00
/// <summary>
/// Opens the SQLite file in the given connection, creating the file if required
/// </summary>
/// <param name="con">The connection to use.</param>
/// <param name="path">Path to the file to open, which may not exist.</param>
2018-06-21 18:58:55 +02:00
private static void OpenSQLiteFile ( System . Data . IDbConnection con , string path )
{
2018-06-22 20:01:23 +02:00
// Check if SQLite database exists before opening a connection to it.
// This information is used to 'fix' permissions on a newly created file.
2018-06-27 13:36:08 +02:00
var fileExists = false ;
2018-11-02 22:13:25 +01:00
if (! Platform . IsClientWindows )
2018-06-22 20:01:23 +02:00
fileExists = File . Exists ( path );
2018-06-21 18:58:55 +02:00
con . ConnectionString = "Data Source=" + path ;
2018-06-28 10:50:17 +02:00
con . Open ();
2018-06-27 13:36:08 +02:00
2018-06-28 10:50:17 +02:00
// If we are non-Windows, make the file only accessible by the current user
2018-11-02 22:13:25 +01:00
if (! Platform . IsClientWindows && ! fileExists )
2018-06-27 13:36:08 +02:00
SetUnixPermissionUserRWOnly ( path );
}
/// <summary>
/// Sets the unix permission user read-write Only.
/// </summary>
/// <param name="path">The file to set permissions on.</param>
/// <remarks> Make sure we do not inline this, as we might eventually load Mono.Posix, which is not present on Windows</remarks>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void SetUnixPermissionUserRWOnly ( string path )
{
2018-06-28 09:28:14 +02:00
var fi = UnixSupport . File . GetUserGroupAndPermissions ( path );
2018-06-27 13:36:08 +02:00
UnixSupport . File . SetUserGroupAndPermissions (
path ,
2018-06-28 09:28:14 +02:00
fi . UID ,
fi . GID ,
2018-06-27 13:36:08 +02:00
0x180 /* FilePermissions.S_IRUSR | FilePermissions.S_IWUSR*/
);
2018-06-21 18:58:55 +02:00
}
2018-06-28 10:50:17 +02:00
/// <summary>
/// Tests the SQLite connection, throwing an exception if the connection does not work
/// </summary>
/// <param name="con">The connection to test.</param>
2018-06-21 18:58:55 +02:00
private static void TestSQLiteFile ( System . Data . IDbConnection con )
{
// Do a dummy query to make sure we have a working db
using ( var cmd = con . CreateCommand ())
{
cmd . CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER" ;
cmd . ExecuteScalar ();
}
2018-06-11 22:06:06 +02:00
}
2014-04-07 11:59:33 +02:00
}
2017-03-01 11:10:01 +01:00
/// <summary>
/// Helper class with PInvoke methods
/// </summary>
internal static class PInvoke
{
/// <summary>
/// Loads the specified module into the address space of the calling process.
/// </summary>
/// <returns>The library ex.</returns>
/// <param name="lpFileName">The filename of the module to load.</param>
/// <param name="hReservedNull">Reserved for future use.</param>
/// <param name="dwFlags">Action to take on load.</param>
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibraryEx ( string lpFileName , IntPtr hReservedNull , uint dwFlags );
}
2014-04-07 11:59:33 +02:00
}