Initial commit

This commit is contained in:
Benjamin Rosseaux 2025-11-19 13:19:35 +01:00
commit cd186a2026
105 changed files with 199076 additions and 3 deletions

35
.gitignore vendored
View file

@ -1,3 +1,4 @@
# ---> Delphi
# Uncomment these types if you want even more clean repository. But be careful.
# It can make harm to an existing project source. Read explanations below.
#
@ -68,7 +69,6 @@
*.projdata
*.tvsconfig
*.dsk
*.dsv
# Delphi history and backups
__history/
@ -80,3 +80,36 @@ __recovery/
# Boss dependency manager vendor folder https://github.com/HashLoad/boss
modules/
# ---> Lazarus
# Lazarus compiler-generated binaries (safe to delete)
*.exe
*.dll
*.so
*.dylib
*.lrs
*.res
*.compiled
*.dbg
*.ppu
*.o
*.or
*.a
# Lazarus autogenerated files (duplicated info)
*.rst
*.rsj
*.lrt
# Lazarus local files (user-specific info)
*.lps
# Lazarus backups and unit output folders.
# These can be changed by user in Lazarus/project options.
backup/
*.bak
lib/
# Application bundle for Mac OS
*.app/

15
.gitmodules vendored Normal file
View file

@ -0,0 +1,15 @@
[submodule "externals/pasmp"]
path = externals/pasmp
url = https://github.com/BeRo1985/pasmp.git
[submodule "externals/pasdblstrutils"]
path = externals/pasdblstrutils
url = https://github.com/BeRo1985/pasdblstrutils.git
[submodule "externals/pashtmldown"]
path = externals/pashtmldown
url = https://github.com/BeRo1985/pashtmldown.git
[submodule "externals/pasjson"]
path = externals/pasjson
url = https://github.com/BeRo1985/pasjson.git
[submodule "externals/pinja"]
path = externals/pinja
url = https://github.com/BeRo1985/pinja.git

106
README.md
View file

@ -1,2 +1,104 @@
# pasllm
PasLLM - LLM interference engine in Object Pascal
# PasLLM
A high-performance Large Language Model inference engine written in pure Object Pascal.
## Overview
PasLLM is a native Pascal implementation for running LLMs locally with optimized quantization and inference capabilities. It supports multiple model architectures and features advanced 4-bit quantization formats for efficient model deployment.
## Features
- **Pure Object Pascal** - No Python or external dependencies for inference
- **Cross-Platform** - Compatible with Delphi ≥11.2 and FreePascal ≥3.3.1
- **Multiple Architectures** - Support for Llama, Qwen, Phi, Gemma, Mixtral, and more
- **Advanced Quantization** - Custom Q4*NL formats (Q40NL, Q41NL, Q42NL, Q43NL) with superior tail reconstruction
- **Optimized Performance** - Native Pascal implementation with platform-specific optimizations
- **CLI and GUI** - Both command-line interface and visual applications (FMX, VCL, LCL)
## Quantization Formats
PasLLM implements several custom 4-bit and 8-bit quantization formats designed for optimal quality/size tradeoff:
- **Q40NL** - 4.5 bits/weight with non-linear decode (drop-in replacement for Q4_0)
- **Q41NL** - Alternative non-linearity with increased tail emphasis
- **Q42NL** - Enhanced variant with improved reconstruction
- **Q43NL** - Advanced format with multiple optimization methods (gradient, coarse-fine, grid)
- **Q80** - 8-bit quantization for higher quality
- **FP8** - 8-bit floating point support
These formats achieve 99.5-99.97% of full precision quality while maintaining compact model sizes.
## Supported Models
PasLLM includes pre-quantized models in the `bin/models/` directory:
- **Llama** - 3/3.1/3.2 (1B, 3B, 8B variants, including abliterated/uncensored)
- **Qwen 2.5** - 0.5B, 1.5B, 3B, 7B Instruct
- **Qwen 3** - 0.6B, 1.7B, 4B, 8B, 14B, 32B (including thinking/coder/abliterated variants, 30B MoE models)
- **Phi-3** - Mini, Medium (4K context)
- **Gemma** - 1.1 (2B) (support for Gemma 2 and 3 coming later)
- **SmolLM** - 2 (135M, 360M, 1.7B) and 3 (3B)
- **Mixtral** - 8x7B Instruct
- **EuroMoE** - 2.6B (0.6B active)
- **SimpleChat** - 4B, 14B
- **DeepSeek** - R1 variants
- **TinyLlama** - 1.1B Chat
## Quick Start
### Command Line Interface
```bash
# Run inference with a quantized model
./bin/pasllmcli --model bin/models/qwen2.5_0.5b_instruct_q40nl.safetensors
```
### Building from Source
**FreePascal:**
```bash
fpc -O3 src/pasllmcli/pasllmcli.dpr
```
**Delphi:**
Open `src/pasllmcli/pasllmcli.dproj` in Delphi IDE and build.
## Project Structure
```
src/
├── PasLLM.pas # Core inference engine
├── PasLLMChatControl.pas # Chat interface control
├── pasllmcli/ # Command-line interface
├── pasllmappfmx/ # FireMonkey GUI app
├── pasllmappvcl/ # VCL GUI app
└── pasllmapplcl/ # Lazarus LCL GUI app
tools/
└── convert.py # Model conversion utilities
docs/
└── quant_4bit_formats.md # Detailed format specifications
```
## Documentation
- [4-bit Quantization Formats](docs/quant_4bit_formats.md) - Complete specification of Q4*NL formats
## License
Dual-licensed under:
- **AGPL 3.0** for open-source use
- **Commercial license** available for proprietary applications (contact: benjamin@rosseaux.com)
## Author
**Benjamin Rosseaux** (BeRo)
GitHub: [@BeRo1985](https://github.com/BeRo1985)
Contact: benjamin@rosseaux.com
## Contributing
Contributions are welcome! Please ensure:
- Code is compatible with both Delphi ≥11.2 and FreePascal ≥3.3.1
- Compiles on 32-bit and 64-bit platforms (x86-32, x86-64, ARM, ARM64)
- No platform-specific or third-party dependencies (unless out-ifdef-able)
- Follows the contribution guidelines in `src/PasLLM.pas`

661
agpl-3.0.txt Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

BIN
bin/libcrypto-3-x64.dll Normal file

Binary file not shown.

BIN
bin/libssl-3-x64.dll Normal file

Binary file not shown.

View file

15
bin/tools.json Normal file
View file

@ -0,0 +1,15 @@
{
/* Tavily API key for accessing Tavily web seatch services */
"tavily_key": "tvly-dev-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", /* Replace with your own actual key */
/* MCP (Model Control Protocol) server configurations */
"mcp": {
"demo-mcp-server": {
"endpoint": "http://0.0.0.0:8181/rpc",
"authorization": "Bearer YOUR_ACCESS_TOKEN",
"timeout_milliseconds": 30000
}
}
}

1198
docs/quant_4bit_formats.md Normal file

File diff suppressed because it is too large Load diff

1
externals/pasdblstrutils vendored Submodule

@ -0,0 +1 @@
Subproject commit 1696f0a2b822fef26c8992f96620f1be129cfa99

1
externals/pashtmldown vendored Submodule

@ -0,0 +1 @@
Subproject commit 137a28f41b90c9e07b58cadd6c3e27952daad780

1
externals/pasjson vendored Submodule

@ -0,0 +1 @@
Subproject commit 1fd236a5c6cace1baf56855d2964e85b37b0e9c1

1
externals/pasmp vendored Submodule

@ -0,0 +1 @@
Subproject commit 3a56dc032fa74eedadca5b6ecc821b0fb783afc7

1
externals/pinja vendored Submodule

@ -0,0 +1 @@
Subproject commit 0ba604e72fe5b07ef1b99c3c34a22f71e8151507

11
gitcommitpush Executable file
View file

@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
read -p "Enter commit message (or leave blank for default): " commit_message
if [ -z "$commit_message" ]; then
commit_message="More work"
fi
git commit -am "$commit_message"
git push

8
gitcommitpush.bat Normal file
View file

@ -0,0 +1,8 @@
@echo off
set /p commit_message="Enter commit message (or leave blank for default): "
if "%commit_message%"=="" (
set commit_message=More work
)
git commit -am "%commit_message%"
git push
rem --set-upstream origin master

5
gitforceupdate Executable file
View file

@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
git stash save
git pull
git stash drop

4
gitforceupdate.bat Normal file
View file

@ -0,0 +1,4 @@
@echo off
call git stash save
call git pull
call git stash drop

109
githubsync Executable file
View file

@ -0,0 +1,109 @@
#!/usr/bin/env zsh
# Sync script from ~/Projects/GIT/pasllm to ~/Projects/GitHub/pasllm
# Only syncs files that already exist in the destination to avoid leaking private content
# Usage: ./githubsync [--dry-run]
set -e
# Parse command line arguments
DRY_RUN=0
if [[ "$1" == "--dry-run" ]]; then
DRY_RUN=1
fi
# Define source and destination directories (relative to script location)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SOURCE_DIR="$SCRIPT_DIR"
DEST_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)/GitHub/pasllm"
# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
echo "${BLUE}=== PasLLM GitHub Sync ===${NC}"
if [[ $DRY_RUN -eq 1 ]]; then
echo "${YELLOW}[DRY RUN MODE - No files will be modified]${NC}"
fi
echo "Source: $SOURCE_DIR"
echo "Destination: $DEST_DIR"
echo ""
# Check if destination exists
if [[ ! -d "$DEST_DIR" ]]; then
echo "${RED}Error: Destination directory does not exist: $DEST_DIR${NC}"
exit 1
fi
# Counter for synced files
synced_count=0
skipped_count=0
uptodate_count=0
# Find all files in destination (excluding .git, externals directories, and .gitmodules)
echo "${BLUE}Finding files to sync...${NC}"
cd "$DEST_DIR" || { echo "${RED}Failed to cd to destination${NC}"; exit 1; }
# Use fd if available, otherwise fall back to find
if command -v fd &> /dev/null; then
files=(${(f)"$(fd --type f --hidden --exclude .git --exclude externals --exclude .gitmodules)"})
else
files=(${(f)"$(find . -type f -not -path '*/.git/*' -not -path '*/externals/*' -not -name '.gitmodules' | sed 's|^\./||')"})
fi
cd "$SOURCE_DIR" || { echo "${RED}Failed to cd to source${NC}"; exit 1; }
echo "${BLUE}Syncing ${#files[@]} files...${NC}"
echo ""
# Sync each file that exists in destination
for file in "${files[@]}"; do
src_file="$SOURCE_DIR/$file"
dest_file="$DEST_DIR/$file"
# echo "Processing: $file"
if [[ -f "$src_file" ]]; then
# Check if source is newer than destination or if destination doesn't exist
if [[ "$src_file" -nt "$dest_file" ]] || [[ ! -f "$dest_file" ]]; then
if [[ $DRY_RUN -eq 1 ]]; then
echo "${BLUE}→${NC} Would sync: $file"
((synced_count++)) || true
else
# Create destination directory if needed
dest_dir=$(dirname "$dest_file")
mkdir -p "$dest_dir"
# Copy file preserving timestamps
if cp -p "$src_file" "$dest_file"; then
echo "${GREEN}✓${NC} Synced: $file"
((synced_count++)) || true
else
echo "${RED}✗${NC} Failed: $file"
fi
fi
else
echo "${GREEN}=${NC} Up-to-date: $file"
((uptodate_count++)) || true
fi
else
echo "${YELLOW}⊘${NC} Not found in source: $file"
((skipped_count++)) || true
fi
done
echo ""
if [[ $DRY_RUN -eq 1 ]]; then
echo "${BLUE}=== Dry Run Complete ===${NC}"
echo "${BLUE}Would sync: $synced_count files${NC}"
else
echo "${BLUE}=== Sync Complete ===${NC}"
echo "${GREEN}Synced: $synced_count files${NC}"
fi
if [[ $uptodate_count -gt 0 ]]; then
echo "${GREEN}Up-to-date: $uptodate_count files${NC}"
fi
if [[ $skipped_count -gt 0 ]]; then
echo "${YELLOW}Skipped: $skipped_count files (not found in source)${NC}"
fi

3
initsubmodules Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
git submodule update --init --recursive

2
initsubmodules.bat Normal file
View file

@ -0,0 +1,2 @@
@echo off
git submodule update --init --recursive

33
license.txt Normal file
View file

@ -0,0 +1,33 @@
It is dual-licensed under the terms of the AGPL 3.0 license and
a commercial license for proprietary use. See the license.txt file in the
project root for details.
============================================================================
AGPL 3.0 license
============================================================================
PasLLM - A LLM inference engine
Copyright (C) 2025-2025, Benjamin Rosseaux (benjamin@rosseaux.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
============================================================================
Commercial license
============================================================================
Contact the author (benjamin@rosseaux.com) for details, as it is custom for
every use case.

26571
src/PasLLM.pas Normal file

File diff suppressed because it is too large Load diff

6408
src/PasLLMChatControl.pas Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,264 @@
unit PasLLMApp.FormMain;
interface
uses System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Generics.Collections,
System.Math,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Objects,
FMX.StdCtrls,
FMX.Layouts,
FMX.Controls.Presentation,
FMX.Effects,
FMX.Edit,
FMX.ListBox,
PasLLM,
PasHTMLDown,
PasHTMLDownCanvasRenderer,
PasLLMChatControl,
PasMP, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo;
type TStringQueue=TPasMPUnboundedQueue<TPasLLMRawByteString>;
{ TFormMain }
TFormMain = class(TForm)
MaterialOxfordBlueSB:TStyleBook;
ToolBar1:TToolBar;
ShadowEffect4:TShadowEffect;
Label1:TLabel;
PanelLeft: TPanel;
PanelLeftTop: TPanel;
PanelLeftBottom: TPanel;
ListBoxSessions: TListBox;
EditSessionName: TEdit;
ButtonNewSession: TButton;
StatusBar1: TStatusBar;
GridPanelLayout1: TGridPanelLayout;
StatusBarLabel1: TLabel;
StatusBarLabel2: TLabel;
StatusBarLabel3: TLabel;
StatusBarLabel4: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure EditSessionNameExit(Sender: TObject);
procedure ListBoxSessionsClick(Sender: TObject);
procedure ListBoxSessionsDblClick(Sender: TObject);
procedure ListBoxSessionsKeyDown(Sender: TObject; var Key: Word;
var KeyChar: WideChar; Shift: TShiftState);
procedure EditSessionNameKeyDown(Sender: TObject; var Key: Word;
var KeyChar: WideChar; Shift: TShiftState);
procedure ButtonNewSessionClick(Sender: TObject);
private
{ Private declarations }
procedure ChatControlRequestModelList(aSender:TObject;var aModels:TPasLLMChatControl.TPasLLMModels);
public
{ Public declarations }
fChatControl:TPasLLMChatControl;
// Session management methods
procedure RefreshSessionsList;
procedure LoadSelectedSession;
procedure DeleteSelectedSession;
procedure CreateNewSession;
procedure SaveCurrentSession;
end;
var FormMain:TFormMain;
implementation
{$R *.fmx}
{ TFormMain }
procedure TFormMain.EditSessionNameExit(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.UpdateCurrentSessionTitle(EditSessionName.Text);
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.EditSessionNameKeyDown(Sender: TObject; var Key: Word;
var KeyChar: WideChar; Shift: TShiftState);
begin
if (Key=13) and assigned(fChatControl) then begin // Enter
// Update session title and auto-save
fChatControl.UpdateCurrentSessionTitle(Trim(EditSessionName.Text));
Key:=0;
KeyChar:=#0;
end;
end;
procedure TFormMain.ButtonNewSessionClick(Sender: TObject);
begin
CreateNewSession;
end;
procedure TFormMain.ChatControlRequestModelList(aSender:TObject;var aModels:TPasLLMChatControl.TPasLLMModels);
var SearchRec:TSearchRec;
ModelDir:TPasLLMUTF8String;
Count:TPasLLMInt32;
begin
// Scan for models in the executable directory
ModelDir:=IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
Count:=0;
if FindFirst(ModelDir+'*.safetensors',faAnyFile,SearchRec)=0 then begin
try
repeat
inc(Count);
SetLength(aModels,Count);
aModels[Count-1]:=SearchRec.Name;
until FindNext(SearchRec)<>0;
finally
FindClose(SearchRec);
end;
end;
// If no models found, provide some example names
if Count=0 then begin
SetLength(aModels,3);
aModels[0]:='qwen2.5_0.5b_instruct_q40nl.safetensors';
aModels[1]:='llama32_1b_instruct_q40nl.safetensors';
aModels[2]:='smollm2_1.7b_instruct_q40nl.safetensors';
end;
end;
procedure TFormMain.FormCreate(Sender:TObject);
begin
{BorderStyle := TFmxFormBorderStyle.Single;
Transparency := False; }
fChatControl:=TPasLLMChatControl.Create(self);
fChatControl.Parent:=self;
fChatControl.Align:=TAlignLayout.Client;
fChatControl.EditSessionName:=EditSessionName;
fChatControl.OnRequestModelList:=ChatControlRequestModelList;
fChatControl.StatusBarLabel1:=StatusBarLabel1;
fChatControl.StatusBarLabel2:=StatusBarLabel2;
fChatControl.StatusBarLabel3:=StatusBarLabel3;
fChatControl.StatusBarLabel4:=StatusBarLabel4;
// Initial session list refresh
RefreshSessionsList;
fChatControl.PopulateSessionsList(ListBoxSessions);
(*
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
'Here is a comparison table between the US Dollar (USD) and the Euro (EUR):'+#13#10+
''+#13#10+
'**Note:** The exchange rates provided are subject to change and may not reflect the current exchange rates. For the most up-to-date and accurate rates, please check the current exchange rates on a reliable source such as XE.com or a financial institution.'+#13#10+
''+#13#10+
'| **Category** | **US Dollar (USD)** | **Euro (EUR)** |'+#13#10+
'| --- | --- | --- |'+#13#10+
'| **1. Currency** | $100 = 1 EUR | 100 = 1 EUR |'+#13#10+
'| **2. Units** | 1 USD = 100 EUR | 1 EUR = 100 USD |'+#13#10+
'| **3. Exchanges** | Bank deposits, ATMs, Currency exchange offices | Bank deposits, ATMs, Currency exchange offices |'+#13#10+
'| **4. Withdrawals** | Withdraw from a bank or ATM in the US | Withdraw from a bank or ATM in the Eurozone |'+#13#10+
'| **5. Deposits** | Deposit cash, cashier''s checks | Deposit cash, cashier''s checks |'+#13#10+
'| **6. Minimums** | No minimums | No minimums |'+#13#10+
'| **7. Maximums** | No maximums | No maximums |'+#13#10+
'| **8. Taxes** | No taxes | 0% |'+#13#10+
'| **9. Fees** | No fees | 0% |'+#13#10+
'| **10. Currency Controls** | No currency controls | No currency controls |'+#13#10+
'| **11. International Trade** | All international trade transactions are in USD | All international trade transactions are in EUR |'+#13#10+
'| **12. Travel** | All travel transactions are in USD | All travel transactions are in EUR |'+#13#10+
'| **13. Currency and Credit Card Transactions** | All transactions are subject to US Dollar and Euro currency and credit card regulations | All transactions are subject to US Dollar and Euro currency and credit card regulations |'+#13#10+
'| **14. Online Purchases** | All online purchases are subject to US Dollar and Euro currency and credit card regulations | All online purchases are subject to US Dollar and Euro currency and credit card regulations |'+#13#10+
'| **15. Currency and Credit Card Regulations** | All currency and credit card transactions are subject to the regulations of both the US and the Eurozone | All currency and credit card transactions are subject to the regulations of the US and the Eurozone |'+#13#10+
''+#13#10+
'**Disclaimer:** This comparison table is for informational purposes only and is not intended to be a comprehensive or definitive guide to the use of the US Dollar and the Euro. The use of the US Dollar and the Euro for international transactions is subject to the laws and regulations of both the US and the Eurozone, and users are encouraged to consult with a qualified professional before making any decisions.'#13#10);
*)
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
{}
end;
procedure TFormMain.ListBoxSessionsClick(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.OnSessionSelected(ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ListBoxSessionsDblClick(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ListBoxSessionsKeyDown(Sender: TObject; var Key: Word;
var KeyChar: WideChar; Shift: TShiftState);
begin
if assigned(fChatControl) then begin
case Key of
vkReturn:begin // Enter
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
Key:=0;
KeyChar:=#0;
end;
vkDelete:begin // Delete
if ssCtrl in Shift then begin
fChatControl.DeleteSelectedSession(ListBoxSessions.ItemIndex);
Key:=0;
KeyChar:=#0;
end;
end;
end;
end;
end;
procedure TFormMain.RefreshSessionsList;
begin
if assigned(fChatControl) then begin
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.LoadSelectedSession;
begin
if assigned(fChatControl) then begin
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.DeleteSelectedSession;
begin
if assigned(fChatControl) then begin
fChatControl.DeleteSelectedSession(ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.CreateNewSession;
begin
if assigned(fChatControl) then begin
fChatControl.NewChatSession;
fChatControl.RefreshSessionsList;
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.SaveCurrentSession;
begin
// Remove this method - auto-save handles everything
// Keep for backward compatibility but make it do nothing
end;
end.

View file

@ -0,0 +1,63 @@
program pasllmappfmx;
{$legacyifend on}
uses
System.StartUpCopy,
FMX.Types,
{$ifdef mswindows}
Windows,
{$endif }
FMX.Forms,
FMX.Skia,
PasLLMApp.FormMain in 'PasLLMApp.FormMain.pas' {FormMain},
PasLLM in '..\PasLLM.pas';
{$R *.res}
{$ifdef mswindows}
function IsWine: Boolean;
type
TWineGetVersion = function: PAnsiChar; cdecl;
var
hNTDLL: HMODULE;
WineGetVersion: TWineGetVersion;
begin
Result := False;
hNTDLL := GetModuleHandle('ntdll.dll');
if hNTDLL <> 0 then
begin
WineGetVersion := GetProcAddress(hNTDLL, 'wine_get_version');
Result := Assigned(WineGetVersion);
end;
end;
{$endif}
begin
{$ifdef mswindows}
if IsWine then begin
// 1) Make sure Skia is OFF on Windows
{$if declared(GlobalUseSkia)}
GlobalUseSkia := false;
{$ifend}
// 2) Avoid GPU canvas (DX) and Direct2D force GDI+ software canvas
GlobalUseGPUCanvas := False; // don't use TCanvasGpu
GlobalUseDirect2D := False; // turn off D2D; FMX will use GDI+ for 2D
end else begin
FMX.Skia.GlobalUseSkia:=true;
end;
// Optional: if present in your Delphi version
// GlobalUseDX := False; // replaces deprecated GlobalUseDX10
// GlobalUseDX10Software := True; // force D2D WARP (software rasterizer)
{$endif}
Application.Initialize;
Application.CreateForm(TFormMain, FormMain);
Application.Run;
end.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,233 @@
object FormMain: TFormMain
Left = 0
Height = 549
Top = 0
Width = 800
Caption = 'PasLLM App LCL - Copyright (C) 2025, Benjamin ''BeRo'' Rosseaux'
ClientHeight = 451
ClientWidth = 640
Color = clBtnFace
Constraints.MinHeight = 480
Constraints.MinWidth = 640
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Default'
Menu = MainMenu
OnCreate = FormCreate
OnDestroy = FormDestroy
OnResize = FormResize
Position = poScreenCenter
LCLVersion = '2.3.0.0'
object PanelTop: TPanel
Left = 0
Height = 50
Top = 0
Width = 800
Align = alTop
BevelOuter = bvNone
ParentBackground = False
TabOrder = 0
Visible = False
end
object PanelLeft: TPanel
AnchorSideRight.Control = Owner
AnchorSideRight.Side = asrBottom
Left = 0
Height = 474
Top = 50
Width = 200
Align = alLeft
ClientHeight = 474
ClientWidth = 200
ParentBackground = False
TabOrder = 1
object PanelLeftTop: TPanel
Left = 9
Height = 50
Top = 9
Width = 182
Align = alTop
BorderSpacing.Around = 8
ClientHeight = 50
ClientWidth = 182
ParentBackground = False
TabOrder = 0
object EditSessionName: TEdit
AnchorSideLeft.Control = PanelLeftTop
AnchorSideTop.Control = PanelLeftTop
AnchorSideTop.Side = asrCenter
AnchorSideRight.Control = PanelLeftTop
AnchorSideRight.Side = asrBottom
Left = 9
Height = 21
Top = 15
Width = 164
Anchors = [akTop, akLeft, akRight]
BorderSpacing.Left = 8
BorderSpacing.Top = 8
BorderSpacing.Right = 8
BorderSpacing.Bottom = 8
OnChange = EditSessionNameChange
OnExit = EditSessionNameExit
TabOrder = 0
end
end
object PanelSessions: TPanel
Left = 9
Height = 340
Top = 67
Width = 182
Align = alClient
BorderSpacing.Around = 8
ClientHeight = 340
ClientWidth = 182
ParentBackground = False
TabOrder = 1
object ListBoxSessions: TListBox
Left = 9
Height = 322
Top = 9
Width = 164
Align = alClient
BorderSpacing.Around = 8
ItemHeight = 0
TabOrder = 0
end
end
object PanelLeftBottom: TPanel
Left = 9
Height = 50
Top = 415
Width = 182
Align = alBottom
BorderSpacing.Around = 8
ClientHeight = 50
ClientWidth = 182
ParentBackground = False
TabOrder = 2
object FlowPanel1: TFlowPanel
Left = 1
Height = 48
Top = 1
Width = 180
Align = alClient
AutoSize = True
BevelOuter = bvNone
ControlList = <>
FlowLayout = tlTop
FlowStyle = fsLeftRightTopBottom
TabOrder = 0
end
object ButtonNew: TButton
AnchorSideLeft.Control = PanelLeftBottom
AnchorSideTop.Control = PanelLeftBottom
AnchorSideTop.Side = asrCenter
AnchorSideBottom.Side = asrBottom
Left = 9
Height = 23
Top = 14
Width = 49
AutoSize = True
BorderSpacing.Around = 8
Caption = '&New'
OnClick = ButtonNewClick
TabOrder = 1
end
end
end
object PanelChat: TPanel
Left = 205
Height = 474
Top = 50
Width = 595
Align = alClient
ParentBackground = False
TabOrder = 2
end
object Splitter1: TSplitter
AnchorSideLeft.Control = PanelLeft
AnchorSideLeft.Side = asrBottom
AnchorSideTop.Control = PanelLeft
Left = 200
Height = 474
Top = 50
Width = 5
Beveled = True
end
object PanelBottom: TPanel
Left = 0
Height = 25
Top = 524
Width = 800
Align = alBottom
AutoSize = True
ClientHeight = 25
ClientWidth = 800
ParentBackground = False
TabOrder = 4
object StatusBar1: TStatusBar
Left = 1
Height = 23
Top = 1
Width = 798
Align = alClient
Panels = <
item
Text = 'Ready'
Width = 200
end
item
Text = '0 prompt token/seconds'
Width = 200
end
item
Text = '0 output token/seconds'
Width = 200
end
item
Text = '0 total token/seconds'
Width = 200
end>
SimplePanel = False
end
end
object MainMenu: TMainMenu
Left = 608
object MenuFile: TMenuItem
Caption = '&File'
object MenuFileExit: TMenuItem
Caption = 'E&xit'
ShortCut = 32883
OnClick = MenuFileExitClick
end
end
object MenuEdit: TMenuItem
Caption = '&Edit'
object MenuEditClear: TMenuItem
Caption = '&Clear Chat'
ShortCut = 16430
OnClick = MenuEditClearClick
end
object MenuEditSeparator: TMenuItem
Caption = '-'
end
object MenuEditCopy: TMenuItem
Caption = '&Copy Last Response'
ShortCut = 24643
OnClick = MenuEditCopyClick
end
object MenuEditSelectAll: TMenuItem
Caption = 'Select &All'
ShortCut = 16449
OnClick = MenuEditSelectAllClick
end
end
object MenuHelp: TMenuItem
Caption = '&Help'
object MenuHelpAbout: TMenuItem
Caption = '&About...'
OnClick = MenuHelpAboutClick
end
end
end
end

View file

@ -0,0 +1,558 @@
unit UnitFormMain;
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpu386}
{$asmmode intel}
{$endif}
{$ifdef cpuamd64}
{$asmmode intel}
{$endif}
{$ifdef FPC_LITTLE_ENDIAN}
{$define LITTLE_ENDIAN}
{$else}
{$ifdef FPC_BIG_ENDIAN}
{$define BIG_ENDIAN}
{$endif}
{$endif}
{-$pic off}
{$ifdef fpc_has_internal_sar}
{$define HasSAR}
{$endif}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$define CAN_INLINE}
{$define HAS_ADVANCED_RECORDS}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define LITTLE_ENDIAN}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$define HAS_TYPE_SINGLE}
{$undef CAN_INLINE}
{$undef HAS_ADVANCED_RECORDS}
{$endif}
interface
uses Classes,SysUtils,Forms,Controls,Graphics,Dialogs,StdCtrls,ExtCtrls,
ComCtrls,Menus,
{$ifdef fpc}
LCLType,LCLIntf,
LCLVersion,LResources, PairSplitter,
{$endif}
PasLLM,PasLLMChatControl;
type { TFormMain }
TFormMain=class(TForm)
ButtonNew: TButton;
EditSessionName: TEdit;
// UI components
fChatControl:TPasLLMChatControl;
FlowPanel1: TFlowPanel;
ListBoxSessions: TListBox;
MenuEditSeparator: TMenuItem;
PanelLeftBottom: TPanel;
PanelSessions: TPanel;
PanelLeftTop: TPanel;
PanelBottom: TPanel;
PanelLeft: TPanel;
PanelChat: TPanel;
PanelTop:TPanel;
MainMenu:TMainMenu;
MenuFile:TMenuItem;
MenuFileExit:TMenuItem;
MenuEdit:TMenuItem;
MenuEditClear:TMenuItem;
MenuEditCopy:TMenuItem;
MenuEditSelectAll:TMenuItem;
MenuHelp:TMenuItem;
MenuHelpAbout:TMenuItem;
Splitter1: TSplitter;
StatusBar1: TStatusBar;
// Event handlers
procedure EditSessionNameChange(Sender: TObject);
procedure EditSessionNameExit(Sender: TObject);
procedure FormCreate(aSender:TObject);
procedure FormDestroy(aSender:TObject);
procedure FormResize(aSender:TObject);
procedure ButtonRefreshClick(aSender:TObject);
procedure ComboModelChange(aSender:TObject);
// Session management event handlers
procedure ButtonNewClick(aSender:TObject);
procedure ListBoxSessionsClick(aSender:TObject);
procedure ListBoxSessionsDblClick(aSender:TObject);
procedure ListBoxSessionsKeyDown(aSender:TObject;var aKey:Word;aShift:TShiftState);
procedure EditSessionNameKeyPress(aSender:TObject;var aKey:char);
procedure ChatControlSendPrompt(aSender:TObject;const aPrompt:TPasLLMUTF8String);
procedure ChatControlModelChanged(aSender:TObject;const aModel:TPasLLMUTF8String);
procedure ChatControlRequestModelList(aSender:TObject;var aModels:TPasLLMChatControl.TPasLLMModels);
procedure MenuFileExitClick(aSender:TObject);
procedure MenuEditClearClick(aSender:TObject);
procedure MenuEditCopyClick(aSender:TObject);
procedure MenuEditSelectAllClick(aSender:TObject);
procedure MenuHelpAboutClick(aSender:TObject);
public
// Internal methods
procedure SetupUI;
procedure UpdateModelCombo;
procedure AddDemoMessages;
// Session management methods
procedure RefreshSessionsList;
procedure LoadSelectedSession;
procedure DeleteSelectedSession;
procedure CreateNewSession;
procedure SaveCurrentSession;
end;
var FormMain:TFormMain;
implementation
{$R *.lfm}
{ TFormMain }
procedure TFormMain.FormCreate(aSender:TObject);
begin
WindowState:=wsMaximized;
// Setup UI
SetupUI;
// Update model list
UpdateModelCombo;
// Add some demo messages to show the chat control
AddDemoMessages;
end;
procedure TFormMain.EditSessionNameChange(Sender: TObject);
begin
end;
procedure TFormMain.EditSessionNameExit(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.UpdateCurrentSessionTitle(EditSessionName.Text);
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.FormDestroy(aSender:TObject);
begin
// Nothing to clean up - TPasLLMChatControl handles its own resources
end;
procedure TFormMain.FormResize(aSender:TObject);
begin
// Chat control automatically resizes due to Align=alClient
end;
procedure TFormMain.SetupUI;
begin
// Create chat control (custom component must be created in code)
fChatControl:=TPasLLMChatControl.Create(Self);
fChatControl.Parent:=PanelChat;
fChatControl.Align:=alClient;
fChatControl.StatusBar:=StatusBar1;
fChatControl.EditSessionName:=EditSessionName;
fChatControl.OnSendPrompt:=ChatControlSendPrompt;
fChatControl.OnModelChanged:=ChatControlModelChanged;
fChatControl.OnRequestModelList:=ChatControlRequestModelList;
// Wire up session management UI events
ButtonNew.OnClick:=ButtonNewClick;
ListBoxSessions.OnClick:=ListBoxSessionsClick;
ListBoxSessions.OnDblClick:=ListBoxSessionsDblClick;
ListBoxSessions.OnKeyDown:=ListBoxSessionsKeyDown;
EditSessionName.OnKeyPress:=EditSessionNameKeyPress;
// Initial session list refresh
RefreshSessionsList;
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
procedure TFormMain.ButtonRefreshClick(aSender:TObject);
begin
UpdateModelCombo;
end;
procedure TFormMain.ComboModelChange(aSender:TObject);
begin
{if ComboModel.ItemIndex>=0 then begin
fChatControl.SelectedModel:=ComboModel.Items[ComboModel.ItemIndex];
end;}
end;
procedure TFormMain.ChatControlSendPrompt(aSender:TObject;const aPrompt:TPasLLMUTF8String);
begin
// The chat control handles everything automatically via its internal threading
// Auto-save is handled by TPasLLMChatControl on every message change
end;
procedure TFormMain.ChatControlModelChanged(aSender:TObject;const aModel:TPasLLMUTF8String);
begin
// Update our combo box to match the chat control's selection
//ComboModel.ItemIndex:=ComboModel.Items.IndexOf(aModel);
end;
procedure TFormMain.ChatControlRequestModelList(aSender:TObject;var aModels:TPasLLMChatControl.TPasLLMModels);
var SearchRec:TSearchRec;
ModelDir:TPasLLMUTF8String;
Count:TPasLLMInt32;
begin
// Scan for models in the executable directory
ModelDir:=IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))+'models');
Count:=0;
if FindFirst(ModelDir+'*.safetensors',faAnyFile,SearchRec)=0 then begin
try
repeat
inc(Count);
SetLength(aModels,Count);
aModels[Count-1]:=SearchRec.Name;
until FindNext(SearchRec)<>0;
finally
FindClose(SearchRec);
end;
end;
// If no models found, provide some example names
if Count=0 then begin
SetLength(aModels,3);
aModels[0]:='qwen2.5_0.5b_instruct_q40nl.safetensors';
aModels[1]:='llama32_1b_instruct_q40nl.safetensors';
aModels[2]:='smollm2_1.7b_instruct_q40nl.safetensors';
end;
end;
procedure TFormMain.MenuFileExitClick(aSender:TObject);
begin
Close;
end;
procedure TFormMain.MenuEditClearClick(aSender:TObject);
begin
fChatControl.Clear;
end;
procedure TFormMain.MenuEditCopyClick(aSender:TObject);
begin
fChatControl.CopyLastAssistantMessage;
end;
procedure TFormMain.MenuEditSelectAllClick(aSender:TObject);
begin
fChatControl.SelectAll;
end;
procedure TFormMain.MenuHelpAboutClick(aSender:TObject);
begin
ShowMessage('PasLLM Chat Control Demo'+#13#10+
'Demonstrates the TControlChat component'+#13#10+
'for PasLLM (Pascal AI Language Model)'+#13#10#13#10+
'Copyright (C) 2025 Benjamin Rosseaux');
end;
procedure TFormMain.UpdateModelCombo;
{var Models:TPasLLMChatControl.TPasLLMModels;
Index:TPasLLMInt32;}
begin
// Get model list from chat control
//ChatControlRequestModelList(fChatControl,Models);
{ComboModel.Items.BeginUpdate;
try
ComboModel.Clear;
for Index:=0 to Length(Models)-1 do begin
ComboModel.Items.Add(Models[Index]);
end;
// Select first model if available
if ComboModel.Items.Count>0 then begin
ComboModel.ItemIndex:=0;
ComboModelChange(ComboModel);
end;
finally
ComboModel.Items.EndUpdate;
end;}
end;
procedure TFormMain.AddDemoMessages;
begin
// Add some demo messages to show the chat control functionality
exit;
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
'|**A**|**B**|**C**|'+#13#10+
'|---|---|---|'+#13#10+
'| D | E | F<br>G<br>H |'+#13#10+
'| D | E<br>F<br>G | H |'+#13#10+
'| D<br>E<br>F | G | H |'+#13#10+
''+#13#10+#13#10);
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,'[Hello World](uuu');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,'**2 + 2 = 4** 6 + 6 = 12');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,'6^2');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,'6+6=12');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
''+#10+
'* | *a*|*b* | *c*|'+#10+
' |----|----|----|'+#10+
' | d | e | f |'+#10+
''+#10);
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
''+#10+
'Hello! Yes, absolutely — here are some practical and realistic ideas for making money, depending on your skills, time, location, and goals. Whether you''re looking for side income, a full-time job, or passive income, heres a mix of options:'+#10+
''+#10+
'---'+#10+
''+#10+
'### 💡 **Side Hustles (Low Time, Low Risk)**'+#10+
'1. **Freelancing**'+#10+
' - Offer services like writing, graphic design, copywriting, video editing, or translation.'+#10+
' - Platforms: Fiverr, Upwork, Freelancer, or LinkedIn.'+#10+
''+#10+
'2. **Teaching or Tutoring**'+#10+
' - Teach languages, math, or music online via Zoom or in person.'+#10+
' - Great for students or teachers.'+#10+
''+#10);
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
''+#10+
'A **HTML renderer** is a software component or system that takes raw HTML (HyperText Markup Language) code and converts it into a visual, interactive web page that can be displayed in a web browser or other viewing environment.'+#10+
''+#10+
{ '### Key Responsibilities of an HTML Renderer:'+#10+
'1. **Parsing HTML**: Reads the raw HTML text and constructs a **Document Object Model (DOM)** tree from the markup.'+#10+
'2. **Cascading Style Sheets (CSS) Processing**: Applies styles from CSS files or inline styles to elements in the DOM.'+#10+
'3. **Layout (or Reflow)**: Calculates the position, size, and spacing of all elements on the page based on the DOM and CSS.'+#10+
'4. **Painting**: Converts the layout into visual pixels by drawing elements (text, borders, backgrounds, etc.) onto a canvas.'+#10+
'5. **Compositing**: Combines multiple layers (e.g., from animations, transparency, or scrollable regions) into a final image displayed on screen.'+#10+
'6. **Handling Interactivity**: Processes user events (like clicks, scrolls, and keyboard input) and updates the DOM and visual output accordingly.'+#10+
''+#10+}
'### Examples of HTML Renderers:'+#10+
'- **Web Browsers**:'+#10+
' - **Blink** (used in Chrome and Edge)'+#10+
' - **WebKit** (used in Safari)'+#10+
' - **Gecko** (used in Firefox)'+#10+
''+#10+
'- **Headless Renderers**:'+#10+
''+#10+
' - **Puppeteer** (Node.js library using Chromiums renderer)'+#10+
''+#10+
' - **Playwright**, **Webkit**, **Cypress** (for testing and automation)'+#10+
''+#10+
'- **Server-side Renderers**:'+#10+
' - **Next.js (SSR/SSG)** using React with a renderer on the server'+#10+
' - **Nuxt.js** with Vue.js'+#10+
'- **Native Apps**:'+#10+
' - **WebView components** in Android (Android WebView), iOS (WKWebView), and React Native (React Native WebView)'+#10+
''+#10+
'### Why HTML Renderers Matter:'+#10+
'- They bridge the gap between **structured HTML/CSS/JS** and **user-facing visual content**.'+#10+
'- Enable responsive, dynamic, and interactive web experiences.'+#10+
'- Allow developers to write declarative markup and rely on the renderer to handle the visual presentation efficiently.'+#10+
''+#10+
'### Summary:'+#10+
'> An HTML renderer is the engine that transforms HTML, CSS, and JavaScript into a fully rendered, interactive webpage—turning code into what users see and interact with in their browsers.'+#10+
''+#10+
'Here are some code blocks for you:'+#10+
''+#10+
'**Basic Code Blocks**'+#10+
''+#10+
'* **Hello World**'+#10+
'```python'+#10+
'print("Hello, World!")'+#10+
'```'+#10+
'* **Basic Calculator**'+#10+
'```python'+#10+
'def calculate_area(length, width):'+#10+
' return length * width'+#10+
''+#10+
'length = 5'+#10+
'width = 3'+#10+
'print(calculate_area(length, width))'+#10+
'```'+#10+
''+#10+
'```md'+#10+
'```js'+#10+
'var a=1;'+#10+
'var a=1;'+#10+
'```'+#10#10+
'```js'+#10+
'var a=1;'+#10+
'var a=1;'+#10+
'```'+#10+
'```'+#10+
'');
exit;
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
'```javascript'+#13#10+
'Hello this is a test'+#13#10+#13#10+
' Hello this is a test'+#13#10+#13#10+
' Hello this is a test'+#13#10+
' Hello this is a test'+#13#10+
' Hello this is a test'+#13#10+
'```'+#13#10+#13#10);
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.System_,'Welcome to the **PasLLM** Chat Control Demo! It''s a good day for to live. Hello, how does this chat control work?');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
'Here is a comparison table between the US Dollar (USD) and the Euro (EUR):'+#13#10+
''+#13#10+
'**Note:** The exchange rates provided are subject to change and may not reflect the current exchange rates. For the most up-to-date and accurate rates, please check the current exchange rates on a reliable source such as XE.com or a financial institution.'+#13#10+
''+#13#10+
'| **Category** | **US Dollar (USD)** | **Euro (EUR)** |'+#13#10+
'| --- | --- | --- |'+#13#10+
'| **1. Currency** | $100 = 1 EUR | €100 = 1 EUR |'+#13#10+
'| **2. Units** | 1 USD = 100 EUR | 1 EUR = 100 USD |'+#13#10+
'| **3. Exchanges** | Bank deposits, ATMs, Currency exchange offices | Bank deposits, ATMs, Currency exchange offices |'+#13#10+
'| **4. Withdrawals** | Withdraw from a bank or ATM in the US | Withdraw from a bank or ATM in the Eurozone |'+#13#10+
'| **5. Deposits** | Deposit cash, cashier''s checks | Deposit cash, cashier''s checks |'+#13#10+
'| **6. Minimums** | No minimums | No minimums |'+#13#10+
'| **7. Maximums** | No maximums | No maximums |'+#13#10+
'| **8. Taxes** | No taxes | 0% |'+#13#10+
'| **9. Fees** | No fees | 0% |'+#13#10+
'| **10. Currency Controls** | No currency controls | No currency controls |'+#13#10+
'| **11. International Trade** | All international trade transactions are in USD | All international trade transactions are in EUR |'+#13#10+
'| **12. Travel** | All travel transactions are in USD | All travel transactions are in EUR |'+#13#10+
'| **13. Currency and Credit Card Transactions** | All transactions are subject to US Dollar and Euro currency and credit card regulations | All transactions are subject to US Dollar and Euro currency and credit card regulations |'+#13#10+
'| **14. Online Purchases** | All online purchases are subject to US Dollar and Euro currency and credit card regulations | All online purchases are subject to US Dollar and Euro currency and credit card regulations |'+#13#10+
'| **15. Currency and Credit Card Regulations** | All currency and credit card transactions are subject to the regulations of both the US and the Eurozone | All currency and credit card transactions are subject to the regulations of the US and the Eurozone |'+#13#10+
''+#13#10+
'**Disclaimer:** This comparison table is for informational purposes only and is not intended to be a comprehensive or definitive guide to the use of the US Dollar and the Euro. The use of the US Dollar and the Euro for international transactions is subject to the laws and regulations of both the US and the Eurozone, and users are encouraged to consult with a qualified professional before making any decisions.'#13#10);
{fChatControl.AddMessage(TPasLLMChatControl.TChatRole.System_,'Welcome to the PasLLM Chat Control Demo!');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.User,'Hello, how does this chat control work?');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
'This is the TControlChat component for PasLLM. It provides:'+#13#10+
'• Message bubbles with role-based colors and alignment'+#13#10+
'• Real-time token streaming during generation'+#13#10+
'• Model selection dropdown'+#13#10+
'• Prompt history with up/down arrow navigation'+#13#10+
'• Copy and selection features'+#13#10+
'• Keyboard shortcuts and mouse interaction'+#13#10#13#10+
'Select a model from the dropdown above and start chatting!');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.User,'What keyboard shortcuts are available?');
fChatControl.AddMessage(TPasLLMChatControl.TChatRole.Assistant,
'Available keyboard shortcuts:'+#13#10+
'• Enter: Send message'+#13#10+
'• Shift+Enter: New line in input'+#13#10+
'• Escape: Stop generation'+#13#10+
'• Up/Down arrows: Navigate prompt history'+#13#10+
'• Ctrl+A: Select all chat content'+#13#10+
'• Ctrl+C: Copy selection'+#13#10+
'• Page Up/Down: Scroll chat'+#13#10+
'• Ctrl+Home/End: Jump to top/bottom'); //}
end;
// Session management implementations
procedure TFormMain.ButtonNewClick(aSender:TObject);
begin
CreateNewSession;
end;
procedure TFormMain.ListBoxSessionsClick(aSender:TObject);
begin
if assigned(fChatControl) then begin
fChatControl.OnSessionSelected(ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ListBoxSessionsDblClick(aSender:TObject);
begin
if assigned(fChatControl) then begin
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ListBoxSessionsKeyDown(aSender:TObject;var aKey:Word;aShift:TShiftState);
begin
if assigned(fChatControl) then begin
case aKey of
VK_RETURN:begin // Enter
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
aKey:=0;
end;
VK_DELETE:begin // Delete
if ssCtrl in aShift then begin
fChatControl.DeleteSelectedSession(ListBoxSessions.ItemIndex);
aKey:=0;
end;
end;
end;
end;
end;
procedure TFormMain.EditSessionNameKeyPress(aSender:TObject;var aKey:char);
begin
if (aKey=#13) and assigned(fChatControl) then begin // Enter
// Update session title and auto-save
fChatControl.UpdateCurrentSessionTitle(Trim(EditSessionName.Text));
aKey:=#0;
end;
end;
procedure TFormMain.RefreshSessionsList;
begin
if assigned(fChatControl) then begin
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.LoadSelectedSession;
begin
if assigned(fChatControl) then begin
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.DeleteSelectedSession;
begin
if assigned(fChatControl) then begin
fChatControl.DeleteSelectedSession(ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.CreateNewSession;
begin
if assigned(fChatControl) then begin
fChatControl.NewChatSession;
fChatControl.RefreshSessionsList;
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.SaveCurrentSession;
begin
// Remove this method - auto-save handles everything
// Keep for backward compatibility but make it do nothing
end;
end.

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

View file

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectOptions>
<Version Value="12"/>
<PathDelim Value="\"/>
<General>
<SessionStorage Value="InProjectDir"/>
<Title Value="PasLLM App"/>
<Scaled Value="True"/>
<ResourceType Value="res"/>
<UseXPManifest Value="True"/>
<XPManifest>
<DpiAware Value="True"/>
</XPManifest>
<Icon Value="0"/>
</General>
<BuildModes>
<Item Name="Default" Default="True"/>
<Item Name="Windows">
<CompilerOptions>
<Version Value="11"/>
<PathDelim Value="\"/>
<Target>
<Filename Value="..\..\bin\pasllmapplcl"/>
</Target>
<SearchPaths>
<IncludeFiles Value="$(ProjOutDir)"/>
<OtherUnitFiles Value="..;..\synapse;..\..\externals\pinja\src;..\..\externals\pasdblstrutils\src;..\..\externals\pashtmldown\src;..\..\externals\pasjson\src;..\..\externals\pasmp\src"/>
<UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/>
</SearchPaths>
<CodeGeneration>
<TargetOS Value="win64"/>
<Optimizations>
<OptimizationLevel Value="3"/>
</Optimizations>
</CodeGeneration>
<Linking>
<Debugging>
<DebugInfoType Value="dsDwarf3"/>
</Debugging>
<Options>
<Win32>
<GraphicApplication Value="True"/>
</Win32>
</Options>
</Linking>
</CompilerOptions>
</Item>
</BuildModes>
<PublishOptions>
<Version Value="2"/>
<UseFileFilters Value="True"/>
</PublishOptions>
<RunParams>
<FormatVersion Value="2"/>
</RunParams>
<RequiredPackages>
<Item>
<PackageName Value="LCL"/>
</Item>
</RequiredPackages>
<Units>
<Unit>
<Filename Value="pasllmapplcl.lpr"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\PasLLM.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pinja\src\Pinja.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pinja\src\PinjaChatTemplate.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="UnitFormMain.pas"/>
<IsPartOfProject Value="True"/>
<ComponentName Value="FormMain"/>
<HasResources Value="True"/>
<ResourceBaseClass Value="Form"/>
</Unit>
<Unit>
<Filename Value="..\PasLLMChatControl.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pasdblstrutils\src\PasDblStrUtils.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pashtmldown\src\PasHTMLDown.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pashtmldown\src\PasHTMLDownCanvasRenderer.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pasjson\src\PasJSON.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="..\..\externals\pasmp\src\PasMP.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
</Units>
</ProjectOptions>
<CompilerOptions>
<Version Value="11"/>
<PathDelim Value="\"/>
<Target>
<Filename Value="..\..\bin\pasllmapplcl"/>
</Target>
<SearchPaths>
<IncludeFiles Value="$(ProjOutDir)"/>
<OtherUnitFiles Value="..;..\synapse;..\..\externals\pinja\src;..\..\externals\pasdblstrutils\src;..\..\externals\pashtmldown\src;..\..\externals\pasjson\src;..\..\externals\pasmp\src"/>
<UnitOutputDirectory Value="lib\$(TargetCPU)-$(TargetOS)"/>
</SearchPaths>
<CodeGeneration>
<Optimizations>
<OptimizationLevel Value="3"/>
</Optimizations>
</CodeGeneration>
<Linking>
<Debugging>
<DebugInfoType Value="dsDwarf3"/>
</Debugging>
<Options>
<Win32>
<GraphicApplication Value="True"/>
</Win32>
</Options>
</Linking>
</CompilerOptions>
<Debugging>
<Exceptions>
<Item>
<Name Value="EAbort"/>
</Item>
<Item>
<Name Value="ECodetoolError"/>
</Item>
<Item>
<Name Value="EFOpenError"/>
</Item>
<Item>
<Name Value="Exception"/>
</Item>
</Exceptions>
</Debugging>
</CONFIG>

View file

@ -0,0 +1,28 @@
program pasllmapplcl;
{$mode delphi}
uses
{$IFDEF UNIX}
cmem,
cthreads,
{$ENDIF}
{$IFDEF HASAMIGA}
athreads,
{$ENDIF}
Interfaces, // this includes the LCL widgetset
Forms, PasLLM, Pinja, PinjaChatTemplate, PasLLMChatControl, PasDblStrUtils,
PasHTMLDown, PasHTMLDownCanvasRenderer, PasJSON, PasMP, UnitFormMain
{ you can add units after this };
{$R *.res}
begin
RequireDerivedFormResource:=True;
Application.Title:='PasLLM App';
Application.Scaled:=True;
Application.Initialize;
Application.CreateForm(TFormMain, FormMain);
Application.Run;
end.

View file

@ -0,0 +1,129 @@
object FormMain: TFormMain
Left = 0
Top = 0
Caption = 'PasLLM App VCL- Copyright (C) 2025, Benjamin '#39'BeRo'#39' Rosseaux'
ClientHeight = 441
ClientWidth = 624
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Segoe UI'
Font.Style = []
WindowState = wsMaximized
OnCreate = FormCreate
OnDestroy = FormDestroy
OnShow = FormShow
TextHeight = 15
object Splitter1: TSplitter
Left = 185
Top = 0
Height = 422
ExplicitLeft = 112
ExplicitTop = 256
ExplicitHeight = 100
end
object PanelLeft: TPanel
Left = 0
Top = 0
Width = 185
Height = 422
Align = alLeft
TabOrder = 0
object PanelLeftTop: TPanel
Left = 1
Top = 1
Width = 183
Height = 41
Align = alTop
TabOrder = 0
ExplicitLeft = 96
ExplicitTop = 120
ExplicitWidth = 185
object EditSessionName: TEdit
Left = 1
Top = 1
Width = 181
Height = 39
Align = alClient
TabOrder = 0
OnExit = EditSessionNameExit
OnKeyPress = EditSessionNameKeyPress
ExplicitLeft = 48
ExplicitTop = 24
ExplicitWidth = 121
ExplicitHeight = 23
end
end
object PanelLeftBottom: TPanel
Left = 1
Top = 380
Width = 183
Height = 41
Align = alBottom
TabOrder = 1
ExplicitLeft = 104
ExplicitTop = 376
ExplicitWidth = 185
object ButtonNewSession: TButton
Left = 1
Top = 1
Width = 181
Height = 39
Align = alClient
Caption = 'New'
TabOrder = 0
OnClick = ButtonNewSessionClick
ExplicitLeft = 136
ExplicitTop = 8
ExplicitWidth = 75
ExplicitHeight = 25
end
end
object ListBoxSessions: TListBox
Left = 1
Top = 42
Width = 183
Height = 338
Align = alClient
ItemHeight = 15
TabOrder = 2
OnClick = ListBoxSessionsClick
OnDblClick = ListBoxSessionsDblClick
OnKeyDown = ListBoxSessionsKeyDown
ExplicitLeft = 104
ExplicitTop = 272
ExplicitWidth = 121
ExplicitHeight = 97
end
end
object PanelChat: TPanel
Left = 188
Top = 0
Width = 436
Height = 422
Align = alClient
TabOrder = 1
ExplicitLeft = 185
ExplicitWidth = 439
end
object StatusBar1: TStatusBar
Left = 0
Top = 422
Width = 624
Height = 19
Panels = <
item
Width = 200
end
item
Width = 200
end
item
Width = 200
end
item
Width = 200
end>
end
end

View file

@ -0,0 +1,199 @@
unit UnitFormMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, PasLLM, PasLLMChatControl, Vcl.ComCtrls,
Vcl.ExtCtrls, Vcl.StdCtrls;
type
TFormMain = class(TForm)
PanelLeft: TPanel;
PanelChat: TPanel;
StatusBar1: TStatusBar;
PanelLeftTop: TPanel;
PanelLeftBottom: TPanel;
Splitter1: TSplitter;
ButtonNewSession: TButton;
ListBoxSessions: TListBox;
EditSessionName: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EditSessionNameExit(Sender: TObject);
procedure EditSessionNameKeyPress(Sender: TObject; var Key: Char);
procedure ListBoxSessionsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ListBoxSessionsDblClick(Sender: TObject);
procedure ListBoxSessionsClick(Sender: TObject);
procedure ButtonNewSessionClick(Sender: TObject);
private
{ Private declarations }
procedure ChatControlRequestModelList(aSender:TObject;var aModels:TPasLLMChatControl.TPasLLMModels);
public
{ Public declarations }
fChatControl:TPasLLMChatControl;
// Session management methods
procedure RefreshSessionsList;
procedure LoadSelectedSession;
procedure DeleteSelectedSession;
procedure CreateNewSession;
procedure SaveCurrentSession;
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
procedure TFormMain.EditSessionNameExit(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.UpdateCurrentSessionTitle(EditSessionName.Text);
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.EditSessionNameKeyPress(Sender: TObject; var Key: Char);
begin
if (Key=#13) and assigned(fChatControl) then begin // Enter
// Update session title and auto-save
fChatControl.UpdateCurrentSessionTitle(Trim(EditSessionName.Text));
Key:=#0;
end;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
// Create chat control (custom component must be created in code)
fChatControl:=TPasLLMChatControl.Create(PanelChat);
fChatControl.Parent:=PanelChat;
fChatControl.Align:=alClient;
fChatControl.StatusBar:=StatusBar1;
fChatControl.EditSessionName:=EditSessionName;
{fChatControl.OnSendPrompt:=ChatControlSendPrompt;
fChatControl.OnModelChanged:=ChatControlModelChanged;}
// fChatControl.OnRequestModelList:=ChatControlRequestModelList;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
{}
end;
procedure TFormMain.FormShow(Sender: TObject);
begin
fChatControl.PopulateModelCombo;
// Initial session list refresh
RefreshSessionsList;
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
procedure TFormMain.ChatControlRequestModelList(aSender:TObject;var aModels:TPasLLMChatControl.TPasLLMModels);
var SearchRec:TSearchRec;
ModelDir:TPasLLMUTF8String;
Count:TPasLLMInt32;
begin
// Scan for models in the executable directory
ModelDir:=IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))+'models');
Count:=0;
if FindFirst(ModelDir+'*.safetensors',faAnyFile,SearchRec)=0 then begin
try
repeat
inc(Count);
SetLength(aModels,Count);
aModels[Count-1]:=SearchRec.Name;
until FindNext(SearchRec)<>0;
finally
FindClose(SearchRec);
end;
end;
// If no models found, provide some example names
if Count=0 then begin
SetLength(aModels,3);
aModels[0]:='qwen2.5_0.5b_instruct_q40nl.safetensors';
aModels[1]:='llama32_1b_instruct_q40nl.safetensors';
aModels[2]:='smollm2_1.7b_instruct_q40nl.safetensors';
end;
end;
procedure TFormMain.RefreshSessionsList;
begin
if assigned(fChatControl) then begin
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.ListBoxSessionsClick(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.OnSessionSelected(ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ListBoxSessionsDblClick(Sender: TObject);
begin
if assigned(fChatControl) then begin
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ListBoxSessionsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if assigned(fChatControl) then begin
case Key of
VK_RETURN:begin // Enter
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
Key:=0;
end;
VK_DELETE:begin // Delete
if ssCtrl in Shift then begin
fChatControl.DeleteSelectedSession(ListBoxSessions.ItemIndex);
Key:=0;
end;
end;
end;
end;
end;
procedure TFormMain.LoadSelectedSession;
begin
if assigned(fChatControl) then begin
fChatControl.LoadSession('',ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.DeleteSelectedSession;
begin
if assigned(fChatControl) then begin
fChatControl.DeleteSelectedSession(ListBoxSessions.ItemIndex);
end;
end;
procedure TFormMain.ButtonNewSessionClick(Sender: TObject);
begin
CreateNewSession;
end;
procedure TFormMain.CreateNewSession;
begin
if assigned(fChatControl) then begin
fChatControl.NewChatSession;
fChatControl.RefreshSessionsList;
fChatControl.PopulateSessionsList(ListBoxSessions);
end;
end;
procedure TFormMain.SaveCurrentSession;
begin
// Remove this method - auto-save handles everything
// Keep for backward compatibility but make it do nothing
end;
end.

View file

@ -0,0 +1,15 @@
program pasllmappvcl;
uses
Vcl.Forms,
UnitFormMain in 'UnitFormMain.pas' {FormMain},
PasLLM in '..\PasLLM.pas';
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TFormMain, FormMain);
Application.Run;
end.

File diff suppressed because it is too large Load diff

485
src/pasllmcli/pasllmcli.dpr Normal file
View file

@ -0,0 +1,485 @@
program pasllmcli;
{$ifdef fpc}
{$mode delphi}
{$endif}
{$ifdef win32}
{$apptype console}
{$endif}
{$ifdef win64}
{$apptype console}
{$endif}
{$scopedenums on}
uses
{$ifdef fpc}
{$ifdef unix}
cmem,
cthreads,
{$endif}
{$endif}
SysUtils,
Classes,
PasMP,
PasJSON,
PasLLM,
Pinja;
type { TPasLLMCLIInstance }
TPasLLMCLIInstance=class
public
type TArgument=record
Name:TPasLLMUTF8String;
Value:TPasLLMUTF8String;
end;
PArgument=^TArgument;
TArguments=array of TArgument;
TMode=
(
None,
Chat,
Generate,
Study
);
private
fArguments:TArguments;
fPasMPInstance:TPasMP;
fPasLLMInstance:TPasLLM;
fPasLLMModel:TPasLLMModel;
fPasLLMModelInferenceInstance:TPasLLMModelInferenceInstance;
fChatSession:TPasLLMModelInferenceInstance.TChatSession;
fMode:TMode;
fTavilyKey:TPasLLMUTF8String;
fModel:TPasLLMUTF8String;
fSystemPrompt:TPasLLMUTF8String;
fPrompt:TPasLLMUTF8String;
fQuitAfterPrompt:Boolean;
fTools:Boolean;
fTemperature:TPasLLMDouble;
fTopP:TPasLLMDouble;
fSeed:TPasLLMUInt64;
fPenaltyLastN:TPasLLMSizeInt;
fPenaltyRepeat:TPasLLMDouble;
fPenaltyFrequency:TPasLLMDouble;
fPenaltyPresence:TPasLLMDouble;
fPath:TPasLLMUTF8String;
fSteps:TPasLLMSizeInt;
fContextSize:TPasLLMSizeInt;
function DefaultOnInput(const aSender:TPasLLMModelInferenceInstance.TChatSession;const aPrompt:TPasLLMUTF8String):TPasLLMUTF8String;
procedure DefaultOnSideTurn(const aSender:TPasLLMModelInferenceInstance.TChatSession;const aSide:TPasLLMUTF8String);
procedure ParseArguments;
procedure LoadToolConfiguration;
public
constructor Create;
destructor Destroy; override;
procedure Run;
end;
constructor TPasLLMCLIInstance.Create;
begin
inherited Create;
fPasMPInstance:=TPasMP.CreateGlobalInstance;
fMode:=TMode.None;
fTavilyKey:='';
fModel:='';
fSystemPrompt:='';
fPrompt:='';
fQuitAfterPrompt:=false;
fTools:=false;
fTemperature:=0.6;
fTopP:=0.9;
fSeed:=0;
fPenaltyLastN:=0;
fPenaltyRepeat:=1.0;
fPenaltyFrequency:=0.0;
fPenaltyPresence:=0.0;
fPath:='';
fSteps:=0;
fContextSize:=4096;
ParseArguments;
if length(fModel)=0 then begin
// fModel:='qwen2.5_0.5b_instruct_q80.safetensors';
fModel:='llama32_1b_instruct_abliterated_q40nl.safetensors';
//fModel:='qwen3_4b_instruct_q40nl.safetensors';
end;
if not FileExists(fModel) then begin
fModel:=IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))+fModel;
if not FileExists(fModel) then begin
fModel:=IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))+'models')+fModel;
if not FileExists(fModel) then begin
raise Exception.Create('Model file not found: '+ExtractFileName(fModel));
end;
end;
end;
if fSteps<=0 then begin
fSteps:=0;
end;
if fMode=TMode.None then begin
fMode:=TMode.Chat;
end;
end;
destructor TPasLLMCLIInstance.Destroy;
begin
inherited Destroy;
end;
procedure TPasLLMCLIInstance.ParseArguments;
var Index,Count,ArgumentIndex,SplitterPosition:TPasLLMSizeInt;
Code:TPasLLMInt32;
Argument:PArgument;
ArgumentString,Name,Value:TPasLLMUTF8String;
StringList,OtherStringList:TStringList;
begin
// Read arguments from command line, files or standard input
Count:=0;
fArguments:=nil;
try
StringList:=TStringList.Create;
try
Index:=1;
while Index<=ParamCount do begin
ArgumentString:=Trim(ParamStr(Index));
if length(ArgumentString)>0 then begin
if (ArgumentString[1]='@') then begin
ArgumentString:=Copy(ArgumentString,2,length(ArgumentString)-1);
if (ArgumentString='-') or FileExists(ArgumentString) then begin
OtherStringList:=TStringList.Create;
try
if ArgumentString='-' then begin
// Load arguments from standard input until empty line or EOF
while not EOF do begin
ReadLn(ArgumentString);
ArgumentString:=Trim(ArgumentString);
if length(ArgumentString)=0 then begin
break;
end;
OtherStringList.Add(ArgumentString);
end;
end else begin
// Load arguments from file
OtherStringList.LoadFromFile(ArgumentString);
end;
StringList.AddStrings(OtherStringList);
finally
FreeAndNil(OtherStringList);
end;
end;
end else begin
StringList.Add(ArgumentString);
end;
end;
inc(Index);
end;
{ StringList.TextLineBreakStyle:=tlbsLF;
StringList.StrictDelimiter:=true;
StringList.Delimiter:=' ';}
for Index:=0 to StringList.Count-1 do begin
ArgumentString:=Trim(StringList[Index]);
if length(ArgumentString)>0 then begin
if (ArgumentString[1]='-') or (ArgumentString[1]='/') then begin
ArgumentString:=Copy(ArgumentString,2,length(ArgumentString)-1);
if (ArgumentString[1]='-') or (ArgumentString[1]='/') then begin
ArgumentString:=Copy(ArgumentString,2,length(ArgumentString)-1);
end;
SplitterPosition:=Pos('=',ArgumentString);
if SplitterPosition>0 then begin
Name:=Trim(Copy(ArgumentString,1,SplitterPosition-1));
Value:=Trim(Copy(ArgumentString,SplitterPosition+1,length(ArgumentString)-SplitterPosition));
end else begin
Name:=Trim(ArgumentString);
Value:='';
end;
ArgumentIndex:=Count;
inc(Count);
if length(fArguments)<Count then begin
SetLength(fArguments,Count*2);
end;
Argument:=@fArguments[ArgumentIndex];
Argument^.Name:=Name;
Argument^.Value:=Value;
end else begin
if fMode=TMode.None then begin
// Mode
Name:=LowerCase(ArgumentString);
if Name='chat' then begin
fMode:=TMode.Chat;
end else if Name='generate' then begin
fMode:=TMode.Generate;
end else if Name='study' then begin
fMode:=TMode.Study;
end else begin
fMode:=TMode.Chat; // Default to chat
end;
end else begin
// Prompt
if length(fPrompt)>0 then begin
fPrompt:=fPrompt+' '+ArgumentString;
end else begin
fPrompt:=ArgumentString;
end;
end;
end;
end;
end;
finally
FreeAndNil(StringList);
end;
finally
SetLength(fArguments,Count);
end;
// Process arguments
for Index:=0 to Count-1 do begin
Argument:=@fArguments[Index];
if Argument^.Name='model' then begin
fModel:=Argument^.Value;
end else if Argument^.Name='steps' then begin
fSteps:=StrToIntDef(Argument^.Value,0);
end else if Argument^.Name='context-size' then begin
fContextSize:=StrToIntDef(Argument^.Value,4096);
end else if Argument^.Name='tavily-key' then begin
fTavilyKey:=Argument^.Value;
end else if Argument^.Name='system-prompt' then begin
fSystemPrompt:=Argument^.Value;
end else if Argument^.Name='prompt' then begin
fPrompt:=Argument^.Value;
end else if Argument^.Name='quit-after-prompt' then begin
fQuitAfterPrompt:=(Argument^.Value='1') or (LowerCase(Argument^.Value)='true') or (length(Argument^.Value)=0);
end else if Argument^.Name='tools' then begin
fTools:=(Argument^.Value='1') or (LowerCase(Argument^.Value)='true') or (length(Argument^.Value)=0);
end else if Argument^.Name='temperature' then begin
Val(Argument^.Value,fTemperature,Code);
if Code=0 then begin
if fTemperature<0 then begin
fTemperature:=0;
end else if fTemperature>1 then begin
fTemperature:=1;
end;
end else begin
fTemperature:=0.6;
end;
end else if Argument^.Name='top-p' then begin
Val(Argument^.Value,fTopP,Code);
if Code=0 then begin
if fTopP<0 then begin
fTopP:=0;
end else if fTopP>1 then begin
fTopP:=1;
end;
end else begin
fTopP:=0.9;
end;
end else if Argument^.Name='seed' then begin
fSeed:=StrToUInt64Def(Argument^.Value,0);
end else if Argument^.Name='penalty-last-n' then begin
fPenaltyLastN:=StrToIntDef(Argument^.Value,0);
if fPenaltyLastN<0 then begin
fPenaltyLastN:=0;
end;
end else if Argument^.Name='penalty-repeat' then begin
Val(Argument^.Value,fPenaltyRepeat,Code);
if Code<>0 then begin
fPenaltyRepeat:=1.0;
end;
if fPenaltyRepeat<0.0 then begin
fPenaltyRepeat:=0.0;
end;
end else if Argument^.Name='penalty-frequency' then begin
Val(Argument^.Value,fPenaltyFrequency,Code);
if Code<>0 then begin
fPenaltyFrequency:=0.0;
end;
if fPenaltyFrequency<0.0 then begin
fPenaltyFrequency:=0.0;
end;
end else if Argument^.Name='penalty-presence' then begin
Val(Argument^.Value,fPenaltyPresence,Code);
if Code<>0 then begin
fPenaltyPresence:=0.0;
end;
if fPenaltyPresence<0.0 then begin
fPenaltyPresence:=0.0;
end;
end else if Argument^.Name='path' then begin
fPath:=Argument^.Value;
end else if (Argument^.Name='help') or (Argument^.Name='h') or (Argument^.Name='?') then begin
Writeln('PasLLM Command Line Interface');
Writeln('Usage: pasllmcli [options] [mode] ([prompt])');
Writeln('Modes:');
Writeln(' chat Start an interactive chat session (default)');
Writeln(' generate Generate text from a prompt');
Writeln(' study Study text files in a directory');
Writeln('Options:');
Writeln(' -model=FILE Model file to use');
Writeln(' -steps=N Number of steps/tokens to generate (default: 0 = until end)');
Writeln(' -context-size=N Context size in tokens (default: 4096)');
Writeln(' -tavily-key=KEY Tavily API key for web search tool');
Writeln(' -system-prompt=TEXT System prompt for chat mode (default: "You are a helpful assistant.")');
Writeln(' -prompt=TEXT Prompt for generate mode or initial prompt for chat mode');
Writeln(' -quit-after-prompt Quit after initial prompt in chat mode');
Writeln(' -tools Enable tools in chat mode (default: disabled, when enabled, tools.json is used if present)');
Writeln(' -temperature=FLOAT Sampling temperature (0.0 to 1.0, default: 0.6)');
Writeln(' -top-p=FLOAT Top-p sampling (0.0 to 1.0, default: 0.9)');
Writeln(' -seed=N Random seed (default: 0 = random)');
Writeln(' -penalty-last-n=N Penalty last N tokens (default: 0 = disabled)');
Writeln(' -penalty-repeat=FLOAT Penalty repeat factor (default: 1.0)');
Writeln(' -penalty-frequency=FLOAT Penalty frequency factor (default: 0.0)');
Writeln(' -penalty-presence=FLOAT Penalty presence factor (default: 0.0)');
Writeln(' -path=DIR File path for study mode');
Writeln(' -help / -h / -? Show this help message');
Halt(0);
end;
// Add more arguments here as needed
end;
end;
procedure TPasLLMCLIInstance.LoadToolConfiguration;
var JSONFileName:TPasLLMUTF8String;
JSONStream:TMemoryStream;
JSONContentItem,JSONItem:TPasJSONItem;
begin
JSONFileName:=IncludeTrailingPathDelimiter(ExtractFilePath(ChangeFileExt(ParamStr(0),'')))+'tools.json';
{if not FileExists(JSONFileName) then begin
JSONFileName:=GetAppDataLocalStoragePath(ChangeFileExt(ParamStr(0),''))+'tools.json';
end;}
if FileExists(JSONFileName) then begin
JSONStream:=TMemoryStream.Create;
try
JSONStream.LoadFromFile(JSONFileName);
JSONStream.Seek(0,soBeginning);
JSONContentItem:=TPasJSON.Parse(JSONStream);
if assigned(JSONContentItem) then begin
try
if JSONContentItem is TPasJSONItemObject then begin
JSONItem:=TPasJSONItemObject(JSONContentItem).Properties['tavily_key'];
if assigned(JSONItem) then begin
fTavilyKey:=TPasJSON.GetString(JSONItem,fTavilyKey);
end;
JSONItem:=TPasJSONItemObject(JSONContentItem).Properties['mcp'];
if assigned(JSONItem) then begin
fChatSession.LoadMCPServersFromJSON(JSONItem);
end;
end;
finally
FreeAndNil(JSONContentItem);
end;
end;
finally
FreeAndNil(JSONStream);
end;
end;
end;
function TPasLLMCLIInstance.DefaultOnInput(const aSender:TPasLLMModelInferenceInstance.TChatSession;const aPrompt:TPasLLMUTF8String):TPasLLMUTF8String;
begin
if length(fPrompt)>0 then begin
result:=fPrompt;
fPrompt:='';
end else if fQuitAfterPrompt then begin
result:='/quit';
end else begin
Write(aPrompt);
ReadLn(result);
end;
end;
procedure TPasLLMCLIInstance.DefaultOnSideTurn(const aSender:TPasLLMModelInferenceInstance.TChatSession;const aSide:TPasLLMUTF8String);
begin
end;
procedure TPasLLMCLIInstance.Run;
begin
fPasLLMInstance:=TPasLLM.Create(fPasMPInstance);
try
if fContextSize=0 then begin
fContextSize:=High(TPasLLMInt32);
end;
fPasLLMModel:=TPasLLMModel.Create(fPasLLMInstance,fModel,fContextSize);
try
fPasLLMModel.Configuration.PenaltyLastN:=fPenaltyLastN;
fPasLLMModel.Configuration.PenaltyRepeat:=fPenaltyRepeat;
fPasLLMModel.Configuration.PenaltyFrequency:=fPenaltyFrequency;
fPasLLMModel.Configuration.PenaltyPresence:=fPenaltyPresence;
fPasLLMModelInferenceInstance:=TPasLLMModelInferenceInstance.Create(fPasLLMModel,fSeed);
try
fPasLLMModelInferenceInstance.Temperature:=fTemperature;
fPasLLMModelInferenceInstance.TopP:=fTopP;
case fMode of
TMode.Chat:begin
fChatSession:=fPasLLMModelInferenceInstance.CreateChatSession;
try
fChatSession.OnInput:=DefaultOnInput;
fChatSession.ToolsEnabled:=fTools;
if fChatSession.ToolsEnabled then begin
LoadToolConfiguration;
fChatSession.TavilyKey:=fTavilyKey;
fChatSession.AddDefaultTools;
end;
fChatSession.State:=TPasLLMModelInferenceInstance.TChatSession.TState.UserInput;
if length(fSystemPrompt)>0 then begin
fChatSession.SetSystemPrompt(fSystemPrompt);
fChatSession.State:=TPasLLMModelInferenceInstance.TChatSession.TState.Initial;
end;
if fQuitAfterPrompt and (length(fPrompt)>0) then begin
fChatSession.OnSideTurn:=DefaultOnSideTurn;
end;
fChatSession.Run;
finally
FreeAndNil(fChatSession);
end;
end;
TMode.Generate:begin
if length(fPrompt)=0 then begin
ReadLn(fPrompt);
end;
fPrompt:=Trim(fPrompt);
if length(fPrompt)>0 then begin
fPasLLMModelInferenceInstance.Generate(fPrompt,fSteps);
end;
end;
TMode.Study:begin
fPath:=Trim(fPath);
if length(fPath)>0 then begin
fPasLLMModelInferenceInstance.Study(fPath,fSteps);
end;
end;
else begin
raise Exception.Create('Invalid mode');
end;
end;
finally
FreeAndNil(fPasLLMModelInferenceInstance);
end;
finally
FreeAndNil(fPasLLMModel);
end;
finally
FreeAndNil(fPasLLMInstance);
end;
end;
var PasLLMCLIInstance:TPasLLMCLIInstance;
begin
PasLLMCLIInstance:=TPasLLMCLIInstance.Create;
try
PasLLMCLIInstance.Run;
finally
FreeAndNil(PasLLMCLIInstance);
end;
end.

View file

@ -0,0 +1,243 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{42B8FDCE-239C-4EA4-96E8-63640B131D3F}</ProjectGuid>
<MainSource>pasllmcli.dpr</MainSource>
<Base>True</Base>
<Config Condition="'$(Config)'==''">Debug</Config>
<ProjectName Condition="'$(ProjectName)'==''">pasllmcli</ProjectName>
<TargetedPlatforms>168067</TargetedPlatforms>
<AppType>Console</AppType>
<FrameworkType>None</FrameworkType>
<ProjectVersion>20.3</ProjectVersion>
<Platform Condition="'$(Platform)'==''">Win64</Platform>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Base' or '$(Base)'!=''">
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Android' and '$(Base)'=='true') or '$(Base_Android)'!=''">
<Base_Android>true</Base_Android>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Android64' and '$(Base)'=='true') or '$(Base_Android64)'!=''">
<Base_Android64>true</Base_Android64>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='iOSDevice32' and '$(Base)'=='true') or '$(Base_iOSDevice32)'!=''">
<Base_iOSDevice32>true</Base_iOSDevice32>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='iOSDevice64' and '$(Base)'=='true') or '$(Base_iOSDevice64)'!=''">
<Base_iOSDevice64>true</Base_iOSDevice64>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='iOSSimulator' and '$(Base)'=='true') or '$(Base_iOSSimulator)'!=''">
<Base_iOSSimulator>true</Base_iOSSimulator>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Win32' and '$(Base)'=='true') or '$(Base_Win32)'!=''">
<Base_Win32>true</Base_Win32>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Win64' and '$(Base)'=='true') or '$(Base_Win64)'!=''">
<Base_Win64>true</Base_Win64>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Release' or '$(Cfg_1)'!=''">
<Cfg_1>true</Cfg_1>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Config)'=='Debug' or '$(Cfg_2)'!=''">
<Cfg_2>true</Cfg_2>
<CfgParent>Base</CfgParent>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='Android64' and '$(Cfg_2)'=='true') or '$(Cfg_2_Android64)'!=''">
<Cfg_2_Android64>true</Cfg_2_Android64>
<CfgParent>Cfg_2</CfgParent>
<Cfg_2>true</Cfg_2>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='OSX64' and '$(Cfg_2)'=='true') or '$(Cfg_2_OSX64)'!=''">
<Cfg_2_OSX64>true</Cfg_2_OSX64>
<CfgParent>Cfg_2</CfgParent>
<Cfg_2>true</Cfg_2>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="('$(Platform)'=='OSXARM64' and '$(Cfg_2)'=='true') or '$(Cfg_2_OSXARM64)'!=''">
<Cfg_2_OSXARM64>true</Cfg_2_OSXARM64>
<CfgParent>Cfg_2</CfgParent>
<Cfg_2>true</Cfg_2>
<Base>true</Base>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
<DCC_E>false</DCC_E>
<DCC_F>false</DCC_F>
<DCC_K>false</DCC_K>
<DCC_N>false</DCC_N>
<DCC_S>false</DCC_S>
<DCC_ImageBase>00400000</DCC_ImageBase>
<SanitizedProjectName>pasllmcli</SanitizedProjectName>
<VerInfo_Locale>1031</VerInfo_Locale>
<VerInfo_Keys>CompanyName=;FileDescription=;FileVersion=1.0.0.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProductName=;ProductVersion=1.0.0.0;Comments=;CFBundleName=</VerInfo_Keys>
<DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;$(DCC_Namespace)</DCC_Namespace>
<Icon_MainIcon>$(BDS)\bin\delphi_PROJECTICON.ico</Icon_MainIcon>
<Icns_MainIcns>$(BDS)\bin\delphi_PROJECTICNS.icns</Icns_MainIcns>
<DCC_UnitSearchPath>..;..\synapse;..\..\externals\pinja\src;..\..\externals\pasdblstrutils\src;..\..\externals\pasjson\src;..\..\externals\pasmp\src;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<DCC_ExeOutput>..\..\bin</DCC_ExeOutput>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_Android)'!=''">
<VerInfo_Keys>package=com.embarcadero.$(MSBuildProjectName);label=$(MSBuildProjectName);versionCode=1;versionName=1.0.0;persistent=False;restoreAnyVersion=False;installLocation=auto;largeHeap=False;theme=TitleBar;hardwareAccelerated=true;apiKey=;minSdkVersion=23;targetSdkVersion=35</VerInfo_Keys>
<BT_BuildType>Debug</BT_BuildType>
<Android_LauncherIcon36>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_36x36.png</Android_LauncherIcon36>
<Android_LauncherIcon48>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_48x48.png</Android_LauncherIcon48>
<Android_LauncherIcon72>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_72x72.png</Android_LauncherIcon72>
<Android_LauncherIcon96>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_96x96.png</Android_LauncherIcon96>
<Android_LauncherIcon144>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_144x144.png</Android_LauncherIcon144>
<Android_SplashImage426>$(BDS)\bin\Artwork\Android\FM_SplashImage_426x320.png</Android_SplashImage426>
<Android_SplashImage470>$(BDS)\bin\Artwork\Android\FM_SplashImage_470x320.png</Android_SplashImage470>
<Android_SplashImage640>$(BDS)\bin\Artwork\Android\FM_SplashImage_640x480.png</Android_SplashImage640>
<Android_SplashImage960>$(BDS)\bin\Artwork\Android\FM_SplashImage_960x720.png</Android_SplashImage960>
<AUP_ACCESS_COARSE_LOCATION>true</AUP_ACCESS_COARSE_LOCATION>
<AUP_ACCESS_FINE_LOCATION>true</AUP_ACCESS_FINE_LOCATION>
<AUP_CALL_PHONE>true</AUP_CALL_PHONE>
<AUP_CAMERA>true</AUP_CAMERA>
<AUP_INTERNET>true</AUP_INTERNET>
<AUP_READ_CALENDAR>true</AUP_READ_CALENDAR>
<AUP_READ_EXTERNAL_STORAGE>true</AUP_READ_EXTERNAL_STORAGE>
<AUP_WRITE_CALENDAR>true</AUP_WRITE_CALENDAR>
<AUP_WRITE_EXTERNAL_STORAGE>true</AUP_WRITE_EXTERNAL_STORAGE>
<AUP_READ_PHONE_STATE>true</AUP_READ_PHONE_STATE>
<Android_NotificationIcon24>$(BDS)\bin\Artwork\Android\FM_NotificationIcon_24x24.png</Android_NotificationIcon24>
<Android_NotificationIcon36>$(BDS)\bin\Artwork\Android\FM_NotificationIcon_36x36.png</Android_NotificationIcon36>
<Android_NotificationIcon48>$(BDS)\bin\Artwork\Android\FM_NotificationIcon_48x48.png</Android_NotificationIcon48>
<Android_NotificationIcon72>$(BDS)\bin\Artwork\Android\FM_NotificationIcon_72x72.png</Android_NotificationIcon72>
<Android_NotificationIcon96>$(BDS)\bin\Artwork\Android\FM_NotificationIcon_96x96.png</Android_NotificationIcon96>
<Android_LauncherIcon192>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_192x192.png</Android_LauncherIcon192>
<EnabledSysJars>activity-1.7.2.dex.jar;annotation-experimental-1.4.1.dex.jar;annotation-jvm-1.8.1.dex.jar;annotations-13.0.dex.jar;appcompat-1.2.0.dex.jar;appcompat-resources-1.2.0.dex.jar;billing-7.1.1.dex.jar;biometric-1.1.0.dex.jar;browser-1.4.0.dex.jar;cloud-messaging.dex.jar;collection-jvm-1.4.2.dex.jar;concurrent-futures-1.1.0.dex.jar;core-1.15.0.dex.jar;core-common-2.2.0.dex.jar;core-ktx-1.15.0.dex.jar;core-runtime-2.2.0.dex.jar;cursoradapter-1.0.0.dex.jar;customview-1.0.0.dex.jar;documentfile-1.0.0.dex.jar;drawerlayout-1.0.0.dex.jar;error_prone_annotations-2.9.0.dex.jar;exifinterface-1.3.6.dex.jar;firebase-annotations-16.2.0.dex.jar;firebase-common-20.3.1.dex.jar;firebase-components-17.1.0.dex.jar;firebase-datatransport-18.1.7.dex.jar;firebase-encoders-17.0.0.dex.jar;firebase-encoders-json-18.0.0.dex.jar;firebase-encoders-proto-16.0.0.dex.jar;firebase-iid-interop-17.1.0.dex.jar;firebase-installations-17.1.3.dex.jar;firebase-installations-interop-17.1.0.dex.jar;firebase-measurement-connector-19.0.0.dex.jar;firebase-messaging-23.1.2.dex.jar;fmx.dex.jar;fragment-1.2.5.dex.jar;google-play-licensing.dex.jar;interpolator-1.0.0.dex.jar;javax.inject-1.dex.jar;kotlin-stdlib-1.8.22.dex.jar;kotlin-stdlib-common-1.8.22.dex.jar;kotlin-stdlib-jdk7-1.8.22.dex.jar;kotlin-stdlib-jdk8-1.8.22.dex.jar;kotlinx-coroutines-android-1.6.4.dex.jar;kotlinx-coroutines-core-jvm-1.6.4.dex.jar;legacy-support-core-utils-1.0.0.dex.jar;lifecycle-common-2.6.2.dex.jar;lifecycle-livedata-2.6.2.dex.jar;lifecycle-livedata-core-2.6.2.dex.jar;lifecycle-runtime-2.6.2.dex.jar;lifecycle-service-2.6.2.dex.jar;lifecycle-viewmodel-2.6.2.dex.jar;lifecycle-viewmodel-savedstate-2.6.2.dex.jar;listenablefuture-1.0.dex.jar;loader-1.0.0.dex.jar;localbroadcastmanager-1.0.0.dex.jar;okio-jvm-3.4.0.dex.jar;play-services-ads-22.2.0.dex.jar;play-services-ads-base-22.2.0.dex.jar;play-services-ads-identifier-18.0.0.dex.jar;play-services-ads-lite-22.2.0.dex.jar;play-services-appset-16.0.1.dex.jar;play-services-base-18.5.0.dex.jar;play-services-basement-18.4.0.dex.jar;play-services-cloud-messaging-17.0.1.dex.jar;play-services-location-21.0.1.dex.jar;play-services-maps-18.1.0.dex.jar;play-services-measurement-base-20.1.2.dex.jar;play-services-measurement-sdk-api-20.1.2.dex.jar;play-services-stats-17.0.2.dex.jar;play-services-tasks-18.2.0.dex.jar;print-1.0.0.dex.jar;profileinstaller-1.3.0.dex.jar;room-common-2.2.5.dex.jar;room-runtime-2.2.5.dex.jar;savedstate-1.2.1.dex.jar;sqlite-2.1.0.dex.jar;sqlite-framework-2.1.0.dex.jar;startup-runtime-1.1.1.dex.jar;tracing-1.2.0.dex.jar;transport-api-3.0.0.dex.jar;transport-backend-cct-3.1.8.dex.jar;transport-runtime-3.1.8.dex.jar;user-messaging-platform-2.0.0.dex.jar;vectordrawable-1.1.0.dex.jar;vectordrawable-animated-1.1.0.dex.jar;versionedparcelable-1.1.1.dex.jar;viewpager-1.0.0.dex.jar;work-runtime-2.7.0.dex.jar</EnabledSysJars>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_Android64)'!=''">
<Android_LauncherIcon192>$(BDS)\bin\Artwork\Android\FM_LauncherIcon_192x192.png</Android_LauncherIcon192>
<EnabledSysJars>activity-1.7.2.dex.jar;annotation-experimental-1.4.1.dex.jar;annotation-jvm-1.8.1.dex.jar;annotations-13.0.dex.jar;appcompat-1.2.0.dex.jar;appcompat-resources-1.2.0.dex.jar;billing-7.1.1.dex.jar;biometric-1.1.0.dex.jar;browser-1.4.0.dex.jar;cloud-messaging.dex.jar;collection-jvm-1.4.2.dex.jar;concurrent-futures-1.1.0.dex.jar;core-1.15.0.dex.jar;core-common-2.2.0.dex.jar;core-ktx-1.15.0.dex.jar;core-runtime-2.2.0.dex.jar;cursoradapter-1.0.0.dex.jar;customview-1.0.0.dex.jar;documentfile-1.0.0.dex.jar;drawerlayout-1.0.0.dex.jar;error_prone_annotations-2.9.0.dex.jar;exifinterface-1.3.6.dex.jar;firebase-annotations-16.2.0.dex.jar;firebase-common-20.3.1.dex.jar;firebase-components-17.1.0.dex.jar;firebase-datatransport-18.1.7.dex.jar;firebase-encoders-17.0.0.dex.jar;firebase-encoders-json-18.0.0.dex.jar;firebase-encoders-proto-16.0.0.dex.jar;firebase-iid-interop-17.1.0.dex.jar;firebase-installations-17.1.3.dex.jar;firebase-installations-interop-17.1.0.dex.jar;firebase-measurement-connector-19.0.0.dex.jar;firebase-messaging-23.1.2.dex.jar;fmx.dex.jar;fragment-1.2.5.dex.jar;google-play-licensing.dex.jar;interpolator-1.0.0.dex.jar;javax.inject-1.dex.jar;kotlin-stdlib-1.8.22.dex.jar;kotlin-stdlib-common-1.8.22.dex.jar;kotlin-stdlib-jdk7-1.8.22.dex.jar;kotlin-stdlib-jdk8-1.8.22.dex.jar;kotlinx-coroutines-android-1.6.4.dex.jar;kotlinx-coroutines-core-jvm-1.6.4.dex.jar;legacy-support-core-utils-1.0.0.dex.jar;lifecycle-common-2.6.2.dex.jar;lifecycle-livedata-2.6.2.dex.jar;lifecycle-livedata-core-2.6.2.dex.jar;lifecycle-runtime-2.6.2.dex.jar;lifecycle-service-2.6.2.dex.jar;lifecycle-viewmodel-2.6.2.dex.jar;lifecycle-viewmodel-savedstate-2.6.2.dex.jar;listenablefuture-1.0.dex.jar;loader-1.0.0.dex.jar;localbroadcastmanager-1.0.0.dex.jar;okio-jvm-3.4.0.dex.jar;play-services-ads-22.2.0.dex.jar;play-services-ads-base-22.2.0.dex.jar;play-services-ads-identifier-18.0.0.dex.jar;play-services-ads-lite-22.2.0.dex.jar;play-services-appset-16.0.1.dex.jar;play-services-base-18.5.0.dex.jar;play-services-basement-18.4.0.dex.jar;play-services-cloud-messaging-17.0.1.dex.jar;play-services-location-21.0.1.dex.jar;play-services-maps-18.1.0.dex.jar;play-services-measurement-base-20.1.2.dex.jar;play-services-measurement-sdk-api-20.1.2.dex.jar;play-services-stats-17.0.2.dex.jar;play-services-tasks-18.2.0.dex.jar;print-1.0.0.dex.jar;profileinstaller-1.3.0.dex.jar;room-common-2.2.5.dex.jar;room-runtime-2.2.5.dex.jar;savedstate-1.2.1.dex.jar;sqlite-2.1.0.dex.jar;sqlite-framework-2.1.0.dex.jar;startup-runtime-1.1.1.dex.jar;tracing-1.2.0.dex.jar;transport-api-3.0.0.dex.jar;transport-backend-cct-3.1.8.dex.jar;transport-runtime-3.1.8.dex.jar;user-messaging-platform-2.0.0.dex.jar;vectordrawable-1.1.0.dex.jar;vectordrawable-animated-1.1.0.dex.jar;versionedparcelable-1.1.1.dex.jar;viewpager-1.0.0.dex.jar;work-runtime-2.7.0.dex.jar</EnabledSysJars>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_iOSDevice32)'!=''">
<iPhone_AppIcon120>$(BDS)\bin\Artwork\iOS\iPhone\FM_ApplicationIcon_120x120.png</iPhone_AppIcon120>
<iPhone_Spotlight80>$(BDS)\bin\Artwork\iOS\iPhone\FM_SpotlightSearchIcon_80x80.png</iPhone_Spotlight80>
<iPhone_Notification40>$(BDS)\bin\Artwork\iOS\iPhone\FM_NotificationIcon_40x40.png</iPhone_Notification40>
<iPhone_Notification60>$(BDS)\bin\Artwork\iOS\iPhone\FM_NotificationIcon_60x60.png</iPhone_Notification60>
<iPad_SpotLight80>$(BDS)\bin\Artwork\iOS\iPad\FM_SpotlightSearchIcon_80x80.png</iPad_SpotLight80>
<iPad_Notification40>$(BDS)\bin\Artwork\iOS\iPad\FM_NotificationIcon_40x40.png</iPad_Notification40>
<iPad_AppIcon152>$(BDS)\bin\Artwork\iOS\iPad\FM_ApplicationIcon_152x152.png</iPad_AppIcon152>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_iOSDevice64)'!=''">
<iPhone_AppIcon120>$(BDS)\bin\Artwork\iOS\iPhone\FM_ApplicationIcon_120x120.png</iPhone_AppIcon120>
<iPhone_Spotlight80>$(BDS)\bin\Artwork\iOS\iPhone\FM_SpotlightSearchIcon_80x80.png</iPhone_Spotlight80>
<iPhone_Notification40>$(BDS)\bin\Artwork\iOS\iPhone\FM_NotificationIcon_40x40.png</iPhone_Notification40>
<iPhone_Notification60>$(BDS)\bin\Artwork\iOS\iPhone\FM_NotificationIcon_60x60.png</iPhone_Notification60>
<iPad_SpotLight80>$(BDS)\bin\Artwork\iOS\iPad\FM_SpotlightSearchIcon_80x80.png</iPad_SpotLight80>
<iPad_Notification40>$(BDS)\bin\Artwork\iOS\iPad\FM_NotificationIcon_40x40.png</iPad_Notification40>
<iPad_AppIcon152>$(BDS)\bin\Artwork\iOS\iPad\FM_ApplicationIcon_152x152.png</iPad_AppIcon152>
<iOS_AppStore1024>$(BDS)\bin\Artwork\iOS\iPhone\FM_ApplicationIcon_1024x1024.png</iOS_AppStore1024>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_iOSSimulator)'!=''">
<iPhone_AppIcon120>$(BDS)\bin\Artwork\iOS\iPhone\FM_ApplicationIcon_120x120.png</iPhone_AppIcon120>
<iPhone_Spotlight80>$(BDS)\bin\Artwork\iOS\iPhone\FM_SpotlightSearchIcon_80x80.png</iPhone_Spotlight80>
<iPhone_Notification40>$(BDS)\bin\Artwork\iOS\iPhone\FM_NotificationIcon_40x40.png</iPhone_Notification40>
<iPhone_Notification60>$(BDS)\bin\Artwork\iOS\iPhone\FM_NotificationIcon_60x60.png</iPhone_Notification60>
<iPad_SpotLight80>$(BDS)\bin\Artwork\iOS\iPad\FM_SpotlightSearchIcon_80x80.png</iPad_SpotLight80>
<iPad_Notification40>$(BDS)\bin\Artwork\iOS\iPad\FM_NotificationIcon_40x40.png</iPad_Notification40>
<iPad_AppIcon152>$(BDS)\bin\Artwork\iOS\iPad\FM_ApplicationIcon_152x152.png</iPad_AppIcon152>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_Win32)'!=''">
<DCC_Namespace>Winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;Bde;$(DCC_Namespace)</DCC_Namespace>
<BT_BuildType>Debug</BT_BuildType>
<VerInfo_Keys>CompanyName=;FileDescription=$(MSBuildProjectName);FileVersion=1.0.0.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=1.0.0.0;Comments=</VerInfo_Keys>
<VerInfo_Locale>1033</VerInfo_Locale>
<Manifest_File>(None)</Manifest_File>
<AppDPIAwarenessMode>none</AppDPIAwarenessMode>
</PropertyGroup>
<PropertyGroup Condition="'$(Base_Win64)'!=''">
<DCC_Namespace>Winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;$(DCC_Namespace)</DCC_Namespace>
<BT_BuildType>Debug</BT_BuildType>
<VerInfo_Keys>CompanyName=;FileDescription=$(MSBuildProjectName);FileVersion=1.0.0.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=1.0.0.0;Comments=</VerInfo_Keys>
<VerInfo_Locale>1033</VerInfo_Locale>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
<DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
<DCC_DebugInformation>0</DCC_DebugInformation>
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
<DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_Define>DEBUG;$(DCC_Define)</DCC_Define>
<DCC_Optimize>false</DCC_Optimize>
<DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
<DCC_RangeChecking>true</DCC_RangeChecking>
<DCC_IntegerOverflowCheck>true</DCC_IntegerOverflowCheck>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2_Android64)'!=''">
<BT_BuildType>Debug</BT_BuildType>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2_OSX64)'!=''">
<BT_BuildType>Debug</BT_BuildType>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2_OSXARM64)'!=''">
<BT_BuildType>Debug</BT_BuildType>
</PropertyGroup>
<ItemGroup>
<DelphiCompile Include="$(MainSource)">
<MainSource>MainSource</MainSource>
</DelphiCompile>
<BuildConfiguration Include="Base">
<Key>Base</Key>
</BuildConfiguration>
<BuildConfiguration Include="Release">
<Key>Cfg_1</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
<BuildConfiguration Include="Debug">
<Key>Cfg_2</Key>
<CfgParent>Base</CfgParent>
</BuildConfiguration>
</ItemGroup>
<ProjectExtensions>
<Borland.Personality>Delphi.Personality.12</Borland.Personality>
<Borland.ProjectType/>
<BorlandProject>
<Delphi.Personality>
<Source>
<Source Name="MainSource">pasllmcli.dpr</Source>
</Source>
<Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcboffice2k290.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcbofficexp290.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dcloffice2k290.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dclofficexp290.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages>
</Excluded_Packages>
</Delphi.Personality>
<Platforms>
<Platform value="Android">False</Platform>
<Platform value="Android64">True</Platform>
<Platform value="iOSDevice32">False</Platform>
<Platform value="iOSDevice64">False</Platform>
<Platform value="iOSSimulator">False</Platform>
<Platform value="Linux64">True</Platform>
<Platform value="OSX32">False</Platform>
<Platform value="OSX64">True</Platform>
<Platform value="OSXARM64">True</Platform>
<Platform value="Win32">True</Platform>
<Platform value="Win64">True</Platform>
</Platforms>
</BorlandProject>
<ProjectFileVersion>12</ProjectFileVersion>
</ProjectExtensions>
<Import Project="$(BDS)\Bin\CodeGear.Delphi.Targets" Condition="Exists('$(BDS)\Bin\CodeGear.Delphi.Targets')"/>
<Import Project="$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj" Condition="Exists('$(APPDATA)\Embarcadero\$(BDSAPPDATABASEDIR)\$(PRODUCTVERSION)\UserTools.proj')"/>
</Project>

View file

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectOptions>
<Version Value="12"/>
<General>
<Flags>
<MainUnitHasCreateFormStatements Value="False"/>
<MainUnitHasTitleStatement Value="False"/>
<MainUnitHasScaledStatement Value="False"/>
</Flags>
<SessionStorage Value="InProjectDir"/>
<Title Value="pasllmcli"/>
<UseAppBundle Value="False"/>
<ResourceType Value="res"/>
</General>
<BuildModes>
<Item Name="Default" Default="True"/>
</BuildModes>
<PublishOptions>
<Version Value="2"/>
<UseFileFilters Value="True"/>
</PublishOptions>
<RunParams>
<FormatVersion Value="2"/>
</RunParams>
<Units>
<Unit>
<Filename Value="pasllmcli.dpr"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="../../externals/pinja/src/PinjaChatTemplate.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="../PasLLM.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="../../externals/pinja/src/Pinja.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="../../externals/pasdblstrutils/src/PasDblStrUtils.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="../../externals/pasjson/src/PasJSON.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
<Unit>
<Filename Value="../../externals/pasmp/src/PasMP.pas"/>
<IsPartOfProject Value="True"/>
</Unit>
</Units>
</ProjectOptions>
<CompilerOptions>
<Version Value="11"/>
<Target>
<Filename Value="../../bin/pasllmcli"/>
</Target>
<SearchPaths>
<IncludeFiles Value="$(ProjOutDir)"/>
<OtherUnitFiles Value="..;../synapse;../../externals/pinja/src;../../externals/pasdblstrutils/src;../../externals/pasjson/src;../../externals/pasmp/src"/>
<UnitOutputDirectory Value="lib/$(TargetCPU)-$(TargetOS)"/>
</SearchPaths>
<Linking>
<Debugging>
<DebugInfoType Value="dsDwarf3"/>
</Debugging>
</Linking>
</CompilerOptions>
<Debugging>
<Exceptions>
<Item>
<Name Value="EAbort"/>
</Item>
<Item>
<Name Value="ECodetoolError"/>
</Item>
<Item>
<Name Value="EFOpenError"/>
</Item>
</Exceptions>
</Debugging>
</CONFIG>

3124
src/reference/PasLLM.c Normal file

File diff suppressed because it is too large Load diff

675
src/synapse/Crypt32.pas Normal file
View file

@ -0,0 +1,675 @@
{==============================================================================|
| Project : Ararat Synapse | 001.000.000 |
|==============================================================================|
| Content: minimal support for crypt32 windows API |
|==============================================================================|
| Copyright (c)2018, Pepak |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Pepak (Czech Republic). |
| Portions created by Pepak are Copyright (c)2018. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
unit Crypt32;
// Pozor, tohle je naprosto minimalni mnozina toho, co Crypt32.dll nabizi.
// Prevedl jsem jen to, co jsem potreboval.
interface
uses
Windows;
const
AdvapiLib = 'advapi32.dll';
CryptoLib = 'crypt32.dll';
CryptDlgLib = 'cryptdlg.dll';
type
HCERTSTORE = THandle;
HCRYPTPROV = THandle;
HCRYPTKEY = THandle;
PCRYPT_DATA_BLOB = ^CRYPT_DATA_BLOB;
CRYPT_DATA_BLOB = record
cbData: DWORD;
pbData: PByte;
end;
const
CRYPT_EXPORTABLE = $00000001;
CRYPT_USER_PROTECTED = $00000002;
CRYPT_MACHINE_KEYSET = $00000020;
CRYPT_USER_KEYSET = $00001000;
const
PKCS12_PREFER_CNG_KSP = $00000100;
PKCS12_ALWAYS_CNG_KSP = $00000200;
PKCS12_ALLOW_OVERWRITE_KEY = $00004000;
PKCS12_NO_PERSIST_KEY = $00008000;
PKCS12_INCLUDE_EXTENDED_PROPERTIES = $0010;
type
CRYPT_ALGORITHM_IDENTIFIER = record
pszObjId: PAnsiChar;
Parameters: CRYPT_DATA_BLOB;
end;
CERT_PUBLIC_KEY_INFO = record
Algorithm: CRYPT_ALGORITHM_IDENTIFIER;
PublicKey: CRYPT_DATA_BLOB;
end;
PCERT_EXTENSION = ^CERT_EXTENSION;
CERT_EXTENSION = record
pszObjId: PAnsiChar;
bCritical: BOOL;
Value: CRYPT_DATA_BLOB;
end;
PCERT_INFO = ^CERT_INFO;
CERT_INFO = record
dwVersion: DWORD;
SerialNumber: CRYPT_DATA_BLOB;
SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER;
Issuer: CRYPT_DATA_BLOB;
NotBefore: FILETIME;
NotAfter: FILETIME;
Subject: CRYPT_DATA_BLOB;
SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO;
IssuerUniqueId: CRYPT_DATA_BLOB;
SubjectUniqueId: CRYPT_DATA_BLOB;
cExtension: DWORD;
rgExtension: PCERT_EXTENSION;
end;
PPCCERT_CONTEXT = ^PCCERT_CONTEXT;
PCCERT_CONTEXT = ^CERT_CONTEXT;
CERT_CONTEXT = record
dwCertEncodingType: DWORD;
pbCertEncoded: PByte;
cbCertEncoded: DWORD;
pCertInfo: PCERT_INFO;
hCertStore: HCERTSTORE;
end;
PCRYPT_KEY_PROV_PARAM = ^CRYPT_KEY_PROV_PARAM;
CRYPT_KEY_PROV_PARAM = record
dwParam: DWORD;
pbData: PByte;
cbData: DWORD;
dwFlags: DWORD;
end;
PCRYPT_KEY_PROV_INFO = ^CRYPT_KEY_PROV_INFO;
CRYPT_KEY_PROV_INFO = record
pwszContainerName: PWideChar;
pwszProvName: PWideChar;
dwProvType: DWORD;
dwFlags: DWORD;
cProvParam: DWORD;
rgProvParam: PCRYPT_KEY_PROV_PARAM;
dwKeySpec: DWORD;
__dummy: array[0..65535] of byte;
end;
PCRYPT_HASH_BLOB = ^CRYPT_HASH_BLOB;
CRYPT_HASH_BLOB = record
cbData: DWORD;
pbData: Pointer;
end;
PCRL_ENTRY = ^CRL_ENTRY;
CRL_ENTRY = record
SerialNumber: CRYPT_DATA_BLOB;
RevocationDate: FILETIME;
cExtension: DWORD;
rgExtension: PCERT_EXTENSION;
end;
PCRL_INFO = ^CRL_INFO;
CRL_INFO = record
dwVersion: DWORD;
SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER;
Issuer: CRYPT_DATA_BLOB;
ThisUpdate: FILETIME;
NextUpdate: FILETIME;
cCRLEntry: DWORD;
rgCRLEntry: PCRL_ENTRY;
cExtension: DWORD;
rgExtension: PCERT_EXTENSION;
end;
PCCRL_CONTEXT = ^CRL_CONTEXT;
CRL_CONTEXT = record
dwCertEncodingType: DWORD;
pbCrlEncoded: Pointer;
cbCrlEncoded: DWORD;
pCrlInfo: PCRL_INFO;
hCertStore: HCERTSTORE;
end;
PCRYPT_ATTRIBUTE = ^CRYPT_ATTRIBUTE;
CRYPT_ATTRIBUTE = record
pszObjId: LPSTR;
cValue: DWORD;
rgValue: PCRYPT_DATA_BLOB;
end;
PCRYPT_SIGN_MESSAGE_PARA = ^CRYPT_SIGN_MESSAGE_PARA;
CRYPT_SIGN_MESSAGE_PARA = record
cbSize: DWORD;
dwMsgEncodingType: DWORD;
pSigningCert: PCCERT_CONTEXT;
HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER;
pvHashAuxInfo: Pointer;
cMsgCert: DWORD;
rgpMsgCert: PCCERT_CONTEXT;
cMsgCrl: DWORD;
rgpMsgCrl: PCCRL_CONTEXT;
cAuthAttr: DWORD;
rgAuthAttr: PCRYPT_ATTRIBUTE;
cUnauthAttr: DWORD;
rgUnauthAttr: PCRYPT_ATTRIBUTE;
dwFlags: DWORD;
dwInnerContentType: DWORD;
HashEncryptionAlgorithm: CRYPT_ALGORITHM_IDENTIFIER;
pvHashEncryptionAuxInfo: Pointer;
end;
PPtrArray = ^TPtrArray;
TPtrArray = array[0..32767] of Pointer;
PDWORDArray = ^TDWORDArray;
TDWORDArray = array[0..32767] of DWORD;
const
CERT_STORE_PROV_MSG = LPCSTR(1);
CERT_STORE_PROV_MEMORY = LPCSTR(2);
CERT_STORE_PROV_FILE = LPCSTR(3);
CERT_STORE_PROV_REG = LPCSTR(4);
CERT_STORE_PROV_PKCS7 = LPCSTR(5);
CERT_STORE_PROV_SERIALIZED = LPCSTR(6);
CERT_STORE_PROV_FILENAME_A = LPCSTR(7);
CERT_STORE_PROV_FILENAME_W = LPCSTR(8);
CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W;
CERT_STORE_PROV_SYSTEM_A = LPCSTR(9);
CERT_STORE_PROV_SYSTEM_W = LPCSTR(10);
CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W;
CERT_STORE_PROV_COLLECTION = LPCSTR(11);
CERT_STORE_PROV_SYSTEM_REGISTRY_A = LPCSTR(12);
CERT_STORE_PROV_SYSTEM_REGISTRY_W = LPCSTR(13);
CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W;
CERT_STORE_PROV_PHYSICAL_W = LPCSTR(14);
CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W;
CERT_STORE_PROV_SMART_CARD_W = LPCSTR(15);
CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W;
CERT_STORE_PROV_LDAP_W = LPCSTR(16);
CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W;
sz_CERT_STORE_PROV_MEMORY = 'Memory';
sz_CERT_STORE_PROV_FILENAME_W = 'File';
sz_CERT_STORE_PROV_FILENAME = sz_CERT_STORE_PROV_FILENAME_W;
sz_CERT_STORE_PROV_SYSTEM_W = 'System';
sz_CERT_STORE_PROV_SYSTEM = sz_CERT_STORE_PROV_SYSTEM_W;
sz_CERT_STORE_PROV_PKCS7 = 'PKCS7';
sz_CERT_STORE_PROV_SERIALIZED = 'Serialized';
sz_CERT_STORE_PROV_COLLECTION = 'Collection';
sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W = 'SystemRegistry';
sz_CERT_STORE_PROV_SYSTEM_REGISTRY = sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W;
sz_CERT_STORE_PROV_PHYSICAL_W = 'Physical';
sz_CERT_STORE_PROV_PHYSICAL = sz_CERT_STORE_PROV_PHYSICAL_W;
sz_CERT_STORE_PROV_SMART_CARD_W = 'SmartCard';
sz_CERT_STORE_PROV_SMART_CARD = sz_CERT_STORE_PROV_SMART_CARD_W;
sz_CERT_STORE_PROV_LDAP_W = 'Ldap';
sz_CERT_STORE_PROV_LDAP = sz_CERT_STORE_PROV_LDAP_W;
const
X509_ASN_ENCODING = 1;
PKCS_7_ASN_ENCODING = 65536;
const
CERT_SYSTEM_STORE_UNPROTECTED_FLAG = $40000000;
CERT_SYSTEM_STORE_LOCATION_MASK = $ff0000;
CERT_SYSTEM_STORE_LOCATION_SHIFT = 16;
CERT_SYSTEM_STORE_CURRENT_USER_ID = 1;
CERT_SYSTEM_STORE_LOCAL_MACHINE_ID = 2;
CERT_SYSTEM_STORE_CURRENT_SERVICE_ID = 4;
CERT_SYSTEM_STORE_SERVICES_ID = 5;
CERT_SYSTEM_STORE_USERS_ID = 6;
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID = 7;
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID = 8;
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID = 9;
CERT_SYSTEM_STORE_CURRENT_USER = (CERT_SYSTEM_STORE_CURRENT_USER_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_LOCAL_MACHINE = (CERT_SYSTEM_STORE_LOCAL_MACHINE_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_CURRENT_SERVICE = (CERT_SYSTEM_STORE_CURRENT_SERVICE_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_SERVICES = (CERT_SYSTEM_STORE_SERVICES_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_USERS = (CERT_SYSTEM_STORE_USERS_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = (CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = (CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = (CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID shl CERT_SYSTEM_STORE_LOCATION_SHIFT);
CERT_STORE_READONLY_FLAG = $8000;
const
CERT_FIND_ANY = 0;
CERT_FIND_CERT_ID = 1048576;
CERT_FIND_CTL_USAGE = 655360;
CERT_FIND_ENHKEY_USAGE = 655360;
CERT_FIND_EXISTING = 851968;
CERT_FIND_HASH = 65536;
CERT_FIND_ISSUER_ATTR = 196612;
CERT_FIND_ISSUER_NAME = 131076;
CERT_FIND_ISSUER_OF = 786432;
CERT_FIND_KEY_IDENTIFIER = 983040;
CERT_FIND_KEY_SPEC = 589824;
CERT_FIND_MD5_HASH = 262144;
CERT_FIND_PROPERTY = 327680;
CERT_FIND_PUBLIC_KEY = 393216;
CERT_FIND_SHA1_HASH = 65536;
CERT_FIND_SIGNATURE_HASH = 917504;
CERT_FIND_SUBJECT_ATTR = 196615;
CERT_FIND_SUBJECT_CERT = 720896;
CERT_FIND_SUBJECT_NAME = 131079;
CERT_FIND_SUBJECT_STR_A = 458759;
CERT_FIND_SUBJECT_STR_W = 524295;
CERT_FIND_ISSUER_STR_A = 458756;
CERT_FIND_ISSUER_STR_W = 524292;
CERT_FIND_OR_ENHKEY_USAGE_FLAG = 16;
CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG = 1;
CERT_FIND_NO_ENHKEY_USAGE_FLAG = 8;
CERT_FIND_VALID_ENHKEY_USAGE_FLAG = 32;
CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG = 2;
const
CERT_NAME_EMAIL_TYPE = 1;
CERT_NAME_RDN_TYPE = 2;
CERT_NAME_ATTR_TYPE = 3;
CERT_NAME_SIMPLE_DISPLAY_TYPE = 4;
CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5;
CERT_NAME_DNS_TYPE = 6;
CERT_NAME_URL_TYPE = 7;
CERT_NAME_UPN_TYPE = 8;
const
CERT_NAME_ISSUER_FLAG = 1;
const
CERT_KEY_PROV_HANDLE_PROP_ID = 1;
CERT_KEY_PROV_INFO_PROP_ID = 2;
CERT_SHA1_HASH_PROP_ID = 3;
CERT_MD5_HASH_PROP_ID = 4;
CERT_HASH_PROP_ID = CERT_SHA1_HASH_PROP_ID;
CERT_KEY_CONTEXT_PROP_ID = 5;
CERT_KEY_SPEC_PROP_ID = 6;
CERT_IE30_RESERVED_PROP_ID = 7;
CERT_PUBKEY_HASH_RESERVED_PROP_ID = 8;
CERT_ENHKEY_USAGE_PROP_ID = 9;
CERT_CTL_USAGE_PROP_ID = CERT_ENHKEY_USAGE_PROP_ID;
CERT_NEXT_UPDATE_LOCATION_PROP_ID = 10;
CERT_FRIENDLY_NAME_PROP_ID = 11;
CERT_PVK_FILE_PROP_ID = 12;
CERT_DESCRIPTION_PROP_ID = 13;
CERT_ACCESS_STATE_PROP_ID = 14;
CERT_SIGNATURE_HASH_PROP_ID = 15;
CERT_SMART_CARD_DATA_PROP_ID = 16;
CERT_EFS_PROP_ID = 17;
CERT_FORTEZZA_DATA_PROP_ID = 18;
CERT_ARCHIVED_PROP_ID = 19;
CERT_KEY_IDENTIFIER_PROP_ID = 20;
CERT_AUTO_ENROLL_PROP_ID = 21;
CERT_PUBKEY_ALG_PARA_PROP_ID = 22;
CERT_CROSS_CERT_DIST_POINTS_PROP_ID = 23;
CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID = 24;
CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID = 25;
CERT_ENROLLMENT_PROP_ID = 26;
CERT_DATE_STAMP_PROP_ID = 27;
CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID = 28;
CERT_SUBJECT_NAME_MD5_HASH_PROP_ID = 29;
CERT_EXTENDED_ERROR_INFO_PROP_ID = 30;
CERT_RENEWAL_PROP_ID = 64;
CERT_ARCHIVED_KEY_HASH_PROP_ID = 65;
CERT_AUTO_ENROLL_RETRY_PROP_ID = 66;
CERT_AIA_URL_RETRIEVED_PROP_ID = 67;
CERT_AUTHORITY_INFO_ACCESS_PROP_ID = 68;
CERT_BACKED_UP_PROP_ID = 69;
CERT_OCSP_RESPONSE_PROP_ID = 70;
CERT_REQUEST_ORIGINATOR_PROP_ID = 71;
CERT_SOURCE_LOCATION_PROP_ID = 72;
CERT_SOURCE_URL_PROP_ID = 73;
CERT_NEW_KEY_PROP_ID = 74;
CERT_OCSP_CACHE_PREFIX_PROP_ID = 75;
CERT_SMART_CARD_ROOT_INFO_PROP_ID = 76;
CERT_NO_AUTO_EXPIRE_CHECK_PROP_ID = 77;
CERT_NCRYPT_KEY_HANDLE_PROP_ID = 78;
CERT_HCRYPTPROV_OR_NCRYPT_KEY_HANDLE_PROP_ID = 79;
CERT_SUBJECT_INFO_ACCESS_PROP_ID = 80;
CERT_CA_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID = 81;
CERT_CA_DISABLE_CRL_PROP_ID = 82;
CERT_ROOT_PROGRAM_CERT_POLICIES_PROP_ID = 83;
CERT_ROOT_PROGRAM_NAME_CONSTRAINTS_PROP_ID = 84;
CERT_SUBJECT_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID = 85;
CERT_SUBJECT_DISABLE_CRL_PROP_ID = 86;
CERT_CEP_PROP_ID = 87;
CERT_SIGN_HASH_CNG_ALG_PROP_ID = 89;
CERT_SCARD_PIN_ID_PROP_ID = 90;
CERT_SCARD_PIN_INFO_PROP_ID = 91;
CERT_SUBJECT_PUB_KEY_BIT_LENGTH_PROP_ID = 92;
CERT_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID = 93;
CERT_ISSUER_PUB_KEY_BIT_LENGTH_PROP_ID = 94;
CERT_ISSUER_CHAIN_SIGN_HASH_CNG_ALG_PROP_ID = 95;
CERT_ISSUER_CHAIN_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID = 96;
CERT_NO_EXPIRE_NOTIFICATION_PROP_ID = 97;
CERT_AUTH_ROOT_SHA256_HASH_PROP_ID = 98;
CERT_NCRYPT_KEY_HANDLE_TRANSFER_PROP_ID = 99;
CERT_HCRYPTPROV_TRANSFER_PROP_ID = 100;
CERT_SMART_CARD_READER_PROP_ID = 101;
CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID = 102;
CERT_KEY_REPAIR_ATTEMPTED_PROP_ID = 103;
CERT_DISALLOWED_FILETIME_PROP_ID = 104;
CERT_ROOT_PROGRAM_CHAIN_POLICIES_PROP_ID = 105;
CERT_SMART_CARD_READER_NON_REMOVABLE_PROP_ID = 106;
CERT_FIRST_RESERVED_PROP_ID = 107;
CERT_LAST_RESERVED_PROP_ID = $00007fff;
CERT_FIRST_USER_PROP_ID = $8000;
CERT_LAST_USER_PROP_ID = $0000ffff;
const
CRYPT_DELETEKEYSET = 16;
const
CRYPT_E_NOT_FOUND = $80092004;
const
CRYPT_ACQUIRE_CACHE_FLAG = $1;
CRYPT_ACQUIRE_USE_PROV_INFO_FLAG = $2;
CRYPT_ACQUIRE_COMPARE_KEY_FLAG = $4;
CRYPT_ACQUIRE_NO_HEALING = $8;
CRYPT_ACQUIRE_SILENT_FLAG = $40;
CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG = $80;
CRYPT_ACQUIRE_NCRYPT_KEY_FLAGS_MASK = $70000;
CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG = $10000;
CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG = $20000;
CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = $40000;
const
szOID_RSA = '1.2.840.113549';
szOID_PKCS = '1.2.840.113549.1';
szOID_RSA_HASH = '1.2.840.113549.2';
szOID_RSA_ENCRYPT = '1.2.840.113549.3';
szOID_PKCS_1 = '1.2.840.113549.1.1';
szOID_PKCS_2 = '1.2.840.113549.1.2';
szOID_PKCS_3 = '1.2.840.113549.1.3';
szOID_PKCS_4 = '1.2.840.113549.1.4';
szOID_PKCS_5 = '1.2.840.113549.1.5';
szOID_PKCS_6 = '1.2.840.113549.1.6';
szOID_PKCS_7 = '1.2.840.113549.1.7';
szOID_PKCS_8 = '1.2.840.113549.1.8';
szOID_PKCS_9 = '1.2.840.113549.1.9';
szOID_PKCS_10 = '1.2.840.113549.1.10';
szOID_PKCS_12 = '1.2.840.113549.1.12';
szOID_RSA_RSA = '1.2.840.113549.1.1.1';
szOID_RSA_MD2RSA = '1.2.840.113549.1.1.2';
szOID_RSA_MD4RSA = '1.2.840.113549.1.1.3';
szOID_RSA_MD5RSA = '1.2.840.113549.1.1.4';
szOID_RSA_SHA1RSA = '1.2.840.113549.1.1.5';
szOID_RSA_SETOAEP_RSA = '1.2.840.113549.1.1.6';
szOID_RSAES_OAEP = '1.2.840.113549.1.1.7';
szOID_RSA_MGF1 = '1.2.840.113549.1.1.8';
szOID_RSA_PSPECIFIED = '1.2.840.113549.1.1.9';
szOID_RSA_SSA_PSS = '1.2.840.113549.1.1.10';
szOID_RSA_SHA256RSA = '1.2.840.113549.1.1.11';
szOID_RSA_SHA384RSA = '1.2.840.113549.1.1.12';
szOID_RSA_SHA512RSA = '1.2.840.113549.1.1.13';
szOID_RSA_DH = '1.2.840.113549.1.3.1';
szOID_RSA_data = '1.2.840.113549.1.7.1';
szOID_RSA_signedData = '1.2.840.113549.1.7.2';
szOID_RSA_envelopedData = '1.2.840.113549.1.7.3';
szOID_RSA_signEnvData = '1.2.840.113549.1.7.4';
szOID_RSA_digestedData = '1.2.840.113549.1.7.5';
szOID_RSA_hashedData = '1.2.840.113549.1.7.5';
szOID_RSA_encryptedData = '1.2.840.113549.1.7.6';
szOID_RSA_emailAddr = '1.2.840.113549.1.9.1';
szOID_RSA_unstructName = '1.2.840.113549.1.9.2';
szOID_RSA_contentType = '1.2.840.113549.1.9.3';
szOID_RSA_messageDigest = '1.2.840.113549.1.9.4';
szOID_RSA_signingTime = '1.2.840.113549.1.9.5';
szOID_RSA_counterSign = '1.2.840.113549.1.9.6';
szOID_RSA_challengePwd = '1.2.840.113549.1.9.7';
szOID_RSA_unstructAddr = '1.2.840.113549.1.9.8';
szOID_RSA_extCertAttrs = '1.2.840.113549.1.9.9';
szOID_RSA_certExtensions = '1.2.840.113549.1.9.14';
szOID_RSA_SMIMECapabilities = '1.2.840.113549.1.9.15';
szOID_RSA_preferSignedData = '1.2.840.113549.1.9.15.1';
szOID_TIMESTAMP_TOKEN = '1.2.840.113549.1.9.16.1.4';
szOID_RFC3161_counterSign = '1.3.6.1.4.1.311.3.3.1';
szOID_RSA_SMIMEalg = '1.2.840.113549.1.9.16.3';
szOID_RSA_SMIMEalgESDH = '1.2.840.113549.1.9.16.3.5';
szOID_RSA_SMIMEalgCMS3DESwrap = '1.2.840.113549.1.9.16.3.6';
szOID_RSA_SMIMEalgCMSRC2wrap = '1.2.840.113549.1.9.16.3.7';
szOID_RSA_MD2 = '1.2.840.113549.2.2';
szOID_RSA_MD4 = '1.2.840.113549.2.4';
szOID_RSA_MD5 = '1.2.840.113549.2.5';
szOID_RSA_RC2CBC = '1.2.840.113549.3.2';
szOID_RSA_RC4 = '1.2.840.113549.3.4';
szOID_RSA_DES_EDE3_CBC = '1.2.840.113549.3.7';
szOID_RSA_RC5_CBCPad = '1.2.840.113549.3.9';
szOID_ANSI_X942 = '1.2.840.10046';
szOID_ANSI_X942_DH = '1.2.840.10046.2.1';
szOID_X957 = '1.2.840.10040';
szOID_X957_DSA = '1.2.840.10040.4.1';
szOID_X957_SHA1DSA = '1.2.840.10040.4.3';
szOID_ECC_PUBLIC_KEY = '1.2.840.10045.2.1';
szOID_ECC_CURVE_P256 = '1.2.840.10045.3.1.7';
szOID_ECC_CURVE_P384 = '1.3.132.0.34';
szOID_ECC_CURVE_P521 = '1.3.132.0.35';
szOID_ECDSA_SHA1 = '1.2.840.10045.4.1';
szOID_ECDSA_SPECIFIED = '1.2.840.10045.4.3';
szOID_ECDSA_SHA256 = '1.2.840.10045.4.3.2';
szOID_ECDSA_SHA384 = '1.2.840.10045.4.3.3';
szOID_ECDSA_SHA512 = '1.2.840.10045.4.3.4';
szOID_NIST_AES128_CBC = '2.16.840.1.101.3.4.1.2';
szOID_NIST_AES192_CBC = '2.16.840.1.101.3.4.1.22';
szOID_NIST_AES256_CBC = '2.16.840.1.101.3.4.1.42';
szOID_NIST_AES128_WRAP = '2.16.840.1.101.3.4.1.5';
szOID_NIST_AES192_WRAP = '2.16.840.1.101.3.4.1.25';
szOID_NIST_AES256_WRAP = '2.16.840.1.101.3.4.1.45';
szOID_DH_SINGLE_PASS_STDDH_SHA1_KDF = '1.3.133.16.840.63.0.2';
szOID_DH_SINGLE_PASS_STDDH_SHA256_KDF = '1.3.132.1.11.1';
szOID_DH_SINGLE_PASS_STDDH_SHA384_KDF = '1.3.132.1.11.2';
szOID_DS = '2.5';
szOID_DSALG = '2.5.8';
szOID_DSALG_CRPT = '2.5.8.1';
szOID_DSALG_HASH = '2.5.8.2';
szOID_DSALG_SIGN = '2.5.8.3';
szOID_DSALG_RSA = '2.5.8.1.1';
szOID_OIW = '1.3.14';
szOID_OIWSEC = '1.3.14.3.2';
szOID_OIWSEC_md4RSA = '1.3.14.3.2.2';
szOID_OIWSEC_md5RSA = '1.3.14.3.2.3';
szOID_OIWSEC_md4RSA2 = '1.3.14.3.2.4';
szOID_OIWSEC_desECB = '1.3.14.3.2.6';
szOID_OIWSEC_desCBC = '1.3.14.3.2.7';
szOID_OIWSEC_desOFB = '1.3.14.3.2.8';
szOID_OIWSEC_desCFB = '1.3.14.3.2.9';
szOID_OIWSEC_desMAC = '1.3.14.3.2.10';
szOID_OIWSEC_rsaSign = '1.3.14.3.2.11';
szOID_OIWSEC_dsa = '1.3.14.3.2.12';
szOID_OIWSEC_shaDSA = '1.3.14.3.2.13';
szOID_OIWSEC_mdc2RSA = '1.3.14.3.2.14';
szOID_OIWSEC_shaRSA = '1.3.14.3.2.15';
szOID_OIWSEC_dhCommMod = '1.3.14.3.2.16';
szOID_OIWSEC_desEDE = '1.3.14.3.2.17';
szOID_OIWSEC_sha = '1.3.14.3.2.18';
szOID_OIWSEC_mdc2 = '1.3.14.3.2.19';
szOID_OIWSEC_dsaComm = '1.3.14.3.2.20';
szOID_OIWSEC_dsaCommSHA = '1.3.14.3.2.21';
szOID_OIWSEC_rsaXchg = '1.3.14.3.2.22';
szOID_OIWSEC_keyHashSeal = '1.3.14.3.2.23';
szOID_OIWSEC_md2RSASign = '1.3.14.3.2.24';
szOID_OIWSEC_md5RSASign = '1.3.14.3.2.25';
szOID_OIWSEC_sha1 = '1.3.14.3.2.26';
szOID_OIWSEC_dsaSHA1 = '1.3.14.3.2.27';
szOID_OIWSEC_dsaCommSHA1 = '1.3.14.3.2.28';
szOID_OIWSEC_sha1RSASign = '1.3.14.3.2.29';
szOID_OIWDIR = '1.3.14.7.2';
szOID_OIWDIR_CRPT = '1.3.14.7.2.1';
szOID_OIWDIR_HASH = '1.3.14.7.2.2';
szOID_OIWDIR_SIGN = '1.3.14.7.2.3';
szOID_OIWDIR_md2 = '1.3.14.7.2.2.1';
szOID_OIWDIR_md2RSA = '1.3.14.7.2.3.1';
szOID_INFOSEC = '2.16.840.1.101.2.1';
szOID_INFOSEC_sdnsSignature = '2.16.840.1.101.2.1.1.1';
szOID_INFOSEC_mosaicSignature = '2.16.840.1.101.2.1.1.2';
szOID_INFOSEC_sdnsConfidentiality = '2.16.840.1.101.2.1.1.3';
szOID_INFOSEC_mosaicConfidentiality = '2.16.840.1.101.2.1.1.4';
szOID_INFOSEC_sdnsIntegrity = '2.16.840.1.101.2.1.1.5';
szOID_INFOSEC_mosaicIntegrity = '2.16.840.1.101.2.1.1.6';
szOID_INFOSEC_sdnsTokenProtection = '2.16.840.1.101.2.1.1.7';
szOID_INFOSEC_mosaicTokenProtection = '2.16.840.1.101.2.1.1.8';
szOID_INFOSEC_sdnsKeyManagement = '2.16.840.1.101.2.1.1.9';
szOID_INFOSEC_mosaicKeyManagement = '2.16.840.1.101.2.1.1.10';
szOID_INFOSEC_sdnsKMandSig = '2.16.840.1.101.2.1.1.11';
szOID_INFOSEC_mosaicKMandSig = '2.16.840.1.101.2.1.1.12';
szOID_INFOSEC_SuiteASignature = '2.16.840.1.101.2.1.1.13';
szOID_INFOSEC_SuiteAConfidentiality = '2.16.840.1.101.2.1.1.14';
szOID_INFOSEC_SuiteAIntegrity = '2.16.840.1.101.2.1.1.15';
szOID_INFOSEC_SuiteATokenProtection = '2.16.840.1.101.2.1.1.16';
szOID_INFOSEC_SuiteAKeyManagement = '2.16.840.1.101.2.1.1.17';
szOID_INFOSEC_SuiteAKMandSig = '2.16.840.1.101.2.1.1.18';
szOID_INFOSEC_mosaicUpdatedSig = '2.16.840.1.101.2.1.1.19';
szOID_INFOSEC_mosaicKMandUpdSig = '2.16.840.1.101.2.1.1.20';
szOID_INFOSEC_mosaicUpdatedInteg = '2.16.840.1.101.2.1.1.21';
szOID_NIST_sha256 = '2.16.840.1.101.3.4.2.1';
szOID_NIST_sha384 = '2.16.840.1.101.3.4.2.2';
szOID_NIST_sha512 = '2.16.840.1.101.3.4.2.3';
const
CERT_STORE_ADD_NEW = 1;
CERT_STORE_ADD_USE_EXISTING = 2;
CERT_STORE_ADD_REPLACE_EXISTING = 3;
CERT_STORE_ADD_ALWAYS = 4;
CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5;
CERT_STORE_ADD_NEWER = 6;
CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7;
function PFXImportCertStore(pPFX: PCRYPT_DATA_BLOB; szPassword: PWideChar; dwFlags: DWORD): HCERTSTORE; stdcall; external CryptoLib;
function CertOpenSystemStore(hProv: HCRYPTPROV; szSubsystemProtocol: PChar): HCERTSTORE; stdcall; external CryptoLib name {$IFDEF UNICODE} 'CertOpenSystemStoreW' {$ELSE} 'CertOpenSystemStoreA' {$ENDIF} ;
function CertOpenStore(szStoreProvider: LPCSTR; dwMsgAndCertEncodingType: DWORD; hCryptProv: HCRYPTPROV; dwFlags: DWORD; pvPara: Pointer): HCERTSTORE; stdcall; external CryptoLib name 'CertOpenStore';
function CertCloseStore(hCertStore: HCERTSTORE; dwFlags: DWORD): BOOL; stdcall; external CryptoLib;
function CertEnumCertificatesInStore(hCertStore: HCERTSTORE; pPrevCertContext: PCCERT_CONTEXT): PCCERT_CONTEXT; stdcall; external CryptoLib;
function CertFindCertificateInStore(hCertStore: HCERTSTORE; dwCertEncodingType: DWORD; dwFindFlags: DWORD; dwFindType: DWORD; pvFindPara: Pointer; pPrevCertContext: PCCERT_CONTEXT): PCCERT_CONTEXT; stdcall; external CryptoLib;
function CertFreeCertificateContext(pCertContext: PCCERT_CONTEXT): BOOL; stdcall; external CryptoLib;
function CertDuplicateCertificateContext(pCertContext: PCCERT_CONTEXT): PCCERT_CONTEXT; stdcall; external CryptoLib;
function CertGetNameStringA(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer; pszNameString: PAnsiChar; cchNameString: DWORD): DWORD; stdcall; external CryptoLib name 'CertGetNameStringA';
function CertGetNameStringW(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer; pszNameString: PWideChar; cchNameString: DWORD): DWORD; stdcall; external CryptoLib name 'CertGetNameStringW';
function CertGetNameString(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer; pszNameString: PChar; cchNameString: DWORD): DWORD; stdcall; external CryptoLib name {$IFDEF UNICODE} 'CertGetNameStringW' {$ELSE} 'CertGetNameStringA' {$ENDIF} ;
function GetFriendlyNameOfCert(pCertContext: PCCERT_CONTEXT; pchBuffer: PChar; cchBuffer: DWORD): DWORD; stdcall; external CryptDlgLib name {$IFDEF UNICODE} 'GetFriendlyNameOfCertW' {$ELSE} 'GetFriendlyNameOfCertA' {$ENDIF} ;
function CertGetCertificateContextProperty(pCertContext: PCCERT_CONTEXT; dwPropId: DWORD; pvData: Pointer; var pcbData: DWORD): BOOL; stdcall; external CryptoLib;
function CryptAcquireContextA(var phProv: HCRYPTPROV; pszContainer, pszProvider: PAnsiChar; dwProvType, dwFlags: DWORD): BOOL; stdcall; external AdvapiLib;
function CryptAcquireContextU(var phProv: HCRYPTPROV; pszContainer, pszProvider: PWideChar; dwProvType, dwFlags: DWORD): BOOL; stdcall; external AdvapiLib name 'CryptAcquireContextW';
function CryptAcquireContextW(var phProv: HCRYPTPROV; pszContainer, pszProvider: PWideChar; dwProvType, dwFlags: DWORD): BOOL; stdcall; external AdvapiLib;
function CryptAcquireContext(var phProv: HCRYPTPROV; pszContainer, pszProvider: PChar; dwProvType, dwFlags: DWORD): BOOL; stdcall; external AdvapiLib name {$IFDEF UNICODE} 'CryptAcquireContextW' {$ELSE} 'CryptAcquireContextA' {$ENDIF} ;
function CryptAcquireCertificatePrivateKey(pCertContext: PCCERT_CONTEXT; dwFlags: DWORD; pvParameters: Pointer; var phCryptProv: HCRYPTPROV; var pdwKeySpec: DWORD; pfCallerFreeProv: PBOOL): BOOL; stdcall; external CryptoLib;
function CertAddCertificateContextToStore(hCertStore: HCERTSTORE; pCertContext: PCCERT_CONTEXT; dwAddDisposition: DWORD; ppStoreContext: PPCCERT_CONTEXT): BOOL; stdcall; external CryptoLib;
function CryptSignMessage(pSignPara: PCRYPT_SIGN_MESSAGE_PARA; fDetachedSignature: BOOL; cToBeSigned: DWORD; rgpbToBeSigned: PPtrArray; rgcbToBeSigned: PDWORDArray; pbSignedBlob: PByte; var pcbSignedBlob: DWORD): BOOL; stdcall external CryptoLib;
function CertGetNameStringPAS(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer; out Name: string): boolean; overload;
function CertGetNameStringPAS(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer): string; overload;
function CertGetCertificateContextPropertyPAS(pCertContext: PCCERT_CONTEXT; dwPropId: DWORD; out Data: AnsiString): BOOL; overload;
function CertGetCertificateContextPropertyPAS(pCertContext: PCCERT_CONTEXT; dwPropId: DWORD): AnsiString; overload;
implementation
function CertGetNameStringPAS(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer; out Name: string): boolean; overload;
var
n: DWORD;
begin
Result := False;
Name := '';
n := CertGetNameString(pCertContext, dwType, dwFlags, pvTypePara, nil, 0);
if n > 0 then
begin
SetLength(Name, n);
n := CertGetNameString(pCertContext, dwType, dwFlags, pvTypePara, @Name[1], n);
if n > 0 then
begin
SetLength(Name, n-1);
Result := True;
end
else
Name := '';
end;
end;
function CertGetNameStringPAS(pCertContext: PCCERT_CONTEXT; dwType, dwFlags: DWORD; pvTypePara: Pointer): string;
begin
if not CertGetNameStringPAS(pCertContext, dwType, dwFlags, pvTypePara, Result) then
Result := '';
end;
function CertGetCertificateContextPropertyPAS(pCertContext: PCCERT_CONTEXT; dwPropId: DWORD; out Data: AnsiString): BOOL;
var
n: DWORD;
begin
Result := False;
Data := '';
n := 0;
if CertGetCertificateContextProperty(pCertContext, dwPropId, nil, n) then
begin
SetLength(Data, n);
if CertGetCertificateContextProperty(pCertContext, dwPropId, @Data[1], n) then
begin
SetLength(Data, n);
Result := True;
end
else
Data := '';
end;
end;
function CertGetCertificateContextPropertyPAS(pCertContext: PCCERT_CONTEXT; dwPropId: DWORD): AnsiString;
begin
if not CertGetCertificateContextPropertyPAS(pCertContext, dwPropId, Result) then
Result := '';
end;
end.

50
src/synapse/README.md Normal file
View file

@ -0,0 +1,50 @@
# (Ararat) Synapse TCP/IP library for Pascal
Official source repository is https://github.com/geby/synapse (It was changed from SourceForge at January 2024)
This opensource library is my freetime hobby. You can reward me by any donation, thank you!
[![Paypal donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/donate/?hosted_button_id=8APS698SPM2VQ) or use https://paypal.me/gebauerl
### About
This project deals with network communication by means of blocking sockets (with limited non-blocking mode) on Windows, Linux, Android and on many POSIX based systems. This project not using asynchronous sockets! The Project contains simple low level non-visual classes in set of units for easiest programming.
Blocking mode is more natural in pre-emptive multitasking and multithreading environment. Synchronous mode (called 'blocking' in Winsock terminology) features acting thread waits until the needed operation terminates. When we want to send data, the program exits function only after data is sent - or - if we want to receive data, the program exits the function only after the desired data is received.
Thus, much more crisp and simple programming is achieved. You especially feel it when trying to implement any Internet protocol, which is typically based on 'send-wait for reply' method. If you want to implement it in an asynchronous method, you would have to accept complicated event processing and synchronous mode simulation. Therefore a synchronous socket is simple and natural for the majority programming tasks. No required multithread synchronisation, no need for windows message processing... Great for command line utilities, visual projects, services, simple servers...
You can found here addition to Synapse project called **SynaSer**, too. This is library for blocking communication on serial ports (COM). It is non-visual class as in Synapse, and API is very similar to Synapse.
### Compatibility
* **Delphi 5 - 2007** (ANSI, Win32)
* **Delphi 2009 - 12** (Unicode, Win32/Win64/Android)
* **FreePascal** (Win32/Win64, probably all platforms supported by **sockets** unit)
### Basic features
* IPv4 and IPv6 support
* low level UDP protocol, include SOCKS5 proxy support
* low level TCP protocol, include SOCKS4/5 or HTTP proxy support, TLS encryption by 3rd-party libraries (OpenSSL 3.x, etc.)
* ICMP pings
* Basic support for internet protocols like: DNS, SMTP, IMAP4, HTTP, NTP, POP3, FTP, TFTP, SNMP, LDAP, Syslog, NNTP, Telnet, ClamD
* encoding/decoding MIME messages, include charset conversions. Old style UUcode, XXcode and Yenc supported too
* many handy utilities included
* Serial port communication, include high-speed USB chips
### Support
Feel free to use:
* Read the [wiki](https://github.com/geby/synapse/wiki)
* Ask in [discussions](https://github.com/geby/synapse/discussions)
* Report [issues](https://github.com/geby/synapse/issues)
### BSD style license
**Copyright (c)1999-2024, Lukas Gebauer**
**All rights reserved.**
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Lukas Gebauer nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<sub>Version: 2024/01/16</sub>

521
src/synapse/asn1util.pas Normal file
View file

@ -0,0 +1,521 @@
{==============================================================================|
| Project : Ararat Synapse | 002.001.001 |
|==============================================================================|
| Content: support for ASN.1 BER coding and decoding |
|==============================================================================|
| Copyright (c)1999-2021, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c) 1999-2021 |
| Portions created by Hernan Sanchez are Copyright (c) 2000. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
| Hernan Sanchez (hernan.sanchez@iname.com) |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{: @abstract(Utilities for handling ASN.1 BER encoding)
By this unit you can parse ASN.1 BER encoded data to elements or build back any
elements to ASN.1 BER encoded buffer. You can dump ASN.1 BER encoded data to
human readable form for easy debugging, too.
Supported element types are: ASN1_BOOL, ASN1_INT, ASN1_OCTSTR, ASN1_NULL,
ASN1_OBJID, ASN1_ENUM, ASN1_SEQ, ASN1_SETOF, ASN1_IPADDR, ASN1_COUNTER,
ASN1_GAUGE, ASN1_TIMETICKS, ASN1_OPAQUE
For sample of using, look to @link(TSnmpSend) or @link(TLdapSend)class.
}
{$Q-}
{$H+}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit asn1util;
interface
uses
SysUtils, Classes, synautil;
const
ASN1_BOOL = $01;
ASN1_INT = $02;
ASN1_OCTSTR = $04;
ASN1_NULL = $05;
ASN1_OBJID = $06;
ASN1_ENUM = $0a;
ASN1_SEQ = $30;
ASN1_SETOF = $31;
ASN1_IPADDR = $40;
ASN1_COUNTER = $41;
ASN1_GAUGE = $42;
ASN1_TIMETICKS = $43;
ASN1_OPAQUE = $44;
ASN1_COUNTER64 = $46;
{:Encodes OID item to binary form.}
function ASNEncOIDItem(Value: Int64): AnsiString;
{:Decodes an OID item of the next element in the "Buffer" from the "Start"
position.}
function ASNDecOIDItem(var Start: Integer; const Buffer: AnsiString): Int64;
{:Encodes the length of ASN.1 element to binary.}
function ASNEncLen(Len: Integer): AnsiString;
{:Decodes length of next element in "Buffer" from the "Start" position.}
function ASNDecLen(var Start: Integer; const Buffer: AnsiString): Integer;
{:Encodes a signed integer to ASN.1 binary}
function ASNEncInt(Value: Int64): AnsiString;
{:Encodes unsigned integer into ASN.1 binary}
function ASNEncUInt(Value: Integer): AnsiString;
{:Encodes ASN.1 object to binary form.}
function ASNObject(const Data: AnsiString; ASNType: Integer): AnsiString;
{:Beginning with the "Start" position, decode the ASN.1 item of the next element
in "Buffer". Type of item is stored in "ValueType."}
function ASNItem(var Start: Integer; const Buffer: AnsiString;
var ValueType: Integer): AnsiString;
{:Encodes an MIB OID string to binary form.}
function MibToId(Mib: String): AnsiString;
{:Decodes MIB OID from binary form to string form.}
function IdToMib(const Id: AnsiString): String;
{:Encodes an one number from MIB OID to binary form. (used internally from
@link(MibToId))}
function IntMibToStr(const Value: AnsiString): AnsiString;
{:Convert ASN.1 BER encoded buffer to human readable form for debugging.}
function ASNdump(const Value: AnsiString): AnsiString;
implementation
{==============================================================================}
function ASNEncOIDItem(Value: Int64): AnsiString;
var
x: Int64;
xm: Byte;
b: Boolean;
begin
x := Value;
b := False;
Result := '';
repeat
xm := x mod 128;
x := x div 128;
if b then
xm := xm or $80;
if x > 0 then
b := True;
Result := AnsiChar(xm) + Result;
until x = 0;
end;
{==============================================================================}
function ASNDecOIDItem(var Start: Integer; const Buffer: AnsiString): Int64;
var
x: Integer;
b: Boolean;
begin
Result := 0;
repeat
Result := Result * 128;
x := Ord(Buffer[Start]);
Inc(Start);
b := x > $7F;
x := x and $7F;
Result := Result + x;
until not b;
end;
{==============================================================================}
function ASNEncLen(Len: Integer): AnsiString;
var
x, y: Integer;
begin
if Len < $80 then
Result := AnsiChar(Len)
else
begin
x := Len;
Result := '';
repeat
y := x mod 256;
x := x div 256;
Result := AnsiChar(y) + Result;
until x = 0;
y := Length(Result);
y := y or $80;
Result := AnsiChar(y) + Result;
end;
end;
{==============================================================================}
function ASNDecLen(var Start: Integer; const Buffer: AnsiString): Integer;
var
x, n: Integer;
begin
x := Ord(Buffer[Start]);
Inc(Start);
if x < $80 then
Result := x
else
begin
Result := 0;
x := x and $7F;
for n := 1 to x do
begin
Result := Result * 256;
x := Ord(Buffer[Start]);
Inc(Start);
Result := Result + x;
end;
end;
end;
{==============================================================================}
function ASNEncInt(Value: Int64): AnsiString;
var
x: Int64;
y: byte;
neg: Boolean;
begin
neg := Value < 0;
x := Abs(Value);
if neg then
x := x - 1;
Result := '';
repeat
y := x mod 256;
x := x div 256;
if neg then
y := not y;
Result := AnsiChar(y) + Result;
until x = 0;
if (not neg) and (Result[1] > #$7F) then
Result := #0 + Result;
if (neg) and (Result[1] < #$80) then
Result := #$FF + Result;
end;
{==============================================================================}
function ASNEncUInt(Value: Integer): AnsiString;
var
x, y: Integer;
neg: Boolean;
begin
neg := Value < 0;
x := Value;
if neg then
x := x and $7FFFFFFF;
Result := '';
repeat
y := x mod 256;
x := x div 256;
Result := AnsiChar(y) + Result;
until x = 0;
if neg then
Result[1] := AnsiChar(Ord(Result[1]) or $80);
end;
{==============================================================================}
function ASNObject(const Data: AnsiString; ASNType: Integer): AnsiString;
begin
Result := AnsiChar(ASNType) + ASNEncLen(Length(Data)) + Data;
end;
{==============================================================================}
function ASNItem(var Start: Integer; const Buffer: AnsiString;
var ValueType: Integer): AnsiString;
var
ASNType: Integer;
ASNSize: Integer;
y: int64;
n: Integer;
x: byte;
s: AnsiString;
c: AnsiChar;
neg: Boolean;
l: Integer;
begin
Result := '';
ValueType := ASN1_NULL;
l := Length(Buffer);
if l < (Start + 1) then
Exit;
ASNType := Ord(Buffer[Start]);
ValueType := ASNType;
Inc(Start);
ASNSize := ASNDecLen(Start, Buffer);
if (Start + ASNSize - 1) > l then
Exit;
if (ASNType and $20) > 0 then
// Result := '$' + IntToHex(ASNType, 2)
Result := Copy(Buffer, Start, ASNSize)
else
case ASNType of
ASN1_INT, ASN1_ENUM, ASN1_BOOL:
begin
y := 0;
neg := False;
for n := 1 to ASNSize do
begin
x := Ord(Buffer[Start]);
if (n = 1) and (x > $7F) then
neg := True;
if neg then
x := not x;
y := y * 256 + x;
Inc(Start);
end;
if neg then
y := -(y + 1);
Result := IntToStr(y);
end;
ASN1_COUNTER, ASN1_GAUGE, ASN1_TIMETICKS, ASN1_COUNTER64:
begin
y := 0;
for n := 1 to ASNSize do
begin
y := y * 256 + Ord(Buffer[Start]);
Inc(Start);
end;
Result := IntToStr(y);
end;
ASN1_OCTSTR, ASN1_OPAQUE:
begin
for n := 1 to ASNSize do
begin
c := AnsiChar(Buffer[Start]);
Inc(Start);
s := s + c;
end;
Result := s;
end;
ASN1_OBJID:
begin
for n := 1 to ASNSize do
begin
c := AnsiChar(Buffer[Start]);
Inc(Start);
s := s + c;
end;
Result := IdToMib(s);
end;
ASN1_IPADDR:
begin
s := '';
for n := 1 to ASNSize do
begin
if (n <> 1) then
s := s + '.';
y := Ord(Buffer[Start]);
Inc(Start);
s := s + IntToStr(y);
end;
Result := s;
end;
ASN1_NULL:
begin
Result := '';
Start := Start + ASNSize;
end;
else // unknown
begin
for n := 1 to ASNSize do
begin
c := AnsiChar(Buffer[Start]);
Inc(Start);
s := s + c;
end;
Result := s;
end;
end;
end;
{==============================================================================}
function MibToId(Mib: String): AnsiString;
var
x: int64;
function WalkInt(var s: String): int64;
var
x: Integer;
t: AnsiString;
begin
x := Pos('.', s);
if x < 1 then
begin
t := s;
s := '';
end
else
begin
t := Copy(s, 1, x - 1);
s := Copy(s, x + 1, Length(s) - x);
end;
Result := StrToInt64Def(t, 0);
end;
begin
Result := '';
x := WalkInt(Mib);
x := x * 40 + WalkInt(Mib);
Result := ASNEncOIDItem(x);
while Mib <> '' do
begin
x := WalkInt(Mib);
Result := Result + ASNEncOIDItem(x);
end;
end;
{==============================================================================}
function IdToMib(const Id: AnsiString): String;
var
x, y: int64;
n: Integer;
begin
Result := '';
n := 1;
while Length(Id) + 1 > n do
begin
x := ASNDecOIDItem(n, Id);
if (n - 1) = 1 then
begin
y := x div 40;
x := x mod 40;
Result := IntToStr(y);
end;
Result := Result + '.' + IntToStr(x);
end;
end;
{==============================================================================}
function IntMibToStr(const Value: AnsiString): AnsiString;
var
n, y: Integer;
begin
y := 0;
for n := 1 to Length(Value) - 1 do
y := y * 256 + Ord(Value[n]);
Result := IntToStr(y);
end;
{==============================================================================}
function ASNdump(const Value: AnsiString): AnsiString;
var
i, at, x, n: integer;
s, indent: AnsiString;
il: TStringList;
begin
il := TStringList.Create;
try
Result := '';
i := 1;
indent := '';
while i < Length(Value) do
begin
for n := il.Count - 1 downto 0 do
begin
x := StrToIntDef(il[n], 0);
if x <= i then
begin
il.Delete(n);
Delete(indent, 1, 2);
end;
end;
s := ASNItem(i, Value, at);
Result := Result + indent + '$' + IntToHex(at, 2);
if (at and $20) > 0 then
begin
x := Length(s);
Result := Result + ' constructed: length ' + IntToStr(x);
indent := indent + ' ';
il.Add(IntToStr(x + i - 1));
end
else
begin
case at of
ASN1_BOOL:
Result := Result + ' BOOL: ';
ASN1_INT:
Result := Result + ' INT: ';
ASN1_ENUM:
Result := Result + ' ENUM: ';
ASN1_COUNTER:
Result := Result + ' COUNTER: ';
ASN1_GAUGE:
Result := Result + ' GAUGE: ';
ASN1_TIMETICKS:
Result := Result + ' TIMETICKS: ';
ASN1_OCTSTR:
Result := Result + ' OCTSTR: ';
ASN1_OPAQUE:
Result := Result + ' OPAQUE: ';
ASN1_OBJID:
Result := Result + ' OBJID: ';
ASN1_IPADDR:
Result := Result + ' IPADDR: ';
ASN1_NULL:
Result := Result + ' NULL: ';
ASN1_COUNTER64:
Result := Result + ' COUNTER64: ';
else // other
Result := Result + ' unknown: ';
end;
if IsBinaryString(s) then
s := DumpExStr(s);
Result := Result + s;
end;
Result := Result + #$0d + #$0a;
end;
finally
il.Free;
end;
end;
{==============================================================================}
end.

4408
src/synapse/blcksock.pas Normal file

File diff suppressed because it is too large Load diff

277
src/synapse/clamsend.pas Normal file
View file

@ -0,0 +1,277 @@
{==============================================================================|
| Project : Ararat Synapse | 001.001.001 |
|==============================================================================|
| Content: ClamAV-daemon client |
|==============================================================================|
| Copyright (c)2005-2010, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2005-2010. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{:@abstract( ClamAV-daemon client)
This unit is capable to do antivirus scan of your data by TCP channel to ClamD
daemon from ClamAV. See more about ClamAV on @LINK(http://www.clamav.net)
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$Q-}
{$H+}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit clamsend;
interface
uses
SysUtils, Classes,
synsock, blcksock, synautil;
const
cClamProtocol = '3310';
type
{:@abstract(Implementation of ClamAV-daemon client protocol)
By this class you can scan any your data by ClamAV opensource antivirus.
This class can connect to ClamD by TCP channel, send your data to ClamD
and read result.}
TClamSend = class(TSynaClient)
private
FSock: TTCPBlockSocket;
FDSock: TTCPBlockSocket;
FSession: boolean;
function Login: boolean; virtual;
function Logout: Boolean; virtual;
function OpenStream: Boolean; virtual;
public
constructor Create;
destructor Destroy; override;
{:Call any command to ClamD. Used internally by other methods.}
function DoCommand(const Value: AnsiString): AnsiString; virtual;
{:Return ClamAV version and version of loaded databases.}
function GetVersion: AnsiString; virtual;
{:Scan content of TStrings.}
function ScanStrings(const Value: TStrings): AnsiString; virtual;
{:Scan content of TStream.}
function ScanStream(const Value: TStream): AnsiString; virtual;
{:Scan content of TStrings by new 0.95 API.}
function ScanStrings2(const Value: TStrings): AnsiString; virtual;
{:Scan content of TStream by new 0.95 API.}
function ScanStream2(const Value: TStream): AnsiString; virtual;
published
{:Socket object used for TCP/IP operation. Good for seting OnStatus hook, etc.}
property Sock: TTCPBlockSocket read FSock;
{:Socket object used for TCP data transfer operation. Good for seting OnStatus hook, etc.}
property DSock: TTCPBlockSocket read FDSock;
{:Can turn-on session mode of communication with ClamD. Default is @false,
because ClamAV developers design their TCP code very badly and session mode
is broken now (CVS-20051031). Maybe ClamAV developers fix their bugs
and this mode will be possible in future.}
property Session: boolean read FSession write FSession;
end;
implementation
constructor TClamSend.Create;
begin
inherited Create;
FSock := TTCPBlockSocket.Create;
FSock.Owner := self;
FDSock := TTCPBlockSocket.Create;
FDSock.Owner := self;
FTimeout := 60000;
FTargetPort := cClamProtocol;
FSession := false;
end;
destructor TClamSend.Destroy;
begin
Logout;
FDSock.Free;
FSock.Free;
inherited Destroy;
end;
function TClamSend.DoCommand(const Value: AnsiString): AnsiString;
begin
Result := '';
if not FSession then
FSock.CloseSocket
else
FSock.SendString(Value + LF);
if not FSession or (FSock.LastError <> 0) then
begin
if Login then
FSock.SendString(Value + LF)
else
Exit;
end;
Result := FSock.RecvTerminated(FTimeout, LF);
end;
function TClamSend.Login: boolean;
begin
Result := False;
Sock.CloseSocket;
FSock.Bind(FIPInterface, cAnyPort);
if FSock.LastError <> 0 then
Exit;
FSock.Connect(FTargetHost, FTargetPort);
if FSock.LastError <> 0 then
Exit;
if FSession then
FSock.SendString('SESSION' + LF);
Result := FSock.LastError = 0;
end;
function TClamSend.Logout: Boolean;
begin
FSock.SendString('END' + LF);
Result := FSock.LastError = 0;
FSock.CloseSocket;
end;
function TClamSend.GetVersion: AnsiString;
begin
Result := DoCommand('nVERSION');
end;
function TClamSend.OpenStream: Boolean;
var
S: AnsiString;
begin
Result := False;
s := DoCommand('nSTREAM');
if (s <> '') and (Copy(s, 1, 4) = 'PORT') then
begin
s := SeparateRight(s, ' ');
FDSock.CloseSocket;
FDSock.Bind(FIPInterface, cAnyPort);
if FDSock.LastError <> 0 then
Exit;
FDSock.Connect(FTargetHost, s);
if FDSock.LastError <> 0 then
Exit;
Result := True;
end;
end;
function TClamSend.ScanStrings(const Value: TStrings): AnsiString;
begin
Result := '';
if OpenStream then
begin
DSock.SendString(Value.Text);
DSock.CloseSocket;
Result := FSock.RecvTerminated(FTimeout, LF);
end;
end;
function TClamSend.ScanStream(const Value: TStream): AnsiString;
begin
Result := '';
if OpenStream then
begin
DSock.SendStreamRaw(Value);
DSock.CloseSocket;
Result := FSock.RecvTerminated(FTimeout, LF);
end;
end;
function TClamSend.ScanStrings2(const Value: TStrings): AnsiString;
var
i: integer;
s: AnsiString;
begin
Result := '';
if not FSession then
FSock.CloseSocket
else
FSock.sendstring('nINSTREAM' + LF);
if not FSession or (FSock.LastError <> 0) then
begin
if Login then
FSock.sendstring('nINSTREAM' + LF)
else
Exit;
end;
s := Value.text;
i := length(s);
FSock.SendString(CodeLongint(i) + s + #0#0#0#0);
Result := FSock.RecvTerminated(FTimeout, LF);
end;
function TClamSend.ScanStream2(const Value: TStream): AnsiString;
var
i: integer;
begin
Result := '';
if not FSession then
FSock.CloseSocket
else
FSock.sendstring('nINSTREAM' + LF);
if not FSession or (FSock.LastError <> 0) then
begin
if Login then
FSock.sendstring('nINSTREAM' + LF)
else
Exit;
end;
i := value.Size;
FSock.SendString(CodeLongint(i));
FSock.SendStreamRaw(Value);
FSock.SendString(#0#0#0#0);
Result := FSock.RecvTerminated(FTimeout, LF);
end;
end.

603
src/synapse/dnssend.pas Normal file
View file

@ -0,0 +1,603 @@
{==============================================================================|
| Project : Ararat Synapse | 002.007.006 |
|==============================================================================|
| Content: DNS client |
|==============================================================================|
| Copyright (c)1999-2010, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2000-2010. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{: @abstract(DNS client by UDP or TCP)
Support for sending DNS queries by UDP or TCP protocol. It can retrieve zone
transfers too!
Used RFC: RFC-1035, RFC-1183, RFC1706, RFC1712, RFC2163, RFC2230
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$Q-}
{$H+}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit dnssend;
interface
uses
SysUtils, Classes,
blcksock, synautil, synaip, synsock;
const
cDnsProtocol = '53';
QTYPE_A = 1;
QTYPE_NS = 2;
QTYPE_MD = 3;
QTYPE_MF = 4;
QTYPE_CNAME = 5;
QTYPE_SOA = 6;
QTYPE_MB = 7;
QTYPE_MG = 8;
QTYPE_MR = 9;
QTYPE_NULL = 10;
QTYPE_WKS = 11; //
QTYPE_PTR = 12;
QTYPE_HINFO = 13;
QTYPE_MINFO = 14;
QTYPE_MX = 15;
QTYPE_TXT = 16;
QTYPE_RP = 17;
QTYPE_AFSDB = 18;
QTYPE_X25 = 19;
QTYPE_ISDN = 20;
QTYPE_RT = 21;
QTYPE_NSAP = 22;
QTYPE_NSAPPTR = 23;
QTYPE_SIG = 24; // RFC-2065
QTYPE_KEY = 25; // RFC-2065
QTYPE_PX = 26;
QTYPE_GPOS = 27;
QTYPE_AAAA = 28;
QTYPE_LOC = 29; // RFC-1876
QTYPE_NXT = 30; // RFC-2065
QTYPE_SRV = 33;
QTYPE_NAPTR = 35; // RFC-2168
QTYPE_KX = 36;
QTYPE_SPF = 99;
QTYPE_AXFR = 252;
QTYPE_MAILB = 253; //
QTYPE_MAILA = 254; //
QTYPE_ALL = 255;
type
{:@abstract(Implementation of DNS protocol by UDP or TCP protocol.)
Note: Are you missing properties for specify server address and port? Look to
parent @link(TSynaClient) too!}
TDNSSend = class(TSynaClient)
private
FID: Word;
FRCode: Integer;
FBuffer: AnsiString;
FSock: TUDPBlockSocket;
FTCPSock: TTCPBlockSocket;
FUseTCP: Boolean;
FAnswerInfo: TStringList;
FNameserverInfo: TStringList;
FAdditionalInfo: TStringList;
FAuthoritative: Boolean;
FTruncated: Boolean;
function CompressName(const Value: AnsiString): AnsiString;
function CodeHeader: AnsiString;
function CodeQuery(const Name: AnsiString; QType: Integer): AnsiString;
function DecodeLabels(var From: Integer): AnsiString;
function DecodeString(var From: Integer): AnsiString;
function DecodeResource(var i: Integer; const Info: TStringList;
QType: Integer): AnsiString;
function RecvTCPResponse(const WorkSock: TBlockSocket): AnsiString;
function DecodeResponse(const Buf: AnsiString; const Reply: TStrings;
QType: Integer):boolean;
public
constructor Create;
destructor Destroy; override;
{:Query a DNSHost for QType resources correspond to a name. Supported QType
values are: Qtype_A, Qtype_NS, Qtype_MD, Qtype_MF, Qtype_CNAME, Qtype_SOA,
Qtype_MB, Qtype_MG, Qtype_MR, Qtype_NULL, Qtype_PTR, Qtype_HINFO,
Qtype_MINFO, Qtype_MX, Qtype_TXT, Qtype_RP, Qtype_AFSDB, Qtype_X25,
Qtype_ISDN, Qtype_RT, Qtype_NSAP, Qtype_NSAPPTR, Qtype_PX, Qtype_GPOS,
Qtype_KX.
Type for zone transfers QTYPE_AXFR is supported too, but only in TCP mode!
"Name" is domain name or host name for queried resource. If "name" is
IP address, automatically convert to reverse domain form (.in-addr.arpa).
If result is @true, Reply contains resource records. One record on one line.
If Resource record have multiple fields, they are stored on line divided by
comma. (example: MX record contains value 'rs.cesnet.cz' with preference
number 10, string in Reply is: '10,rs.cesnet.cz'). All numbers or IP address
in resource are converted to string form.}
function DNSQuery(Name: AnsiString; QType: Integer;
const Reply: TStrings): Boolean;
published
{:Socket object used for UDP operation. Good for seting OnStatus hook, etc.}
property Sock: TUDPBlockSocket read FSock;
{:Socket object used for TCP operation. Good for seting OnStatus hook, etc.}
property TCPSock: TTCPBlockSocket read FTCPSock;
{:if @true, then is used TCP protocol instead UDP. It is needed for zone
transfers, etc.}
property UseTCP: Boolean read FUseTCP Write FUseTCP;
{:After DNS operation contains ResultCode of DNS operation.
Values are: 0-no error, 1-format error, 2-server failure, 3-name error,
4-not implemented, 5-refused.}
property RCode: Integer read FRCode;
{:@True, if answer is authoritative.}
property Authoritative: Boolean read FAuthoritative;
{:@True, if answer is truncated to 512 bytes.}
property Truncated: Boolean read FTRuncated;
{:Detailed informations from name server reply. One record per line. Record
have comma delimited entries with type number, TTL and data filelds.
This information contains detailed information about query reply.}
property AnswerInfo: TStringList read FAnswerInfo;
{:Detailed informations from name server reply. One record per line. Record
have comma delimited entries with type number, TTL and data filelds.
This information contains detailed information about nameserver.}
property NameserverInfo: TStringList read FNameserverInfo;
{:Detailed informations from name server reply. One record per line. Record
have comma delimited entries with type number, TTL and data filelds.
This information contains detailed additional information.}
property AdditionalInfo: TStringList read FAdditionalInfo;
end;
{:A very useful function, and example of it's use is found in the TDNSSend object.
This function is used to get mail servers for a domain and sort them by
preference numbers. "Servers" contains only the domain names of the mail
servers in the right order (without preference number!). The first domain name
will always be the highest preferenced mail server. Returns boolean @TRUE if
all went well.}
function GetMailServers(const DNSHost, Domain: AnsiString;
const Servers: TStrings): Boolean;
implementation
constructor TDNSSend.Create;
begin
inherited Create;
FSock := TUDPBlockSocket.Create;
FSock.Owner := self;
FTCPSock := TTCPBlockSocket.Create;
FTCPSock.Owner := self;
FUseTCP := False;
FTimeout := 10000;
FTargetPort := cDnsProtocol;
FAnswerInfo := TStringList.Create;
FNameserverInfo := TStringList.Create;
FAdditionalInfo := TStringList.Create;
Randomize;
end;
destructor TDNSSend.Destroy;
begin
FAnswerInfo.Free;
FNameserverInfo.Free;
FAdditionalInfo.Free;
FTCPSock.Free;
FSock.Free;
inherited Destroy;
end;
function TDNSSend.CompressName(const Value: AnsiString): AnsiString;
var
n: Integer;
s: AnsiString;
begin
Result := '';
if Value = '' then
Result := #0
else
begin
s := '';
for n := 1 to Length(Value) do
if Value[n] = '.' then
begin
Result := Result + AnsiChar(Length(s)) + s;
s := '';
end
else
s := s + Value[n];
if s <> '' then
Result := Result + AnsiChar(Length(s)) + s;
Result := Result + #0;
end;
end;
function TDNSSend.CodeHeader: AnsiString;
begin
FID := Random(32767);
Result := CodeInt(FID); // ID
Result := Result + CodeInt($0100); // flags
Result := Result + CodeInt(1); // QDCount
Result := Result + CodeInt(0); // ANCount
Result := Result + CodeInt(0); // NSCount
Result := Result + CodeInt(0); // ARCount
end;
function TDNSSend.CodeQuery(const Name: AnsiString; QType: Integer): AnsiString;
begin
Result := CompressName(Name);
Result := Result + CodeInt(QType);
Result := Result + CodeInt(1); // Type INTERNET
end;
function TDNSSend.DecodeString(var From: Integer): AnsiString;
var
Len: integer;
begin
Len := Ord(FBuffer[From]);
Inc(From);
Result := Copy(FBuffer, From, Len);
Inc(From, Len);
end;
function TDNSSend.DecodeLabels(var From: Integer): AnsiString;
var
l, f: Integer;
begin
Result := '';
while True do
begin
if From >= Length(FBuffer) then
Break;
l := Ord(FBuffer[From]);
Inc(From);
if l = 0 then
Break;
if Result <> '' then
Result := Result + '.';
if (l and $C0) = $C0 then
begin
f := l and $3F;
f := f * 256 + Ord(FBuffer[From]) + 1;
Inc(From);
Result := Result + DecodeLabels(f);
Break;
end
else
begin
Result := Result + Copy(FBuffer, From, l);
Inc(From, l);
end;
end;
end;
function TDNSSend.DecodeResource(var i: Integer; const Info: TStringList;
QType: Integer): AnsiString;
var
Rname: AnsiString;
RType, Len, j, x, y, z, n: Integer;
R: AnsiString;
t1, t2, ttl: integer;
ip6: TIp6bytes;
begin
Result := '';
R := '';
Rname := DecodeLabels(i);
RType := DecodeInt(FBuffer, i);
Inc(i, 4);
t1 := DecodeInt(FBuffer, i);
Inc(i, 2);
t2 := DecodeInt(FBuffer, i);
Inc(i, 2);
ttl := t1 * 65536 + t2;
Len := DecodeInt(FBuffer, i);
Inc(i, 2); // i point to begin of data
j := i;
i := i + len; // i point to next record
if Length(FBuffer) >= (i - 1) then
case RType of
QTYPE_A:
begin
R := IntToStr(Ord(FBuffer[j]));
Inc(j);
R := R + '.' + IntToStr(Ord(FBuffer[j]));
Inc(j);
R := R + '.' + IntToStr(Ord(FBuffer[j]));
Inc(j);
R := R + '.' + IntToStr(Ord(FBuffer[j]));
end;
QTYPE_AAAA:
begin
for n := 0 to 15 do
ip6[n] := ord(FBuffer[j + n]);
R := IP6ToStr(ip6);
end;
QTYPE_NS, QTYPE_MD, QTYPE_MF, QTYPE_CNAME, QTYPE_MB,
QTYPE_MG, QTYPE_MR, QTYPE_PTR, QTYPE_X25, QTYPE_NSAP,
QTYPE_NSAPPTR:
R := DecodeLabels(j);
QTYPE_SOA:
begin
R := DecodeLabels(j);
R := R + ',' + DecodeLabels(j);
for n := 1 to 5 do
begin
x := DecodeInt(FBuffer, j) * 65536 + DecodeInt(FBuffer, j + 2);
Inc(j, 4);
R := R + ',' + IntToStr(x);
end;
end;
QTYPE_NULL:
begin
end;
QTYPE_WKS:
begin
end;
QTYPE_HINFO:
begin
R := DecodeString(j);
R := R + ',' + DecodeString(j);
end;
QTYPE_MINFO, QTYPE_RP, QTYPE_ISDN:
begin
R := DecodeLabels(j);
R := R + ',' + DecodeLabels(j);
end;
QTYPE_MX, QTYPE_AFSDB, QTYPE_RT, QTYPE_KX:
begin
x := DecodeInt(FBuffer, j);
Inc(j, 2);
R := IntToStr(x);
R := R + ',' + DecodeLabels(j);
end;
QTYPE_TXT, QTYPE_SPF:
begin
R := '';
while j < i do
R := R + DecodeString(j);
end;
QTYPE_GPOS:
begin
R := DecodeLabels(j);
R := R + ',' + DecodeLabels(j);
R := R + ',' + DecodeLabels(j);
end;
QTYPE_PX:
begin
x := DecodeInt(FBuffer, j);
Inc(j, 2);
R := IntToStr(x);
R := R + ',' + DecodeLabels(j);
R := R + ',' + DecodeLabels(j);
end;
QTYPE_SRV:
// Author: Dan <ml@mutox.org>
begin
x := DecodeInt(FBuffer, j);
Inc(j, 2);
y := DecodeInt(FBuffer, j);
Inc(j, 2);
z := DecodeInt(FBuffer, j);
Inc(j, 2);
R := IntToStr(x); // Priority
R := R + ',' + IntToStr(y); // Weight
R := R + ',' + IntToStr(z); // Port
R := R + ',' + DecodeLabels(j); // Server DNS Name
end;
end;
if R <> '' then
Info.Add(RName + ',' + IntToStr(RType) + ',' + IntToStr(ttl) + ',' + R);
if QType = RType then
Result := R;
end;
function TDNSSend.RecvTCPResponse(const WorkSock: TBlockSocket): AnsiString;
var
l: integer;
begin
Result := '';
l := WorkSock.recvbyte(FTimeout) * 256 + WorkSock.recvbyte(FTimeout);
if l > 0 then
Result := WorkSock.RecvBufferStr(l, FTimeout);
end;
function TDNSSend.DecodeResponse(const Buf: AnsiString; const Reply: TStrings;
QType: Integer):boolean;
var
n, i: Integer;
flag, qdcount, ancount, nscount, arcount: Integer;
s: AnsiString;
begin
Result := False;
Reply.Clear;
FAnswerInfo.Clear;
FNameserverInfo.Clear;
FAdditionalInfo.Clear;
FAuthoritative := False;
if (Length(Buf) > 13) and (FID = DecodeInt(Buf, 1)) then
begin
Result := True;
flag := DecodeInt(Buf, 3);
FRCode := Flag and $000F;
FAuthoritative := (Flag and $0400) > 0;
FTruncated := (Flag and $0200) > 0;
if FRCode = 0 then
begin
qdcount := DecodeInt(Buf, 5);
ancount := DecodeInt(Buf, 7);
nscount := DecodeInt(Buf, 9);
arcount := DecodeInt(Buf, 11);
i := 13; //begin of body
if (qdcount > 0) and (Length(Buf) > i) then //skip questions
for n := 1 to qdcount do
begin
while (Buf[i] <> #0) and ((Ord(Buf[i]) and $C0) <> $C0) do
Inc(i);
Inc(i, 5);
end;
if (ancount > 0) and (Length(Buf) > i) then // decode reply
for n := 1 to ancount do
begin
s := DecodeResource(i, FAnswerInfo, QType);
if s <> '' then
Reply.Add(s);
end;
if (nscount > 0) and (Length(Buf) > i) then // decode nameserver info
for n := 1 to nscount do
DecodeResource(i, FNameserverInfo, QType);
if (arcount > 0) and (Length(Buf) > i) then // decode additional info
for n := 1 to arcount do
DecodeResource(i, FAdditionalInfo, QType);
end;
end;
end;
function TDNSSend.DNSQuery(Name: AnsiString; QType: Integer;
const Reply: TStrings): Boolean;
var
WorkSock: TBlockSocket;
t: TStringList;
b: boolean;
begin
Result := False;
if IsIP(Name) then
Name := ReverseIP(Name) + '.in-addr.arpa';
if IsIP6(Name) then
Name := ReverseIP6(Name) + '.ip6.arpa';
FBuffer := CodeHeader + CodeQuery(Name, QType);
if FUseTCP then
WorkSock := FTCPSock
else
WorkSock := FSock;
WorkSock.Bind(FIPInterface, cAnyPort);
WorkSock.Connect(FTargetHost, FTargetPort);
if FUseTCP then
FBuffer := Codeint(length(FBuffer)) + FBuffer;
WorkSock.SendString(FBuffer);
if FUseTCP then
FBuffer := RecvTCPResponse(WorkSock)
else
FBuffer := WorkSock.RecvPacket(FTimeout);
if FUseTCP and (QType = QTYPE_AXFR) then //zone transfer
begin
t := TStringList.Create;
try
repeat
b := DecodeResponse(FBuffer, Reply, QType);
if (t.Count > 1) and (AnswerInfo.Count > 0) then //find end of transfer
b := b and (t[0] <> AnswerInfo[AnswerInfo.count - 1]);
if b then
begin
t.AddStrings(AnswerInfo);
FBuffer := RecvTCPResponse(WorkSock);
if FBuffer = '' then
Break;
if WorkSock.LastError <> 0 then
Break;
end;
until not b;
Reply.Assign(t);
Result := True;
finally
t.free;
end;
end
else //normal query
if WorkSock.LastError = 0 then
Result := DecodeResponse(FBuffer, Reply, QType);
end;
{==============================================================================}
function GetMailServers(const DNSHost, Domain: AnsiString;
const Servers: TStrings): Boolean;
var
DNS: TDNSSend;
t: TStringList;
n, m, x: Integer;
begin
Result := False;
Servers.Clear;
t := TStringList.Create;
DNS := TDNSSend.Create;
try
DNS.TargetHost := DNSHost;
if DNS.DNSQuery(Domain, QType_MX, t) then
begin
{ normalize preference number to 5 digits }
for n := 0 to t.Count - 1 do
begin
x := Pos(',', t[n]);
if x > 0 then
for m := 1 to 6 - x do
t[n] := '0' + t[n];
end;
{ sort server list }
t.Sorted := True;
{ result is sorted list without preference numbers }
for n := 0 to t.Count - 1 do
begin
x := Pos(',', t[n]);
Servers.Add(Copy(t[n], x + 1, Length(t[n]) - x));
end;
Result := True;
end;
finally
DNS.Free;
t.Free;
end;
end;
end.

2106
src/synapse/ftpsend.pas Normal file

File diff suppressed because it is too large Load diff

403
src/synapse/ftptsend.pas Normal file
View file

@ -0,0 +1,403 @@
{==============================================================================|
| Project : Ararat Synapse | 001.001.001 |
|==============================================================================|
| Content: Trivial FTP (TFTP) client and server |
|==============================================================================|
| Copyright (c)1999-2010, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2003-2010. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{: @abstract(TFTP client and server protocol)
Used RFC: RFC-1350
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$Q-}
{$H+}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit ftptsend;
interface
uses
SysUtils, Classes,
blcksock, synautil;
const
cTFTPProtocol = '69';
cTFTP_RRQ = word(1);
cTFTP_WRQ = word(2);
cTFTP_DTA = word(3);
cTFTP_ACK = word(4);
cTFTP_ERR = word(5);
type
{:@abstract(Implementation of TFTP client and server)
Note: Are you missing properties for specify server address and port? Look to
parent @link(TSynaClient) too!}
TTFTPSend = class(TSynaClient)
private
FSock: TUDPBlockSocket;
FErrorCode: integer;
FErrorString: string;
FData: TMemoryStream;
FRequestIP: string;
FRequestPort: string;
function SendPacket(Cmd: word; Serial: word; const Value: string): Boolean;
function RecvPacket(Serial: word; var Value: string): Boolean;
public
constructor Create;
destructor Destroy; override;
{:Upload @link(data) as file to TFTP server.}
function SendFile(const Filename: string): Boolean;
{:Download file from TFTP server to @link(data).}
function RecvFile(const Filename: string): Boolean;
{:Acts as TFTP server and wait for client request. When some request
incoming within Timeout, result is @true and parametres is filled with
information from request. You must handle this request, validate it, and
call @link(ReplyError), @link(ReplyRecv) or @link(ReplySend) for send reply
to TFTP Client.}
function WaitForRequest(var Req: word; var filename: string): Boolean;
{:send error to TFTP client, when you acts as TFTP server.}
procedure ReplyError(Error: word; Description: string);
{:Accept uploaded file from TFTP client to @link(data), when you acts as
TFTP server.}
function ReplyRecv: Boolean;
{:Accept download request file from TFTP client and send content of
@link(data), when you acts as TFTP server.}
function ReplySend: Boolean;
published
{:Code of TFTP error.}
property ErrorCode: integer read FErrorCode;
{:Human readable decription of TFTP error. (if is sended by remote side)}
property ErrorString: string read FErrorString;
{:MemoryStream with datas for sending or receiving}
property Data: TMemoryStream read FData;
{:Address of TFTP remote side.}
property RequestIP: string read FRequestIP write FRequestIP;
{:Port of TFTP remote side.}
property RequestPort: string read FRequestPort write FRequestPort;
end;
implementation
constructor TTFTPSend.Create;
begin
inherited Create;
FSock := TUDPBlockSocket.Create;
FSock.Owner := self;
FTargetPort := cTFTPProtocol;
FData := TMemoryStream.Create;
FErrorCode := 0;
FErrorString := '';
end;
destructor TTFTPSend.Destroy;
begin
FSock.Free;
FData.Free;
inherited Destroy;
end;
function TTFTPSend.SendPacket(Cmd: word; Serial: word; const Value: string): Boolean;
var
s, sh: string;
begin
FErrorCode := 0;
FErrorString := '';
Result := false;
if Cmd <> 2 then
s := CodeInt(Cmd) + CodeInt(Serial) + Value
else
s := CodeInt(Cmd) + Value;
FSock.SendString(s);
s := FSock.RecvPacket(FTimeout);
if FSock.LastError = 0 then
if length(s) >= 4 then
begin
sh := CodeInt(4) + CodeInt(Serial);
if Pos(sh, s) = 1 then
Result := True
else
if s[1] = #5 then
begin
FErrorCode := DecodeInt(s, 3);
Delete(s, 1, 4);
FErrorString := SeparateLeft(s, #0);
end;
end;
end;
function TTFTPSend.RecvPacket(Serial: word; var Value: string): Boolean;
var
s: string;
ser: word;
begin
FErrorCode := 0;
FErrorString := '';
Result := False;
Value := '';
s := FSock.RecvPacket(FTimeout);
if FSock.LastError = 0 then
if length(s) >= 4 then
if DecodeInt(s, 1) = 3 then
begin
ser := DecodeInt(s, 3);
if ser = Serial then
begin
Delete(s, 1, 4);
Value := s;
S := CodeInt(4) + CodeInt(ser);
FSock.SendString(s);
Result := FSock.LastError = 0;
end
else
begin
S := CodeInt(5) + CodeInt(5) + 'Unexcepted serial#' + #0;
FSock.SendString(s);
end;
end;
if DecodeInt(s, 1) = 5 then
begin
FErrorCode := DecodeInt(s, 3);
Delete(s, 1, 4);
FErrorString := SeparateLeft(s, #0);
end;
end;
function TTFTPSend.SendFile(const Filename: string): Boolean;
var
s: string;
ser: word;
n, n1, n2: integer;
begin
Result := False;
FErrorCode := 0;
FErrorString := '';
FSock.CloseSocket;
FSock.Connect(FTargetHost, FTargetPort);
try
if FSock.LastError = 0 then
begin
s := Filename + #0 + 'octet' + #0;
if not Sendpacket(2, 0, s) then
Exit;
ser := 1;
FData.Position := 0;
n1 := FData.Size div 512;
n2 := FData.Size mod 512;
for n := 1 to n1 do
begin
s := ReadStrFromStream(FData, 512);
// SetLength(s, 512);
// FData.Read(pointer(s)^, 512);
if not Sendpacket(3, ser, s) then
Exit;
inc(ser);
end;
s := ReadStrFromStream(FData, n2);
// SetLength(s, n2);
// FData.Read(pointer(s)^, n2);
if not Sendpacket(3, ser, s) then
Exit;
Result := True;
end;
finally
FSock.CloseSocket;
end;
end;
function TTFTPSend.RecvFile(const Filename: string): Boolean;
var
s: string;
ser: word;
begin
Result := False;
FErrorCode := 0;
FErrorString := '';
FSock.CloseSocket;
FSock.Connect(FTargetHost, FTargetPort);
try
if FSock.LastError = 0 then
begin
s := CodeInt(1) + Filename + #0 + 'octet' + #0;
FSock.SendString(s);
if FSock.LastError <> 0 then
Exit;
FData.Clear;
ser := 1;
repeat
if not RecvPacket(ser, s) then
Exit;
inc(ser);
WriteStrToStream(FData, s);
// FData.Write(pointer(s)^, length(s));
until length(s) <> 512;
FData.Position := 0;
Result := true;
end;
finally
FSock.CloseSocket;
end;
end;
function TTFTPSend.WaitForRequest(var Req: word; var filename: string): Boolean;
var
s: string;
begin
Result := False;
FErrorCode := 0;
FErrorString := '';
FSock.CloseSocket;
FSock.Bind('0.0.0.0', FTargetPort);
if FSock.LastError = 0 then
begin
s := FSock.RecvPacket(FTimeout);
if FSock.LastError = 0 then
if Length(s) >= 4 then
begin
FRequestIP := FSock.GetRemoteSinIP;
FRequestPort := IntToStr(FSock.GetRemoteSinPort);
Req := DecodeInt(s, 1);
delete(s, 1, 2);
filename := Trim(SeparateLeft(s, #0));
s := SeparateRight(s, #0);
s := SeparateLeft(s, #0);
Result := lowercase(trim(s)) = 'octet';
end;
end;
end;
procedure TTFTPSend.ReplyError(Error: word; Description: string);
var
s: string;
begin
FSock.CloseSocket;
FSock.Connect(FRequestIP, FRequestPort);
s := CodeInt(5) + CodeInt(Error) + Description + #0;
FSock.SendString(s);
FSock.CloseSocket;
end;
function TTFTPSend.ReplyRecv: Boolean;
var
s: string;
ser: integer;
begin
Result := False;
FErrorCode := 0;
FErrorString := '';
FSock.CloseSocket;
FSock.Connect(FRequestIP, FRequestPort);
try
s := CodeInt(4) + CodeInt(0);
FSock.SendString(s);
FData.Clear;
ser := 1;
repeat
if not RecvPacket(ser, s) then
Exit;
inc(ser);
WriteStrToStream(FData, s);
// FData.Write(pointer(s)^, length(s));
until length(s) <> 512;
FData.Position := 0;
Result := true;
finally
FSock.CloseSocket;
end;
end;
function TTFTPSend.ReplySend: Boolean;
var
s: string;
ser: word;
n, n1, n2: integer;
begin
Result := False;
FErrorCode := 0;
FErrorString := '';
FSock.CloseSocket;
FSock.Connect(FRequestIP, FRequestPort);
try
ser := 1;
FData.Position := 0;
n1 := FData.Size div 512;
n2 := FData.Size mod 512;
for n := 1 to n1 do
begin
s := ReadStrFromStream(FData, 512);
// SetLength(s, 512);
// FData.Read(pointer(s)^, 512);
if not Sendpacket(3, ser, s) then
Exit;
inc(ser);
end;
s := ReadStrFromStream(FData, n2);
// SetLength(s, n2);
// FData.Read(pointer(s)^, n2);
if not Sendpacket(3, ser, s) then
Exit;
Result := True;
finally
FSock.CloseSocket;
end;
end;
{==============================================================================}
end.

890
src/synapse/httpsend.pas Normal file
View file

@ -0,0 +1,890 @@
{==============================================================================|
| Project : Ararat Synapse | 003.013.000 |
|==============================================================================|
| Content: HTTP client |
|==============================================================================|
| Copyright (c)1999-2021, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c) 1999-2021. |
| Portions created by Pepak are Copyright (c) 2020-2021. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{:@abstract(HTTP protocol client)
Used RFC: RFC-1867, RFC-1947, RFC-2388, RFC-2616
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
//old Delphi does not have MSWINDOWS define.
{$IFDEF WIN32}
{$IFNDEF MSWINDOWS}
{$DEFINE MSWINDOWS}
{$ENDIF}
{$ENDIF}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
{$IFDEF NEXTGEN}
{$ZEROBASEDSTRINGS OFF}
{$ENDIF}
unit httpsend;
interface
uses
SysUtils, Classes,
blcksock, synautil, synaip, synacode, synsock
{$IFDEF NEXTGEN}
,synafpc
{$ENDIF};
const
cHttpProtocol = '80';
type
{:These encoding types are used internally by the THTTPSend object to identify
the transfer data types.}
TTransferEncoding = (TE_UNKNOWN, TE_IDENTITY, TE_CHUNKED);
{:abstract(Implementation of HTTP protocol.)}
THTTPSend = class(TSynaClient)
protected
FSock: TTCPBlockSocket;
FTransferEncoding: TTransferEncoding;
FAliveHost: string;
FAlivePort: string;
FHeaders: TStringList;
FDocument: TMemoryStream;
FMimeType: string;
FProtocol: string;
FKeepAlive: Boolean;
FKeepAliveTimeout: integer;
FStatus100: Boolean;
FProxyHost: string;
FProxyPort: string;
FProxyUser: string;
FProxyPass: string;
FResultCode: Integer;
FResultString: string;
FUserAgent: string;
FCookies: TStringList;
FDownloadSize: int64;
FUploadSize: int64;
FRangeStart: int64;
FRangeEnd: int64;
FAddPortNumberToHost: Boolean;
FInputStream, FOutputStream: TStream;
function ReadUnknown: Boolean; virtual;
function ReadIdentity(Size: int64): Boolean; virtual;
function ReadChunked: Boolean; virtual;
procedure ParseCookies;
function PrepareHeaders: AnsiString;
function InternalDoConnect(needssl: Boolean): Boolean;
function InternalConnect(needssl: Boolean): Boolean;
function InputDocument: TStream;
function OutputDocument: TStream;
public
constructor Create;
destructor Destroy; override;
{:Reset headers, document and Mimetype.}
procedure Clear;
{:Decode ResultCode and ResultString from Value.}
procedure DecodeStatus(const Value: string);
{:Connects to host defined in URL and accesses resource defined in URL by
method. If Document is not empty, send it to the server as part of the HTTP
request. Server response is in Document and headers. Connection may be
authorised by username and password in URL. If you define proxy properties,
connection is made by this proxy.
If all OK, result is @true, else result is @false.
If you use 'https:' instead of 'http:' in the URL, your request is made
by SSL/TLS connection (if you do not specify port, then port 443 is used
instead of standard port 80). If you use SSL/TLS request and you have
defined HTTP proxy, then HTTP-tunnel mode is automatically used .}
function HTTPMethod(const Method, URL: string): Boolean;
{:You can call this method from OnStatus event to break current data
transfer. (or from another thread.)}
procedure Abort;
published
{:Before HTTP operation you may define any non-standard headers for HTTP
request, except: 'Expect: 100-continue', 'Content-Length', 'Content-Type',
'Connection', 'Authorization', 'Proxy-Authorization' and 'Host' headers.
After HTTP operation, it contains full headers of the returned document.}
property Headers: TStringList read FHeaders;
{:Stringlist with name-value stringlist pairs. Each pair is one cookie.
After the HTTP request is returned, cookies are parsed to this stringlist.
You can leave these cookies untouched for next HTTP requests. You can also
save this stringlist for later use.}
property Cookies: TStringList read FCookies;
{:Stream with document to send (before request), or with document received
from HTTP server (after request).}
property Document: TMemoryStream read FDocument;
{:If you need to download only part of a requested document, specify here
the position of subpart begin. If 0, the full document is requested.}
property RangeStart: int64 read FRangeStart Write FRangeStart;
{:If you need to download only part of a requested document, specify here
the position of subpart end. If 0, the document from rangeStart to end of
document is requested.
(Useful for resuming broken downloads, for example.)}
property RangeEnd: int64 read FRangeEnd Write FRangeEnd;
{:Mime type of sending data. Default is: 'text/html'.}
property MimeType: string read FMimeType Write FMimeType;
{:Define protocol version. Possible values are: '1.1', '1.0' (default)
and '0.9'.}
property Protocol: string read FProtocol Write FProtocol;
{:If @true (default value), keepalives in HTTP protocol 1.1 is enabled.}
property KeepAlive: Boolean read FKeepAlive Write FKeepAlive;
{:Define timeout for keepalives in seconds!}
property KeepAliveTimeout: integer read FKeepAliveTimeout Write FKeepAliveTimeout;
{:if @true, then the server is requested for 100status capability when
uploading data. Default is @false (off).}
property Status100: Boolean read FStatus100 Write FStatus100;
{:Address of proxy server (IP address or domain name) where you want to
connect in @link(HTTPMethod) method.}
property ProxyHost: string read FProxyHost Write FProxyHost;
{:Port number for proxy connection. Default value is 8080.}
property ProxyPort: string read FProxyPort Write FProxyPort;
{:Username for connection to proxy server used in HTTPMethod method.}
property ProxyUser: string read FProxyUser Write FProxyUser;
{:Password for connection to proxy server used in HTTPMethod method.}
property ProxyPass: string read FProxyPass Write FProxyPass;
{:Here you can specify custom User-Agent identification.
Default: 'Mozilla/4.0 (compatible; Synapse)'}
property UserAgent: string read FUserAgent Write FUserAgent;
{:Operation result code after successful @link(HTTPMethod) method.}
property ResultCode: Integer read FResultCode;
{:Operation result string after successful @link(HTTPMethod) method.}
property ResultString: string read FResultString;
{:if this value is not 0, then data download is pending. In this case you
have here the total size of downloaded data. Useful for drawing download
progressbar from OnStatus event.}
property DownloadSize: int64 read FDownloadSize;
{:if this value is not 0, then data upload is pending. In this case you have
here the total size of uploaded data. Useful for drawing upload progressbar
from OnStatus event.}
property UploadSize: int64 read FUploadSize;
{:Socket object used for TCP/IP operation.
Good for setting OnStatus hook, etc.}
property Sock: TTCPBlockSocket read FSock;
{:Allows to switch off port number in 'Host:' HTTP header. By default @TRUE.
Some buggy servers do not like port informations in this header.}
property AddPortNumberToHost: Boolean read FAddPortNumberToHost write FAddPortNumberToHost;
public
{:for direct sending from any TStream. Defalut nil = use Document property instead.}
property InputStream: TStream read FInputStream write FInputStream;
{:for direct dovnloading into any TStream. Defalut nil = use Document property instead.}
property OutputStream: TStream read FOutputStream write FOutputStream;
end;
{:A very useful function, and example of use can be found in the THTTPSend
object. It implements the GET method of the HTTP protocol. This function sends
the GET method for URL document to an HTTP server. Returned document is in the
"Response" stringlist (without any headers). Returns boolean TRUE if all went
well.}
function HttpGetText(const URL: string; const Response: TStrings): Boolean;
{:A very useful function, and example of use can be found in the THTTPSend
object. It implements the GET method of the HTTP protocol. This function sends
the GET method for URL document to an HTTP server. Returned document is in the
"Response" stream. Returns boolean TRUE if all went well.}
function HttpGetBinary(const URL: string; const Response: TStream): Boolean;
{:A very useful function, and example of use can be found in the THTTPSend
object. It implements the POST method of the HTTP protocol. This function sends
the SEND method for a URL document to an HTTP server. The document to be sent
is located in the "Data" stream. The returned document is in the "Data" stream.
Returns boolean TRUE if all went well.}
function HttpPostBinary(const URL: string; const Data: TStream): Boolean;
{:A very useful function, and example of use can be found in the THTTPSend
object. It implements the POST method of the HTTP protocol. This function is
good for POSTing form data. It sends the POST method for a URL document to
an HTTP server. You must prepare the form data in the same manner as you would
the URL data, and pass this prepared data to "URLdata". The following is
a sample of how the data would appear: 'name=Lukas&field1=some%20data'.
The information in the field must be encoded by the EncodeURLElement function.
The returned document is in the "Data" stream. Returns boolean TRUE if all
went well.}
function HttpPostURL(const URL, URLData: string; const Data: TStream): Boolean;
{:A very useful function, and example of use can be found in the THTTPSend
object. It implements the POST method of the HTTP protocol. This function sends
the POST method for a URL document to an HTTP server. This function simulates
posting of file by HTML form using the 'multipart/form-data' method. The posted
file is in the DATA stream. Its name is Filename string. Fieldname is for the
name of the form field with the file. (simulates HTML INPUT FILE) The returned
document is in the ResultData Stringlist. Returns boolean TRUE if all
went well.}
function HttpPostFile(const URL, FieldName, FileName: string;
const Data: TStream; const ResultData: TStrings): Boolean;
implementation
constructor THTTPSend.Create;
begin
inherited Create;
FHeaders := TStringList.Create;
FCookies := TStringList.Create;
FDocument := TMemoryStream.Create;
FSock := TTCPBlockSocket.Create;
FSock.Owner := self;
FSock.ConvertLineEnd := True;
FSock.SizeRecvBuffer := c64k;
FSock.SizeSendBuffer := c64k;
FTimeout := 90000;
FTargetPort := cHttpProtocol;
FProxyHost := '';
FProxyPort := '8080';
FProxyUser := '';
FProxyPass := '';
FAliveHost := '';
FAlivePort := '';
FProtocol := '1.0';
FKeepAlive := True;
FStatus100 := False;
FUserAgent := 'Mozilla/4.0 (compatible; Synapse)';
FDownloadSize := 0;
FUploadSize := 0;
FAddPortNumberToHost := true;
FKeepAliveTimeout := 300;
FInputStream := nil;
FOutputStream := nil;
Clear;
end;
destructor THTTPSend.Destroy;
begin
FSock.Free;
FDocument.Free;
FCookies.Free;
FHeaders.Free;
inherited Destroy;
end;
function THTTPSend.InputDocument: TStream;
begin
if InputStream <> nil then
Result := InputStream
else
Result := Document;
end;
function THTTPSend.OutputDocument: TStream;
begin
if OutputStream <> nil then
Result := OutputStream
else
Result := Document;
end;
procedure THTTPSend.Clear;
begin
FRangeStart := 0;
FRangeEnd := 0;
FDocument.Clear;
InputDocument.Size := 0;
OutputDocument.Size := 0;
FHeaders.Clear;
FMimeType := 'text/html';
end;
procedure THTTPSend.DecodeStatus(const Value: string);
var
s, su: string;
begin
s := Trim(SeparateRight(Value, ' '));
su := Trim(SeparateLeft(s, ' '));
FResultCode := StrToIntDef(su, 0);
FResultString := Trim(SeparateRight(s, ' '));
if FResultString = s then
FResultString := '';
end;
function THTTPSend.PrepareHeaders: AnsiString;
begin
if FProtocol = '0.9' then
Result := FHeaders[0] + CRLF
else
{$IFNDEF MSWINDOWS}
Result := {$IFDEF UNICODE}AnsiString{$ENDIF}(AdjustLineBreaks(FHeaders.Text, tlbsCRLF));
{$ELSE}
Result := FHeaders.Text;
{$ENDIF}
end;
function THTTPSend.InternalDoConnect(needssl: Boolean): Boolean;
begin
Result := False;
FSock.CloseSocket;
FSock.Bind(FIPInterface, cAnyPort);
if FSock.LastError <> 0 then
Exit;
FSock.Connect(FTargetHost, FTargetPort);
if FSock.LastError <> 0 then
Exit;
if needssl then
begin
if (FSock.SSL.SNIHost='') then
FSock.SSL.SNIHost:=FTargetHost;
FSock.SSLDoConnect;
FSock.SSL.SNIHost:=''; //don't need it anymore and don't wan't to reuse it in next connection
if FSock.LastError <> 0 then
Exit;
end;
FAliveHost := FTargetHost;
FAlivePort := FTargetPort;
Result := True;
end;
function THTTPSend.InternalConnect(needssl: Boolean): Boolean;
begin
if FSock.Socket = INVALID_SOCKET then
Result := InternalDoConnect(needssl)
else
if (FAliveHost <> FTargetHost) or (FAlivePort <> FTargetPort)
or FSock.CanRead(0) then
Result := InternalDoConnect(needssl)
else
Result := True;
end;
function THTTPSend.HTTPMethod(const Method, URL: string): Boolean;
var
Sending, Receiving: Boolean;
status100: Boolean;
status100error: string;
ToClose: Boolean;
Size: int64;
Prot, User, Pass, Host, Port, Path, Para, URI: string;
s, su: AnsiString;
HttpTunnel: Boolean;
n: integer;
pp: string;
UsingProxy: boolean;
l: TStringList;
x: integer;
begin
{initial values}
Result := False;
FResultCode := 500;
FResultString := '';
FDownloadSize := 0;
FUploadSize := 0;
URI := ParseURL(trim(URL), Prot, User, Pass, Host, Port, Path, Para);
User := DecodeURL(user);
Pass := DecodeURL(pass);
if User = '' then
begin
User := FUsername;
Pass := FPassword;
end;
if UpperCase(Prot) = 'HTTPS' then
begin
HttpTunnel := FProxyHost <> '';
FSock.HTTPTunnelIP := FProxyHost;
FSock.HTTPTunnelPort := FProxyPort;
FSock.HTTPTunnelUser := FProxyUser;
FSock.HTTPTunnelPass := FProxyPass;
end
else
begin
HttpTunnel := False;
FSock.HTTPTunnelIP := '';
FSock.HTTPTunnelPort := '';
FSock.HTTPTunnelUser := '';
FSock.HTTPTunnelPass := '';
end;
UsingProxy := (FProxyHost <> '') and not(HttpTunnel);
Sending := InputDocument.Size > 0;
{Headers for Sending data}
status100 := FStatus100 and Sending and (FProtocol = '1.1');
if status100 then
FHeaders.Insert(0, 'Expect: 100-continue');
if Sending then
begin
FHeaders.Insert(0, 'Content-Length: ' + IntToStr(InputDocument.Size));
if FMimeType <> '' then
FHeaders.Insert(0, 'Content-Type: ' + FMimeType);
end;
{ setting User-agent }
if FUserAgent <> '' then
FHeaders.Insert(0, 'User-Agent: ' + FUserAgent);
{ setting Ranges }
if (FRangeStart > 0) or (FRangeEnd > 0) then
begin
if FRangeEnd >= FRangeStart then
FHeaders.Insert(0, 'Range: bytes=' + IntToStr(FRangeStart) + '-' + IntToStr(FRangeEnd))
else
FHeaders.Insert(0, 'Range: bytes=' + IntToStr(FRangeStart) + '-');
end;
{ setting Cookies }
s := '';
for n := 0 to FCookies.Count - 1 do
begin
if s <> '' then
s := s + '; ';
s := s + FCookies[n];
end;
if s <> '' then
FHeaders.Insert(0, 'Cookie: ' + s);
{ setting KeepAlives }
pp := '';
if UsingProxy then
pp := 'Proxy-';
if FKeepAlive then
begin
FHeaders.Insert(0, pp + 'Connection: keep-alive');
FHeaders.Insert(0, 'Keep-Alive: ' + IntToStr(FKeepAliveTimeout));
end
else
FHeaders.Insert(0, pp + 'Connection: close');
{ set target servers/proxy, authorizations, etc... }
if User <> '' then
FHeaders.Insert(0, 'Authorization: Basic ' + EncodeBase64(User + ':' + Pass));
if UsingProxy and (FProxyUser <> '') then
FHeaders.Insert(0, 'Proxy-Authorization: Basic ' +
EncodeBase64(FProxyUser + ':' + FProxyPass));
if isIP6(Host) then
s := '[' + Host + ']'
else
s := Host;
if FAddPortNumberToHost
and (((Port <> '80') and (UpperCase(Prot) = 'HTTP'))
or ((Port <> '443') and (UpperCase(Prot) = 'HTTPS'))) then
FHeaders.Insert(0, 'Host: ' + s + ':' + Port)
else
FHeaders.Insert(0, 'Host: ' + s);
if UsingProxy then
URI := Prot + '://' + s + ':' + Port + URI;
if URI = '/*' then
URI := '*';
if FProtocol = '0.9' then
FHeaders.Insert(0, UpperCase(Method) + ' ' + URI)
else
FHeaders.Insert(0, UpperCase(Method) + ' ' + URI + ' HTTP/' + FProtocol);
if UsingProxy then
begin
FTargetHost := FProxyHost;
FTargetPort := FProxyPort;
end
else
begin
FTargetHost := Host;
FTargetPort := Port;
end;
if FHeaders[FHeaders.Count - 1] <> '' then
FHeaders.Add('');
{ connect }
if not InternalConnect(UpperCase(Prot) = 'HTTPS') then
begin
FAliveHost := '';
FAlivePort := '';
Exit;
end;
{ reading Status }
InputDocument.Position := 0;
Status100Error := '';
if status100 then
begin
{ send Headers }
FSock.SendString(PrepareHeaders);
if FSock.LastError <> 0 then
Exit;
repeat
s := FSock.RecvString(FTimeout);
if s <> '' then
Break;
until FSock.LastError <> 0;
DecodeStatus(s);
Status100Error := s;
repeat
s := FSock.recvstring(FTimeout);
if s = '' then
Break;
until FSock.LastError <> 0;
if (FResultCode >= 100) and (FResultCode < 200) then
begin
{ we can upload content }
Status100Error := '';
FUploadSize := InputDocument.Size;
FSock.SendStreamRaw(InputDocument);
end;
end
else
{ upload content }
if sending then
begin
if InputDocument.Size >= c64k then
begin
FSock.SendString(PrepareHeaders);
FUploadSize := InputDocument.Size;
FSock.SendStreamRaw(InputDocument);
end
else
begin
s := PrepareHeaders + ReadStrFromStream(InputDocument, InputDocument.Size);
FUploadSize := Length(s);
FSock.SendString(s);
end;
end
else
begin
{ we not need to upload document, send headers only }
FSock.SendString(PrepareHeaders);
end;
if FSock.LastError <> 0 then
Exit;
Clear;
Size := -1;
FTransferEncoding := TE_UNKNOWN;
{ read status }
if Status100Error = '' then
begin
repeat
repeat
s := FSock.RecvString(FTimeout);
if s <> '' then
Break;
until FSock.LastError <> 0;
if Pos('HTTP/', UpperCase(s)) = 1 then
begin
FHeaders.Add(s);
DecodeStatus(s);
end
else
begin
{ old HTTP 0.9 and some buggy servers not send result }
s := s + CRLF;
WriteStrToStream(OutputDocument, s);
FResultCode := 0;
end;
until (FSock.LastError <> 0) or (FResultCode <> 100);
end
else
FHeaders.Add(Status100Error);
{ if need receive headers, receive and parse it }
ToClose := FProtocol <> '1.1';
if FHeaders.Count > 0 then
begin
l := TStringList.Create;
try
repeat
s := FSock.RecvString(FTimeout);
l.Add(s);
if s = '' then
Break;
until FSock.LastError <> 0;
x := 0;
while l.Count > x do
begin
s := NormalizeHeader(l, x);
FHeaders.Add(s);
su := UpperCase(s);
if Pos('CONTENT-LENGTH:', su) = 1 then
begin
Size := StrToInt64Def(Trim(SeparateRight(s, ':')), -1);
if (Size <> -1) and (FTransferEncoding = TE_UNKNOWN) then
FTransferEncoding := TE_IDENTITY;
end;
if Pos('CONTENT-TYPE:', su) = 1 then
FMimeType := Trim(SeparateRight(s, ':'));
if Pos('TRANSFER-ENCODING:', su) = 1 then
begin
s := Trim(SeparateRight(su, ':'));
if Pos('CHUNKED', s) > 0 then
FTransferEncoding := TE_CHUNKED;
end;
if UsingProxy then
begin
if Pos('PROXY-CONNECTION:', su) = 1 then
if Pos('CLOSE', su) > 0 then
ToClose := True;
end
else
begin
if Pos('CONNECTION:', su) = 1 then
if Pos('CLOSE', su) > 0 then
ToClose := True;
end;
end;
finally
l.free;
end;
end;
Result := FSock.LastError = 0;
if not Result then
begin
FSock.CloseSocket;
FAliveHost := '';
FAlivePort := '';
Exit;
end;
{if need receive response body, read it}
Receiving := Method <> 'HEAD';
Receiving := Receiving and (FResultCode <> 204);
Receiving := Receiving and (FResultCode <> 304);
if Receiving then
case FTransferEncoding of
TE_UNKNOWN:
Result := ReadUnknown;
TE_IDENTITY:
Result := ReadIdentity(Size);
TE_CHUNKED:
Result := ReadChunked;
end;
OutputDocument.Position := 0;
if ToClose then
begin
FSock.CloseSocket;
FAliveHost := '';
FAlivePort := '';
end;
ParseCookies;
end;
function THTTPSend.ReadUnknown: Boolean;
var
s: ansistring;
begin
Result := false;
repeat
s := FSock.RecvPacket(FTimeout);
if FSock.LastError = 0 then
WriteStrToStream(OutputDocument, s);
until FSock.LastError <> 0;
if FSock.LastError = WSAECONNRESET then
begin
Result := true;
FSock.ResetLastError;
end;
end;
function THTTPSend.ReadIdentity(Size: int64): Boolean;
begin
if Size > 0 then
begin
FDownloadSize := Size;
FSock.RecvStreamSize(OutputDocument, FTimeout, Size);
OutputDocument.Position := OutputDocument.Size;
Result := FSock.LastError = 0;
end
else
Result := true;
end;
function THTTPSend.ReadChunked: Boolean;
var
s: ansistring;
Size: int64;
begin
repeat
repeat
s := FSock.RecvString(FTimeout);
until (s <> '') or (FSock.LastError <> 0);
if FSock.LastError <> 0 then
Break;
s := Trim(SeparateLeft(s, ' '));
s := Trim(SeparateLeft(s, ';'));
Size := StrToInt64Def('$' + s, 0);
if Size = 0 then
Break;
if not ReadIdentity(Size) then
break;
until False;
Result := FSock.LastError = 0;
end;
procedure THTTPSend.ParseCookies;
var
n: integer;
s: string;
sn, sv: string;
begin
for n := 0 to FHeaders.Count - 1 do
if Pos('set-cookie:', lowercase(FHeaders[n])) = 1 then
begin
s := SeparateRight(FHeaders[n], ':');
s := trim(SeparateLeft(s, ';'));
sn := trim(SeparateLeft(s, '='));
sv := trim(SeparateRight(s, '='));
FCookies.Values[sn] := sv;
end;
end;
procedure THTTPSend.Abort;
begin
FSock.StopFlag := True;
end;
{==============================================================================}
function HttpGetText(const URL: string; const Response: TStrings): Boolean;
var
HTTP: THTTPSend;
begin
HTTP := THTTPSend.Create;
try
Result := HTTP.HTTPMethod('GET', URL);
if Result then
Response.LoadFromStream(HTTP.Document);
finally
HTTP.Free;
end;
end;
function HttpGetBinary(const URL: string; const Response: TStream): Boolean;
var
HTTP: THTTPSend;
begin
HTTP := THTTPSend.Create;
try
Result := HTTP.HTTPMethod('GET', URL);
if Result then
begin
Response.Position := 0;
Response.CopyFrom(HTTP.Document, 0);
end;
finally
HTTP.Free;
end;
end;
function HttpPostBinary(const URL: string; const Data: TStream): Boolean;
var
HTTP: THTTPSend;
begin
HTTP := THTTPSend.Create;
try
HTTP.Document.CopyFrom(Data, 0);
HTTP.MimeType := 'Application/octet-stream';
Result := HTTP.HTTPMethod('POST', URL);
Data.Size := 0;
if Result then
begin
Data.Position := 0;
Data.CopyFrom(HTTP.Document, 0);
end;
finally
HTTP.Free;
end;
end;
function HttpPostURL(const URL, URLData: string; const Data: TStream): Boolean;
var
HTTP: THTTPSend;
begin
HTTP := THTTPSend.Create;
try
WriteStrToStream(HTTP.Document, URLData);
HTTP.MimeType := 'application/x-www-form-urlencoded';
Result := HTTP.HTTPMethod('POST', URL);
if Result then
Data.CopyFrom(HTTP.Document, 0);
finally
HTTP.Free;
end;
end;
function HttpPostFile(const URL, FieldName, FileName: string;
const Data: TStream; const ResultData: TStrings): Boolean;
var
HTTP: THTTPSend;
Bound, s: string;
begin
Bound := IntToHex(Random(MaxInt), 8) + '_Synapse_boundary';
HTTP := THTTPSend.Create;
try
s := '--' + Bound + CRLF;
s := s + 'content-disposition: form-data; name="' + FieldName + '";';
s := s + ' filename="' + FileName +'"' + CRLF;
s := s + 'Content-Type: Application/octet-string' + CRLF + CRLF;
WriteStrToStream(HTTP.Document, s);
HTTP.Document.CopyFrom(Data, 0);
s := CRLF + '--' + Bound + '--' + CRLF;
WriteStrToStream(HTTP.Document, s);
HTTP.MimeType := 'multipart/form-data; boundary=' + Bound;
Result := HTTP.HTTPMethod('POST', URL);
if Result then
ResultData.LoadFromStream(HTTP.Document);
finally
HTTP.Free;
end;
end;
end.

871
src/synapse/imapsend.pas Normal file
View file

@ -0,0 +1,871 @@
{==============================================================================|
| Project : Ararat Synapse | 002.005.004 |
|==============================================================================|
| Content: IMAP4rev1 client |
|==============================================================================|
| Copyright (c)1999-2015, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2001-2015. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{:@abstract(IMAP4 rev1 protocol client)
Used RFC: RFC-2060, RFC-2595
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$WARN IMPLICIT_STRING_CAST_LOSS OFF}
{$ENDIF}
unit imapsend;
interface
uses
SysUtils, Classes,
blcksock, synautil;
const
cIMAPProtocol = '143';
type
{:@abstract(Implementation of IMAP4 protocol.)
Note: Are you missing properties for setting Username and Password? Look to
parent @link(TSynaClient) object!
Are you missing properties for specify server address and port? Look to
parent @link(TSynaClient) too!}
TIMAPSend = class(TSynaClient)
protected
FSock: TTCPBlockSocket;
FTagCommand: integer;
FResultString: string;
FFullResult: TStringList;
FIMAPcap: TStringList;
FAuthDone: Boolean;
FSelectedFolder: string;
FSelectedCount: integer;
FSelectedRecent: integer;
FSelectedUIDvalidity: integer;
FUID: Boolean;
FAutoTLS: Boolean;
FFullSSL: Boolean;
function ReadResult: string;
function AuthLogin: Boolean;
function Connect: Boolean;
procedure ParseMess(Value:TStrings);
procedure ParseFolderList(Value:TStrings);
procedure ParseSelect;
procedure ParseSearch(Value:TStrings);
procedure ProcessLiterals;
public
constructor Create;
destructor Destroy; override;
{:By this function you can call any IMAP command. Result of this command is
in adequate properties.}
function IMAPcommand(Value: string): string;
{:By this function you can call any IMAP command what need upload any data.
Result of this command is in adequate properties.}
function IMAPuploadCommand(Value: string; const Data:TStrings): string;
{:Call CAPABILITY command and fill IMAPcap property by new values.}
function Capability: Boolean;
{:Connect to IMAP server and do login to this server. This command begin
session.}
function Login: Boolean;
{:Disconnect from IMAP server and terminate session session. If exists some
deleted and non-purged messages, these messages are not deleted!}
function Logout: Boolean;
{:Do NOOP. It is for prevent disconnect by timeout.}
function NoOp: Boolean;
{:Lists folder names. You may specify level of listing. If you specify
FromFolder as empty string, return is all folders in system.}
function List(FromFolder: string; const FolderList: TStrings): Boolean;
{:Lists folder names what match search criteria. You may specify level of
listing. If you specify FromFolder as empty string, return is all folders
in system.}
function ListSearch(FromFolder, Search: string; const FolderList: TStrings): Boolean;
{:Lists subscribed folder names. You may specify level of listing. If you
specify FromFolder as empty string, return is all subscribed folders in
system.}
function ListSubscribed(FromFolder: string; const FolderList: TStrings): Boolean;
{:Lists subscribed folder names what matching search criteria. You may
specify level of listing. If you specify FromFolder as empty string, return
is all subscribed folders in system.}
function ListSearchSubscribed(FromFolder, Search: string; const FolderList: TStrings): Boolean;
{:Create a new folder.}
function CreateFolder(FolderName: string): Boolean;
{:Delete a folder.}
function DeleteFolder(FolderName: string): Boolean;
{:Rename folder names.}
function RenameFolder(FolderName, NewFolderName: string): Boolean;
{:Subscribe folder.}
function SubscribeFolder(FolderName: string): Boolean;
{:Unsubscribe folder.}
function UnsubscribeFolder(FolderName: string): Boolean;
{:Select folder.}
function SelectFolder(FolderName: string): Boolean;
{:Select folder, but only for reading. Any changes are not allowed!}
function SelectROFolder(FolderName: string): Boolean;
{:Close a folder. (end of Selected state)}
function CloseFolder: Boolean;
{:Ask for given status of folder. I.e. if you specify as value 'UNSEEN',
result is number of unseen messages in folder. For another status
indentificator check IMAP documentation and documentation of your IMAP
server (each IMAP server can have their own statuses.)}
function StatusFolder(FolderName, Value: string): integer;
{:Hardly delete all messages marked as 'deleted' in current selected folder.}
function ExpungeFolder: Boolean;
{:Touch to folder. (use as update status of folder, etc.)}
function CheckFolder: Boolean;
{:Append given message to specified folder.}
function AppendMess(ToFolder: string; const Mess: TStrings): Boolean;
{:'Delete' message from current selected folder. It mark message as Deleted.
Real deleting will be done after sucessfull @link(CloseFolder) or
@link(ExpungeFolder)}
function DeleteMess(MessID: integer): boolean;
{:Get full message from specified message in selected folder.}
function FetchMess(MessID: integer; const Mess: TStrings): Boolean;
{:Get message headers only from specified message in selected folder.}
function FetchHeader(MessID: integer; const Headers: TStrings): Boolean;
{:Return message size of specified message from current selected folder.}
function MessageSize(MessID: integer): integer;
{:Copy message from current selected folder to another folder.}
function CopyMess(MessID: integer; ToFolder: string): Boolean;
{:Return message numbers from currently selected folder as result
of searching. Search criteria is very complex language (see to IMAP
specification) similar to SQL (but not same syntax!).}
function SearchMess(Criteria: string; const FoundMess: TStrings): Boolean;
{:Sets flags of message from current selected folder.}
function SetFlagsMess(MessID: integer; Flags: string): Boolean;
{:Gets flags of message from current selected folder.}
function GetFlagsMess(MessID: integer; var Flags: string): Boolean;
{:Add flags to message's flags.}
function AddFlagsMess(MessID: integer; Flags: string): Boolean;
{:Remove flags from message's flags.}
function DelFlagsMess(MessID: integer; Flags: string): Boolean;
{:Call STARTTLS command for upgrade connection to SSL/TLS mode.}
function StartTLS: Boolean;
{:return UID of requested message ID.}
function GetUID(MessID: integer; var UID : Integer): Boolean;
{:Try to find given capabily in capabilty string returned from IMAP server.}
function FindCap(const Value: string): string;
published
{:Status line with result of last operation.}
property ResultString: string read FResultString;
{:Full result of last IMAP operation.}
property FullResult: TStringList read FFullResult;
{:List of server capabilites.}
property IMAPcap: TStringList read FIMAPcap;
{:Authorization is successful done.}
property AuthDone: Boolean read FAuthDone;
{:Turn on or off usage of UID (unicate identificator) of messages instead
only sequence numbers.}
property UID: Boolean read FUID Write FUID;
{:Name of currently selected folder.}
property SelectedFolder: string read FSelectedFolder;
{:Count of messages in currently selected folder.}
property SelectedCount: integer read FSelectedCount;
{:Count of not-visited messages in currently selected folder.}
property SelectedRecent: integer read FSelectedRecent;
{:This number with name of folder is unique indentificator of folder.
(If someone delete folder and next create new folder with exactly same name
of folder, this number is must be different!)}
property SelectedUIDvalidity: integer read FSelectedUIDvalidity;
{:If is set to true, then upgrade to SSL/TLS mode if remote server support it.}
property AutoTLS: Boolean read FAutoTLS Write FAutoTLS;
{:SSL/TLS mode is used from first contact to server. Servers with full
SSL/TLS mode usualy using non-standard TCP port!}
property FullSSL: Boolean read FFullSSL Write FFullSSL;
{:Socket object used for TCP/IP operation. Good for seting OnStatus hook, etc.}
property Sock: TTCPBlockSocket read FSock;
end;
implementation
constructor TIMAPSend.Create;
begin
inherited Create;
FFullResult := TStringList.Create;
FIMAPcap := TStringList.Create;
FSock := TTCPBlockSocket.Create;
FSock.Owner := self;
FSock.ConvertLineEnd := True;
FSock.SizeRecvBuffer := 32768;
FSock.SizeSendBuffer := 32768;
FTimeout := 60000;
FTargetPort := cIMAPProtocol;
FTagCommand := 0;
FSelectedFolder := '';
FSelectedCount := 0;
FSelectedRecent := 0;
FSelectedUIDvalidity := 0;
FUID := False;
FAutoTLS := False;
FFullSSL := False;
end;
destructor TIMAPSend.Destroy;
begin
FSock.Free;
FIMAPcap.Free;
FFullResult.Free;
inherited Destroy;
end;
function TIMAPSend.ReadResult: string;
var
s: string;
x, l: integer;
begin
Result := '';
FFullResult.Clear;
FResultString := '';
repeat
s := FSock.RecvString(FTimeout);
if Pos('S' + IntToStr(FTagCommand) + ' ', s) = 1 then
begin
FResultString := s;
break;
end
else
FFullResult.Add(s);
if (s <> '') and (s[Length(s)]='}') then
begin
s := Copy(s, 1, Length(s) - 1);
x := RPos('{', s);
s := Copy(s, x + 1, Length(s) - x);
l := StrToIntDef(s, -1);
if l <> -1 then
begin
s := FSock.RecvBufferStr(l, FTimeout);
FFullResult.Add(s);
end;
end;
until FSock.LastError <> 0;
s := Trim(separateright(FResultString, ' '));
Result:=uppercase(Trim(separateleft(s, ' ')));
end;
procedure TIMAPSend.ProcessLiterals;
var
l: TStringList;
n, x: integer;
b: integer;
s: string;
begin
l := TStringList.Create;
try
l.Assign(FFullResult);
FFullResult.Clear;
b := 0;
for n := 0 to l.Count - 1 do
begin
s := l[n];
if b > 0 then
begin
FFullResult[FFullresult.Count - 1] :=
FFullResult[FFullresult.Count - 1] + s;
inc(b);
if b > 2 then
b := 0;
end
else
begin
if (s <> '') and (s[Length(s)]='}') then
begin
x := RPos('{', s);
Delete(s, x, Length(s) - x + 1);
b := 1;
end
else
b := 0;
FFullResult.Add(s);
end;
end;
finally
l.Free;
end;
end;
function TIMAPSend.IMAPcommand(Value: string): string;
begin
Inc(FTagCommand);
FSock.SendString('S' + IntToStr(FTagCommand) + ' ' + Value + CRLF);
Result := ReadResult;
end;
function TIMAPSend.IMAPuploadCommand(Value: string; const Data:TStrings): string;
var
l: integer;
begin
Inc(FTagCommand);
l := Length(Data.Text);
FSock.SendString('S' + IntToStr(FTagCommand) + ' ' + Value + ' {'+ IntToStr(l) + '}' + CRLF);
FSock.RecvString(FTimeout);
FSock.SendString(Data.Text + CRLF);
Result := ReadResult;
end;
procedure TIMAPSend.ParseMess(Value:TStrings);
var
n: integer;
begin
Value.Clear;
for n := 0 to FFullResult.Count - 2 do
if (length(FFullResult[n]) > 0) and (FFullResult[n][Length(FFullResult[n])] = '}') then
begin
Value.Text := FFullResult[n + 1];
Break;
end;
end;
procedure TIMAPSend.ParseFolderList(Value:TStrings);
var
n, x: integer;
s: string;
begin
ProcessLiterals;
Value.Clear;
for n := 0 to FFullResult.Count - 1 do
begin
s := FFullResult[n];
if (s <> '') and (Pos('\NOSELECT', UpperCase(s)) = 0) then
begin
if s[Length(s)] = '"' then
begin
Delete(s, Length(s), 1);
x := RPos('"', s);
end
else
x := RPos(' ', s);
if (x > 0) then
Value.Add(Copy(s, x + 1, Length(s) - x));
end;
end;
end;
procedure TIMAPSend.ParseSelect;
var
n: integer;
s, t: string;
begin
ProcessLiterals;
FSelectedCount := 0;
FSelectedRecent := 0;
FSelectedUIDvalidity := 0;
for n := 0 to FFullResult.Count - 1 do
begin
s := uppercase(FFullResult[n]);
if Pos(' EXISTS', s) > 0 then
begin
t := Trim(separateleft(s, ' EXISTS'));
t := Trim(separateright(t, '* '));
FSelectedCount := StrToIntDef(t, 0);
end;
if Pos(' RECENT', s) > 0 then
begin
t := Trim(separateleft(s, ' RECENT'));
t := Trim(separateright(t, '* '));
FSelectedRecent := StrToIntDef(t, 0);
end;
if Pos('UIDVALIDITY', s) > 0 then
begin
t := Trim(separateright(s, 'UIDVALIDITY '));
t := Trim(separateleft(t, ']'));
FSelectedUIDvalidity := StrToIntDef(t, 0);
end;
end;
end;
procedure TIMAPSend.ParseSearch(Value:TStrings);
var
n: integer;
s: string;
begin
ProcessLiterals;
Value.Clear;
for n := 0 to FFullResult.Count - 1 do
begin
s := uppercase(FFullResult[n]);
if Pos('* SEARCH', s) = 1 then
begin
s := Trim(SeparateRight(s, '* SEARCH'));
while s <> '' do
Value.Add(Fetch(s, ' '));
end;
end;
end;
function TIMAPSend.FindCap(const Value: string): string;
var
n: Integer;
s: string;
begin
s := UpperCase(Value);
Result := '';
for n := 0 to FIMAPcap.Count - 1 do
if Pos(s, UpperCase(FIMAPcap[n])) = 1 then
begin
Result := FIMAPcap[n];
Break;
end;
end;
function TIMAPSend.AuthLogin: Boolean;
begin
Result := IMAPcommand('LOGIN "' + FUsername + '" "' + FPassword + '"') = 'OK';
if Result then
FAuthDone := True;
end;
function TIMAPSend.Connect: Boolean;
begin
FSock.CloseSocket;
FSock.Bind(FIPInterface, cAnyPort);
if FSock.LastError = 0 then
FSock.Connect(FTargetHost, FTargetPort);
if FSock.LastError = 0 then
if FFullSSL then
FSock.SSLDoConnect;
Result := FSock.LastError = 0;
end;
function TIMAPSend.Capability: Boolean;
var
n: Integer;
s, t: string;
begin
Result := False;
FIMAPcap.Clear;
s := IMAPcommand('CAPABILITY');
if s = 'OK' then
begin
ProcessLiterals;
for n := 0 to FFullResult.Count - 1 do
if Pos('* CAPABILITY ', FFullResult[n]) = 1 then
begin
s := Trim(SeparateRight(FFullResult[n], '* CAPABILITY '));
while not (s = '') do
begin
t := Trim(separateleft(s, ' '));
s := Trim(separateright(s, ' '));
if s = t then
s := '';
FIMAPcap.Add(t);
end;
end;
Result := True;
end;
end;
function TIMAPSend.Login: Boolean;
var
s: string;
begin
FSelectedFolder := '';
FSelectedCount := 0;
FSelectedRecent := 0;
FSelectedUIDvalidity := 0;
Result := False;
FAuthDone := False;
if not Connect then
Exit;
s := FSock.RecvString(FTimeout);
if Pos('* PREAUTH', s) = 1 then
FAuthDone := True
else
if Pos('* OK', s) = 1 then
FAuthDone := False
else
Exit;
if Capability then
begin
if Findcap('IMAP4rev1') = '' then
Exit;
if FAutoTLS and (Findcap('STARTTLS') <> '') then
if StartTLS then
Capability;
end;
Result := AuthLogin;
end;
function TIMAPSend.Logout: Boolean;
begin
Result := IMAPcommand('LOGOUT') = 'OK';
FSelectedFolder := '';
FSock.CloseSocket;
end;
function TIMAPSend.NoOp: Boolean;
begin
Result := IMAPcommand('NOOP') = 'OK';
end;
function TIMAPSend.List(FromFolder: string; const FolderList: TStrings): Boolean;
begin
Result := IMAPcommand('LIST "' + FromFolder + '" *') = 'OK';
ParseFolderList(FolderList);
end;
function TIMAPSend.ListSearch(FromFolder, Search: string; const FolderList: TStrings): Boolean;
begin
Result := IMAPcommand('LIST "' + FromFolder + '" "' + Search +'"') = 'OK';