-- -------------------------------------------------------------------- -- magic-manager -- magic manager to help in using the libmagic library -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- SPDX-License-Identifier: Apache-2.0 ----------------------------------------------------------------------- package body Magic.Manager is package ICS renames Interfaces.C.Strings; use type ICS.chars_ptr; -- ------------------------------ -- Initialize the magic manager and prepare the libmagic library. -- ------------------------------ procedure Initialize (Manager : in out Magic_Manager; Config : in Flags; Path : in String) is E : Integer; S : ICS.chars_ptr; begin if Manager.Magic_Cookie = null then Manager.Magic_Cookie := Open (Config); if Manager.Magic_Cookie = null then raise Error; end if; else E := Set_Flags (Manager.Magic_Cookie, Config); if E /= 0 then raise Error; end if; end if; S := ICS.New_String (Path); E := Load (Manager.Magic_Cookie, S); ICS.Free (S); if E /= 0 then raise Error; end if; end Initialize; -- ------------------------------ -- Check whether the manager and the libmagic library is initialized. -- ------------------------------ function Is_Initialized (Manager : in Magic_Manager) return Boolean is begin return Manager.Magic_Cookie /= null; end Is_Initialized; -- ------------------------------ -- Identify the content of the buffer by using the libmagic library. -- ------------------------------ function Identify (Manager : in Magic_Manager; Data : in Ada.Streams.Stream_Element_Array) return String is R : Interfaces.C.Strings.chars_ptr; begin R := Buffer (Manager.Magic_Cookie, Data'Address, Interfaces.C.size_t (Data'Length)); if R /= Interfaces.C.Strings.Null_Ptr then return Interfaces.C.Strings.Value (R); else raise Error; end if; end Identify; -- ------------------------------ -- Identify the content of the file. -- ------------------------------ function Identify (Manager : in Magic_Manager; Path : in String) return String is S : ICS.chars_ptr := ICS.New_String (Path); R : Interfaces.C.Strings.chars_ptr; begin R := File (Manager.Magic_Cookie, S); ICS.Free (S); if R /= Interfaces.C.Strings.Null_Ptr then return Interfaces.C.Strings.Value (R); else raise Error; end if; end Identify; -- ------------------------------ -- Return the last error. -- ------------------------------ function Last_Error (Manager : in Magic_Manager) return String is S : constant ICS.chars_ptr := Magic.Error (Manager.Magic_Cookie); begin if S /= ICS.Null_Ptr then return Interfaces.C.Strings.Value (S); else return ""; end if; end Last_Error; function Last_Errno (Manager : in Magic_Manager) return Integer is begin return Errno (Manager.Magic_Cookie); end Last_Errno; overriding procedure Finalize (Manager : in out Magic_Manager) is begin if Manager.Magic_Cookie /= null then Close (Manager.Magic_Cookie); Manager.Magic_Cookie := null; end if; end Finalize; end Magic.Manager;