pax_global_header00006660000000000000000000000064146461424700014522gustar00rootroot0000000000000052 comment=9cbc933472b93a795e9fb0424e365823363bb72b belr-5.3.105/000077500000000000000000000000001464614247000126215ustar00rootroot00000000000000belr-5.3.105/.clang-format000066400000000000000000000021161464614247000151740ustar00rootroot00000000000000# Copyright (c) 2010-2023 Belledonne Communications SARL. # # 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 . --- Language: Cpp BasedOnStyle: LLVM AccessModifierOffset: -4 AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: AllIfsAndElse AlwaysBreakTemplateDeclarations: Yes BinPackParameters: false ColumnLimit: 120 PointerAlignment: Right IndentCaseLabels: true IndentWidth: 4 Standard: c++14 TabWidth: 4 UseTab: ForIndentation ... belr-5.3.105/.github/000077500000000000000000000000001464614247000141615ustar00rootroot00000000000000belr-5.3.105/.github/ISSUE_TEMPLATE/000077500000000000000000000000001464614247000163445ustar00rootroot00000000000000belr-5.3.105/.github/ISSUE_TEMPLATE/bug_report.yml000066400000000000000000000134721464614247000212460ustar00rootroot00000000000000--- name: Bug report description: File a bug/issue title: "[Bug]: " labels: ["bug"] body: - type: markdown attributes: value: '# Reminder' - type: markdown attributes: value: | The responses are provided by the **community** and, on a **best effort** basis, by some Belledonne Communications SARL engineers working on Linphone and its related projects. The community means any people all around the world simply willing to participate to the discussions. Belledonne Communications SARL **disclaims any WARRANTY** that the content posted on github issues or mailing lists is technically correct. Responses from Belledonne Communications SARL engineers shall be considered as individual contributions and shall not be seen as Belledonne Communications's official point of view or commitment. The Github issue tracker must be seen as a place for **collaboration**. Issues submitted should be of general interest, in the goal of improving the software. Consider that a **well documented** issue (with precise reproduction procedure, logs, stack trace if relevant, possibly a corrective patch) has a higher chance to receive interest and feedback from community members and Belledonne Communications' engineers. __Issues poorly documented, with no facts, or asking for debugging assistance for a custom app using Linphone's libraries, or for a modified version of Linphone are unlikely to receive any kind of response.__ People using Linphone or its related projects within the scope of their company job are invited to contact [Belledonne Communications](https://linphone.org/contact#content-bottom3) in order to obtain commercial support. - type: markdown attributes: value: | # Well ordered issues are treated issues **In our apps, the [Linphone-SDK](https://github.com/BelledonneCommunications/linphone-sdk) is used.** Please report your issue here **ONLY** if you are sure that the origin of the error is in this module. Otherwise, open an issue in the repository of the app you are using or in the Linphone-SDK, and we will move it to the related module. - type: markdown attributes: value: | # Useful links [Linphone.org](https://linphone.org) [Linphone commercial contact](https://linphone.org/contact#content-bottom3) Linphone Vulnerability/Security contact: vulnerabilities@linphone.org [Contributor agreement (to sign and to return to sales@belledonne-communications.com for a pull request)](https://linphone.org/sites/default/files/bc-contributor-agreement_0.pdf) - type: textarea attributes: label: | Context description: | - For which purpose do you use the project ? - With which software/hardware it is integrated ? - Did you use sip.linphone.org or a different SIP service (in this case specify which one and which version) ? value: | I use this project in a custom app running on Linux with the sip.linphone.org service for my company. I want to do a simple call between an Android phone and a Linux client. There is an error with a method of this project and I'm sure that I followed the documentation and double checked before posting. validations: required: true - type: textarea attributes: label: General information description: | Complete it multiple time if there are multiple devices involved. Please note that the issue has more chances to be read if you report a bug seen in the latest version of the module. Ex: - Device: [e.g. Samsung Note 20 Ultra] - OS: [e.g. Android 11] - Version of the App [e.g. 4.3.1] - Version of the SDK [e.g 4.4.16] value: | - Device: - OS: - Version of the App: - Version of the SDK: validations: required: true - type: textarea attributes: label: Expected behaviour description: "A clear and concise description of what you expected to happen." value: | I wanted to do a simple call with the Linux client calling the Android phone. However, the phone doesn't ring when it is asleep. validations: required: true - type: textarea attributes: label: To Reproduce description: "Steps to reproduce the behavior:" value: | 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error validations: required: true - type: textarea attributes: label: 'Additional context' value: Add any other context about the problem here. - type: markdown attributes: value: | # Logs ## Module logs Enable debug logs in advanced section of the settings, restart the app, reproduce the issue and then go to About page, click on "Send logs" and copy/paste the link here. If you doesn't have such an option, just provide the logs in attachments. - type: input attributes: label: 'SDK logs URL' - type: markdown attributes: value: | ## Module crash logs In case of a crash related to this module, please also provide the backtrace of the crash in attachments using adb logcat (Android) or the device console (iOS). For desktop versions, you can get the backtrace from a core dump. - type: markdown attributes: value: | # Screenshots Please add screenshots in attachments to help us to understand your problem. - type: markdown attributes: value: | # Pcap file If this is a network issue, join a pcap file of your attempt in attachments (done with Wireshark or TCPDump, for example) belr-5.3.105/.gitignore000066400000000000000000000007371464614247000146200ustar00rootroot00000000000000INSTALL aclocal.m4 *~ configure Makefile.in Makefile build-aux m4 autom4te.cache *.o *.lo *.la config.log config.status .deps .libs libtool compile depcomp missing install-sh config.guess config.h.in config.sub ltmain.sh stamp-h1 .anjuta belle-sip.anjuta .kdev4/ belle-sip.kdev4 config.h src/specs.c belle-sip.pc belle-sip.spec html/ *.orig tester/belle_sip_object_describe tester/belle_sip_parse tester/belle_sip_tester tester/belle_http_get tester/belle_sip_resolve belr.spec belr-5.3.105/BelrConfig.cmake.in000066400000000000000000000032221464614247000162410ustar00rootroot00000000000000############################################################################ # BelrConfig.cmake # Copyright (C) 2015-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ # # Config file for the belr package. # # Targets # ^^^^^^^ # # The following targets are always defined: # belr - The belr library target # # # Result variables # ^^^^^^^^^^^^^^^^ # # This config file will set the following variables in your project: # # Belr_FOUND - The belr library has been found # Belr_TARGET - The name of the CMake target for the belr library @PACKAGE_INIT@ include("${CMAKE_CURRENT_LIST_DIR}/BelrTargets.cmake") set(Belr_TARGET belr) # We must propagate the public dependencies and the private dependencies for static build include(CMakeFindDependencyMacro) find_dependency(BCToolbox) check_required_components(Belr) belr-5.3.105/CHANGELOG.md000066400000000000000000000014141464614247000144320ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.0] - 2019-09-18 ### Added - belr-compiler tool, to generate binary grammar files, that can be loaded hundred times faster than txt grammars. ### Changed - optimize size of user application object code, due to template instanciation of belr classes. - license moves to GNU GPLv3. - add better documentation in README. ## [0.1.3] - 2017-07-19 ### Fixed - Bugs. ## [0.1.0] - 2016-05-?? ### Fixed - Issue when handling non-ascii characters in inputs. ## [0.0.1] - 2016-01-01 ### Added - Belr is born. belr-5.3.105/CMakeLists.txt000066400000000000000000000116631464614247000153700ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2010-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ cmake_minimum_required(VERSION 3.22) project(Belr VERSION 5.3.0 LANGUAGES C CXX) set(BELR_SO_VERSION "1") option(ENABLE_STRICT "Build with strict compile options." YES) option(ENABLE_TOOLS "Turn on or off compilation of tools." YES) option(ENABLE_UNIT_TESTS "Enable compilation of unit tests." YES) option(ENABLE_PACKAGE_SOURCE "Create 'package_source' target for source archive making" OFF) set(CMAKE_CXX_STANDARD 17) if(NOT CPACK_GENERATOR AND NOT CMAKE_INSTALL_RPATH AND CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}) message(STATUS "Setting install rpath to ${CMAKE_INSTALL_RPATH}") endif() include(GNUInstallDirs) include(CheckSymbolExists) include(CMakePushCheckState) include(CheckCXXCompilerFlag) if(MSVC) add_definitions(-D_CRT_SECURE_NO_WARNINGS) add_definitions(-D_SILENCE_CXX17_ADAPTOR_TYPEDEFS_DEPRECATION_WARNING) endif() # find_package should be invoked here to check for libraries - however do NOT # call include_directories here (see below) find_package(BCToolbox 5.3.0 REQUIRED OPTIONAL_COMPONENTS tester) if(UNIX AND NOT APPLE) include(CheckIncludeFiles) check_include_files(libudev.h HAVE_LIBUDEV_H) endif() include_directories( include src ${CMAKE_CURRENT_BINARY_DIR} ) set(STRICT_OPTIONS_CPP ) set(STRICT_OPTIONS_C ) set(STRICT_OPTIONS_CXX ) set(STRICT_OPTIONS_OBJC ) if(MSVC) if(ENABLE_STRICT) list(APPEND STRICT_OPTIONS_CPP "/WX") endif() else() list(APPEND STRICT_OPTIONS_CPP "-Wall" "-Wuninitialized" "-Wno-error=deprecated-declarations") list(APPEND STRICT_OPTIONS_C "-Wdeclaration-after-statement" "-Wstrict-prototypes" "-Wno-error=strict-prototypes") if(CMAKE_C_COMPILER_ID MATCHES "Clang") list(APPEND STRICT_OPTIONS_CPP "-Qunused-arguments" "-Wno-array-bounds") endif() if(APPLE) list(APPEND STRICT_OPTIONS_CPP "-Wno-error=unknown-warning-option" "-Qunused-arguments" "-Wno-tautological-compare" "-Wno-unused-function" "-Wno-array-bounds") endif() if(ENABLE_STRICT) list(APPEND STRICT_OPTIONS_CPP "-Werror" "-Wextra" "-Wunused-parameter" "-fno-strict-aliasing") CHECK_CXX_COMPILER_FLAG("-Wsuggest-override" SUGGEST_OVERRIDE) if(SUGGEST_OVERRIDE) list(APPEND STRICT_OPTIONS_CPP "-Wsuggest-override -Werror=suggest-override") endif() endif() endif() if(STRICT_OPTIONS_CPP) list(REMOVE_DUPLICATES STRICT_OPTIONS_CPP) endif() if(STRICT_OPTIONS_C) list(REMOVE_DUPLICATES STRICT_OPTIONS_C) endif() set(BELR_CPPFLAGS ) if(NOT BUILD_SHARED_LIBS) list(APPEND BELR_CPPFLAGS "-DBELR_STATIC") endif() if(BELR_CPPFLAGS) list(REMOVE_DUPLICATES BELR_CPPFLAGS) add_definitions(${BELR_CPPFLAGS}) endif() add_definitions("-DBELR_EXPORTS") set(BELR_GRAMMARS_DIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/belr/grammars") set(BELR_GRAMMARS_RELATIVE_DIR "${CMAKE_INSTALL_DATADIR}/belr/grammars") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/config.h.cmake" "${CMAKE_CURRENT_BINARY_DIR}/config.h") add_subdirectory(include) add_subdirectory(src) if(ENABLE_UNIT_TESTS) add_subdirectory(tester) endif() if(ENABLE_TOOLS) add_subdirectory(tools) endif() include(CMakePackageConfigHelpers) set(CMAKE_MODULES_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") configure_package_config_file("${PROJECT_NAME}Config.cmake.in" "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" INSTALL_DESTINATION "${CMAKE_MODULES_INSTALL_DIR}" NO_SET_AND_CHECK_MACRO ) write_basic_package_version_file("${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) install(FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" "${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" DESTINATION ${CMAKE_MODULES_INSTALL_DIR} ) install(EXPORT ${PROJECT_NAME}Targets FILE "${PROJECT_NAME}Targets.cmake" DESTINATION ${CMAKE_MODULES_INSTALL_DIR} ) if (ENABLE_PACKAGE_SOURCE) add_subdirectory(build) endif() belr-5.3.105/LICENSE.txt000066400000000000000000000773311464614247000144570ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is 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. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 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. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 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 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. Use with the GNU Affero General Public License. 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 Affero 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 special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 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 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 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 belr-5.3.105/README.md000066400000000000000000000154611464614247000141070ustar00rootroot00000000000000[![pipeline status](https://gitlab.linphone.org/BC/public/belr/badges/master/pipeline.svg)](https://gitlab.linphone.org/BC/public/belr/commits/master) What is Belr ============ Belr is Belledonne Communications' language recognition library, written in C++11. It parses text inputs formatted according to a language defined by an ABNF grammar, such as the protocols standardized at IETF. It drastically simplifies the writing of a parser, provided that the parsed language is defined with an *ABNF grammar[1]*. The parser automaton is automatically generated by belr library, in memory, from the ABNF grammar text. The application developer is responsible to connect belr's parser with its custom code through callbacks in order to get notified of recognized language elements. It is based on finite state machine theory and heavily relies on recursivity from an implementation standpoint. The benefits of using belr are: - belr is safe: no handly written code to parse the language. No buffer overflow. No mistakes in ABNF interpretation. - belr saves time: a lot of human efforts are eliminated because the parser is automatically generated. - belr saves space: belr does not generate source code files to insert in your build process either. The parser automaton is created at runtime, in memory. - belr is fast, as it was around 50% faster on parsing SIP URIs compared to antlr/antlr3c. - belr is flexible: you are free to design your parser API as you want, and simply connect the parser automaton with your API. License ======= Copyright © [Belledonne Communications SARL](https://www.linphone.org), all rights reserved. Belr is dual licensed: - under a GNU GPLv3 license for free (see LICENSE.txt file for details) - under a proprietary license, for closed source projects. Contact sales@belledonne-communications.com for costs and other service information. How it works ============ Let's take a very basic example to understand. Your application first needs to create a Grammar object from a text file contaning the ABNF grammar description: ``` ABNFGrammarBuilder builder; // The grammar is constructed from sipgrammar.txt file, plus an additional built-in grammar called 'CoreRules', // which is used by almost every grammar. shared_ptr grammar=builder.createFromAbnfFile("sipgrammar.txt", make_shared()); ``` Then, from the grammar object returned, instanciate a parser object, by telling belr the name of a base class you have defined to represent any element of the language. In the example below, it is called `SipElement`. The parser object can be used as much time as needed. There is no no need to re-instanciate it each time you need to parse a new input ! ``` ABNFGrammarBuilder builder; Parser> parser(grammar); ``` Now, you have to connect the parser with your own classes in order to have language elements filled into your objects. ``` parser.setHandler("SIP-URI", make_fn(&SipUri::create)) //tells that whenever a SIP-URI is found, a SipUri object must be created. ->setCollector("user", make_sfn(&SipUri::setUsername)) //tells that when a "user" field is found, SipUri::setUsername() is to be called for assigning the "user" ->setCollector("host", make_sfn(&SipUri::setHost)) //tells that when host is encountered, use SipUri::setHost() to assign it to our SipUri object. ->setCollector("port", make_sfn(&SipUri::setPort)); ``` Here, we have instructed our belr parser to invoke our `SipUri::create()` each time it recognizes a SIP-URI. This method must simply return a new `SipUri` instance. We also told him, that each time the `user` part of a SIP URI is recognized, the `SipUri::setUsername(const std::string& user)` method must be called to fill the recognized user part into the created SipUri instance. Similarly, we assign the `host` part with SipUri::setHost() method, and the `port` part with the SipUri::setPort() method. Finally, you can now parse a SIP-URI: ``` size_t parsedSize; string inputToParse = "sip:bob@sip.example.org"; shared_ptr ret = parser.parseInput("SIP-URI", inputToParse , &parsedSize); //if the sip uri is recognized, the return value is non null and you can cast it into a SipUri object. if (ret){ shared_ptr sipUri = dynamic_pointer_cast(ret); // Do what you want with the SipUri object... } ``` The full example is in tools/belr-demo.cc. One last thing to know. Grammar creation from text files requires many computations, which can slow down the startup of your application. Fortunately, a solution exists: use the `belr-compiler` tool to generate a binary representation of the grammar, saved to disk and included as a resource in your application. You can view the binary grammar as a kind of byte-code representing the language automaton. Then your application can simply instanciate the `Grammar` object by loading it from disk. It is hundred times faster. Dependencies ============ - *bctoolbox[2]*: our portability layer Build Belr ========== cmake . -DCMAKE_INSTALL_PREFIX= -DCMAKE_PREFIX_PATH= make make install Limitations =========== Belr doesn't handle non-deterministic ABNF grammars. For example: ``` token = 1*(alphanum / "-" / "." / "!" / "%" / "*" my-element = token "!" ``` The problem of this grammar is that "!" is part of `token`, and also the termination character `my-element`. It is non-deterministic: when the automaton finds a "!", it can recognize it as a `token`, or as the last element of `my-element`. Unfortunately it is not so rare to encounter this kind of situation. Belr's current logic will be to include the "!" into `token`, all the time, because this is the first one that matches in the sequence. The solution for this would be to have belr explore both possibilities, however this is not implemented as of today (2019-09-17). Most of time, a workaround exists by re-writing the problematic grammar rule in such a way that it is no longer this ambiguity. Build options ============= * `CMAKE_INSTALL_PREFIX=`: install prefix * `CMAKE_PREFIX_PATH=`: column-separated list of prefixes where to search for dependencies * `ENABLE_STRICT=NO`: build without strict compilation flags (-Wall -Werror) * `ENABLE_TOOLS=NO`: do not build tools (belr-demo, belr-parse) Note for packagers ================== Our CMake scripts may automatically add some paths into research paths of generated binaries. To ensure that the installed binaries are striped of any rpath, use `-DCMAKE_SKIP_INSTALL_RPATH=ON` while you invoke cmake. Rpm packaging belr can be generated with cmake3 using the following command: mkdir WORK cd WORK cmake3 ../ make package_source rpmbuild -ta --clean --rmsource --rmspec belr--.tar.gz ----------------------- * [1] https://tools.ietf.org/html/rfc5234 * [2] git://git.linphone.org/bctoolbox.git or belr-5.3.105/belr.pc.in000066400000000000000000000004431464614247000144770ustar00rootroot00000000000000# This is a comment prefix=@CMAKE_INSTALL_PREFIX@ Name: @PROJECT_NAME@ Description: Belr is Belledonne Communications' language recognition library Version: @PROJECT_VERSION@ Libs: -L@CMAKE_INSTALL_FULL_LIBDIR@ -lbelr Libs.private: @LIBS_PRIVATE@ Cflags: -I@CMAKE_INSTALL_FULL_INCLUDEDIR@ belr-5.3.105/build/000077500000000000000000000000001464614247000137205ustar00rootroot00000000000000belr-5.3.105/build/CMakeLists.txt000066400000000000000000000023031464614247000164560ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2010-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ if(NOT CPACK_PACKAGE_NAME) set(CPACK_PACKAGE_NAME "belr") endif() set(CPACK_SOURCE_IGNORE_FILES "${CMAKE_BINARY_DIR}" "^${PROJECT_SOURCE_DIR}/.git*" ) bc_make_package_source_target() belr-5.3.105/build/android/000077500000000000000000000000001464614247000153405ustar00rootroot00000000000000belr-5.3.105/build/android/Android.mk000066400000000000000000000004431464614247000172520ustar00rootroot00000000000000LOCAL_PATH:= $(call my-dir)/../../src include $(CLEAR_VARS) LOCAL_CPP_EXTENSION := .cc LOCAL_C_INCLUDES += \ $(LOCAL_PATH)/../include \ LOCAL_SRC_FILES := \ abnf.cc \ belr.cc \ grammarbuilder.cc \ parser.cc \ LOCAL_MODULE:= libbelr include $(BUILD_STATIC_LIBRARY)belr-5.3.105/build/osx/000077500000000000000000000000001464614247000145315ustar00rootroot00000000000000belr-5.3.105/build/osx/Info.plist.in000066400000000000000000000026341464614247000171130ustar00rootroot00000000000000 CFBundleDevelopmentRegion English CFBundleExecutable belr CFBundleGetInfoString ${MACOSX_BUNDLE_INFO_STRING} CFBundleIconFile ${MACOSX_BUNDLE_ICON_FILE} CFBundleIdentifier ${MACOSX_FRAMEWORK_IDENTIFIER} LSMinimumSystemVersion ${CMAKE_OSX_DEPLOYMENT_TARGET} MinimumOSVersion ${CMAKE_OSX_DEPLOYMENT_TARGET} CFBundleInfoDictionaryVersion 6.0 CFBundleLongVersionString ${MACOSX_BUNDLE_LONG_VERSION_STRING} CFBundleName ${MACOSX_BUNDLE_BUNDLE_NAME} CFBundlePackageType FMWK CFBundleShortVersionString ${BELR_SO_VERSION} CFBundleSignature ???? CFBundleVersion ${BELR_SO_VERSION} CSResourcesFileMapped NSHumanReadableCopyright ${MACOSX_BUNDLE_COPYRIGHT} NSPrincipalClass NSApplication NSHighResolutionCapable True belr-5.3.105/build/rpm/000077500000000000000000000000001464614247000145165ustar00rootroot00000000000000belr-5.3.105/build/rpm/belr.spec.cmake000077500000000000000000000057111464614247000174040ustar00rootroot00000000000000# -*- rpm-spec -*- %define _prefix @CMAKE_INSTALL_PREFIX@ %define pkg_prefix @BC_PACKAGE_NAME_PREFIX@ %define package_name @CPACK_PACKAGE_NAME@-${FULL_VERSION} # re-define some directories for older RPMBuild versions which don't. This messes up the doc/ dir # taken from https://fedoraproject.org/wiki/Packaging:RPMMacros?rd=Packaging/RPMMacros %define _datarootdir %{_prefix}/share %define _datadir %{_datarootdir} %define _docdir %{_datadir}/doc Name: @CPACK_PACKAGE_NAME@ Version: ${RPM_VERSION} Release: ${RPM_RELEASE}%{?dist} Summary: Belr is language recognition library for ABNF based protocols. Group: Applications/Communications License: GPL URL: http://www.linphone.org Source0: %{package_name}.tar.gz BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot Requires: %{pkg_prefix}bctoolbox %description Belr is Belledonne Communications' language recognition library. It aims at parsing any input formatted according to a language defined by an ABNF grammar, such as the protocols standardized at IETF. It is based on finite state machine theory and heavily relies on recursivity from an implementation standpoint. %package devel Summary: Development libraries for belr Group: Development/Libraries Requires: %{name} = %{version}-%{release} %description devel Libraries and headers required to develop software with belr %if 0%{?rhel} && 0%{?rhel} <= 7 %global cmake_name cmake3 %define ctest_name ctest3 %else %global cmake_name cmake %define ctest_name ctest %endif # This is for debian builds where debug_package has to be manually specified, whereas in centos it does not %define custom_debug_package %{!?_enable_debug_packages:%debug_package}%{?_enable_debug_package:%{nil}} %custom_debug_package %prep %setup -n %{package_name} %build %{expand:%%%cmake_name} . -DCMAKE_BUILD_TYPE=@CMAKE_BUILD_TYPE@ -DCMAKE_PREFIX_PATH:PATH=%{_prefix} @RPM_ALL_CMAKE_OPTIONS@ make %{?_smp_mflags} %install make install DESTDIR=%{buildroot} # Dirty workaround to give exec rights for all shared libraries. Debian packaging needs this # TODO : set CMAKE_INSTALL_SO_NO_EXE for a cleaner workaround chmod +x `find %{buildroot} *.so.*` %check %{ctest_name} -V %{?_smp_mflags} %clean rm -rf $RPM_BUILD_ROOT %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %defattr(-,root,root) %doc CHANGELOG.md LICENSE.txt README.md %{_libdir}/*.so.* %files devel %defattr(-,root,root) %{_includedir}/belr %if @ENABLE_STATIC@ %{_libdir}/libbelr.a %endif %if @ENABLE_SHARED@ %{_libdir}/libbelr.so %endif %{_libdir}/cmake/belr/belrConfig*.cmake %{_libdir}/cmake/belr/belrTargets*.cmake %if @ENABLE_TESTS@ || @ENABLE_TOOLS@ %{_bindir}/* %endif %changelog * Tue Nov 27 2018 ronan.abhamon - Do not set CMAKE_INSTALL_LIBDIR and never with _libdir! * Wed Jul 19 2017 jehan.monnier - Initial RPM release. belr-5.3.105/config.h.cmake000066400000000000000000000020141464614247000153130ustar00rootroot00000000000000/* * Copyright (C) 2017 Belledonne Communications SARL * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef belr_config_h #define belr_config_h #define BELR_GRAMMARS_DIR "${BELR_GRAMMARS_DIR}" #define BELR_GRAMMARS_RELATIVE_DIR "${BELR_GRAMMARS_RELATIVE_DIR}" #define BELR_LOCAL_RESOURCE_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/tester/res" #endif belr-5.3.105/include/000077500000000000000000000000001464614247000142445ustar00rootroot00000000000000belr-5.3.105/include/CMakeLists.txt000066400000000000000000000027021464614247000170050ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2015 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ set(HEADER_FILES abnf.h belr.h grammarbuilder.h parser.h ) set(BELR_HEADER_FILES ) foreach(HEADER_FILE ${HEADER_FILES}) list(APPEND BELR_HEADER_FILES "${CMAKE_CURRENT_LIST_DIR}/belr/${HEADER_FILE}") endforeach() set(BELR_HEADER_FILES ${BELR_HEADER_FILES} PARENT_SCOPE) install(FILES ${BELR_HEADER_FILES} DESTINATION include/belr PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ) belr-5.3.105/include/Makefile.am000066400000000000000000000000151464614247000162740ustar00rootroot00000000000000SUBDIRS=belr belr-5.3.105/include/belr/000077500000000000000000000000001464614247000151705ustar00rootroot00000000000000belr-5.3.105/include/belr/Makefile.am000066400000000000000000000002071464614247000172230ustar00rootroot00000000000000belr_includedir=$(includedir)/belr belr_include_HEADERS = belr.h abnf.h grammarbuilder.h parser.h EXTRA_DIST=$(belr_include_HEADERS) belr-5.3.105/include/belr/abnf.h000066400000000000000000000036761464614247000162630ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef _ABNF_H_ #define _ABNF_H_ #include "belr.h" // ============================================================================= namespace belr { /** * Grammar containing core definitions of ABNF. * This is required for almost all IETF text based protocols. **/ class CoreRules : public Grammar { public: /// Initialize a CoreRules grammar object. BELR_PUBLIC CoreRules(); private: void alpha(); void bit(); void char_(); void cr(); void lf(); void crlf(); void ctl(); void digit(); void dquote(); void hexdig(); void htab(); void lwsp(); void octet(); void sp(); void vchar(); void wsp(); }; class ABNFGrammar : public Grammar { public: ABNFGrammar(); private: void comment(); void c_nl(); void c_wsp(); void rulename(); void repeat(); void repeat_min(); void repeat_max(); void repeat_count(); void defined_as(); void rulelist(); void rule(); void elements(); void alternation(); void concatenation(); void repetition(); void element(); void group(); void option(); void char_val(); void num_val(); void prose_val(); void bin_val(); void dec_val(); void hex_val(); void crlf_or_lf(); }; } // namespace belr #endif belr-5.3.105/include/belr/belr.h000066400000000000000000000264651464614247000163020ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef _BELR_H_ #define _BELR_H_ #include #include #include #include // ============================================================================= #ifdef _MSC_VER #ifdef BELR_STATIC #define BELR_PUBLIC #else #ifdef BELR_EXPORTS #define BELR_PUBLIC __declspec(dllexport) #else #define BELR_PUBLIC __declspec(dllimport) #endif #endif #else #define BELR_PUBLIC #endif namespace belr { BELR_PUBLIC std::string tolower(const std::string &str); class ParserContextBase; class BinaryOutputStream; class BinaryGrammarBuilder; /** * The transition map is an internal tool used to optimize recognizers **/ struct TransitionMap { TransitionMap(); bool intersect(const TransitionMap *other); bool intersect(const TransitionMap *other, TransitionMap *result); // performs a AND operation void merge(const TransitionMap *other); // Performs an OR operation bool mPossibleChars[256]; }; class Recognizer : public std::enable_shared_from_this { public: virtual ~Recognizer() = default; void setName(const std::string &name); const std::string &getName() const; BELR_PUBLIC size_t feed(ParserContextBase &ctx, const std::string &input, size_t pos); unsigned int getId() const { return mId; } bool getTransitionMap(TransitionMap *mask); void optimize(); void optimize(int recursionLevel); void serialize(BinaryOutputStream &fstr, bool topLevel = false); static std::shared_ptr build(BinaryGrammarBuilder &ifstr); protected: Recognizer() = default; Recognizer(BinaryGrammarBuilder &istr); virtual void _serialize(BinaryOutputStream &fstr) = 0; /*returns true if the transition map is complete, false otherwise*/ virtual bool _getTransitionMap(TransitionMap *mask); virtual void _optimize(int recursionLevel) = 0; virtual size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) = 0; std::string mName; unsigned int mId = 0; }; enum RecognizerTypeId { CharRecognizerId = 1, SelectorId, ExclusiveSelectorId, SequenceId, LoopId, CharRangeId, LiteralId, PointerId, AliasId, RuleRefId }; class CharRecognizer : public Recognizer { public: CharRecognizer(int to_recognize, bool caseSensitive = false); CharRecognizer(BinaryGrammarBuilder &istr); private: size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; void _optimize(int recursionLevel) override; virtual void _serialize(BinaryOutputStream &fstr) override; int mToRecognize; bool mCaseSensitive; }; class Selector : public Recognizer { public: std::shared_ptr addRecognizer(const std::shared_ptr &element); Selector(bool isExclusive = false); Selector(BinaryGrammarBuilder &istr); protected: void _optimize(int recursionLevel) override; size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; bool _getTransitionMap(TransitionMap *mask) override; virtual void _serialize(BinaryOutputStream &fstr) override; size_t _feedExclusive(ParserContextBase &ctx, const std::string &input, size_t pos); std::list> mElements; bool mIsExclusive = false; }; /**This is an optimization of the first one for the case where there can be only a single match*/ class ExclusiveSelector : public Selector { public: ExclusiveSelector(); ExclusiveSelector(BinaryGrammarBuilder &istr); private: size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; }; class Sequence : public Recognizer { public: Sequence() = default; Sequence(BinaryGrammarBuilder &istr); bool _getTransitionMap(TransitionMap *mask) override; std::shared_ptr addRecognizer(const std::shared_ptr &element); protected: virtual void _serialize(BinaryOutputStream &fstr) override; void _optimize(int recursionLevel) override; private: size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; std::list> mElements; }; class Loop : public Recognizer { public: Loop() = default; Loop(BinaryGrammarBuilder &istr); bool _getTransitionMap(TransitionMap *mask) override; std::shared_ptr setRecognizer(const std::shared_ptr &element, int min = 0, int max = -1); protected: virtual void _serialize(BinaryOutputStream &fstr) override; void _optimize(int recursionLevel) override; private: size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; std::shared_ptr mRecognizer; int mMin = 0; int mMax = -1; }; class Foundation { public: static std::shared_ptr charRecognizer(int character, bool caseSensitive = false); static std::shared_ptr selector(bool isExclusive = false); static std::shared_ptr sequence(); static std::shared_ptr loop(); }; /*this is an optimization of a selector with multiple individual char recognizer*/ class CharRange : public Recognizer { public: CharRange(int begin, int end); CharRange(BinaryGrammarBuilder &istr); private: virtual void _serialize(BinaryOutputStream &fstr) override; void _optimize(int recursionLevel) override; size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; int mBegin; int mEnd; }; class Literal : public Recognizer { public: Literal(const std::string &lit); Literal(BinaryGrammarBuilder &istr); bool _getTransitionMap(TransitionMap *mask) override; private: void _optimize(int recursionLevel) override; virtual void _serialize(BinaryOutputStream &fstr) override; size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; std::string mLiteral; size_t mLiteralSize; }; class Utils { public: static std::shared_ptr literal(const std::string <); static std::shared_ptr char_range(int begin, int end); }; /** * The RecognizerPointer just points to another recognizer and delegates everything to the pointed recognizer. * It is a place holder when a rule not-yet-defined appears when parsing an ABNF grammar. * The pointed recognizer is set to the rule when it comes defined. **/ class RecognizerPointer : public Recognizer { public: RecognizerPointer() = default; // RecognizerPointer(BinaryGrammarBuilder &istr); std::shared_ptr getPointed(); void setPointed(const std::shared_ptr &r); private: void _optimize(int recursionLevel) override; virtual void _serialize(BinaryOutputStream &fstr) override; size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; std::shared_ptr mRecognizer; }; /** * The RecognizerAlias points to another recognizer and delegates everything. It is necessary to represents ABNF *statements like rule2 = rule1 It is different from the RecognizerPointer in its function, however it behaves exactly *the same way. A different type is necessary to distinguish between the two usage. **/ class RecognizerAlias : public Recognizer { public: RecognizerAlias() = default; RecognizerAlias(BinaryGrammarBuilder &istr); std::shared_ptr getPointed(); void setPointed(const std::shared_ptr &r); private: void _optimize(int recursionLevel) override; virtual void _serialize(BinaryOutputStream &fstr) override; size_t _feed(ParserContextBase &ctx, const std::string &input, size_t pos) override; std::shared_ptr mRecognizer; }; /** * Grammar class represents an ABNF grammar, with all its rules. **/ class Grammar { public: /** * Initialize an empty grammar, giving a name for debugging. **/ BELR_PUBLIC Grammar(const std::string &name); BELR_PUBLIC ~Grammar(); /** * Include another grammar into this grammar. **/ BELR_PUBLIC void include(const std::shared_ptr &grammar); /** * Add a rule to the grammar. * @param name the name of the rule * @param rule the rule recognizer, must be an instance of belr::Recognizer. * @note The grammar takes ownership of the recognizer, which must not be used outside of this grammar. * TODO: use unique_ptr to enforce this, or make a copy ? **/ void addRule(const std::string &name, const std::shared_ptr &rule); /** * Extend a rule from the grammar. * This corresponds to the '/=' operator of ABNF definition. * @param name the name of the rule to extend. * @param rule the recognizer of the extension. **/ void extendRule(const std::string &name, const std::shared_ptr &rule); /** * Find a rule from the grammar, given its name. * @param name the name of the rule * @return the recognizer implementing this rule. Is nullptr if the rule doesn't exist in the grammar. **/ BELR_PUBLIC std::shared_ptr findRule(const std::string &name); /** * Find a rule from the grammar, given its name. * Unlike findRule(), getRule() never returns nullptr. * If the rule is not (yet) defined, it returns an undefined pointer, that will be set later if the rule gets *defined. This mechanism is required to allow defining rules in any order, and defining rules that call themselve *recursively. * @param name the name of the rule to get * @return the recognizer implementing the rule, or a RecognizerPointer if the rule isn't yet defined. **/ BELR_PUBLIC std::shared_ptr getRule(const std::string &name); /** * Returns true if the grammar is complete, that is all rules are defined. * In other words, a grammar is complete if no rule depends on another rule which is not defined. **/ BELR_PUBLIC bool isComplete() const; /** * Optimize the grammar. This is required to obtain good performance of the recognizers implementing the rule. * The optimization step consists in checking whether belr::Selector objects in the grammar are exclusive or not. * A selector is said exclusive when a single sub-rule can match. Knowing this in advance optimizes the processing *because no branch context is to be created to explore the different choices of the selector recognizer. **/ BELR_PUBLIC void optimize(); /** * Return the number of rules in this grammar. **/ BELR_PUBLIC int getNumRules() const; /** * Save the grammar into a binary file. **/ BELR_PUBLIC int save(const std::string &filename); /** * Load the grammar from a binary file **/ BELR_PUBLIC int load(const std::string &filename); private: std::map> mRules; // The recognizer pointers create loops in the chain of recognizer, preventing shared_ptr<> to be released. // We store them in this list so that we can reset them manually to break the loop of reference. std::list> mRecognizerPointers; std::string mName; }; } // namespace belr #endif belr-5.3.105/include/belr/grammarbuilder.h000066400000000000000000000216621464614247000203450ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef _GRAMMARBUILDER_H_ #define _GRAMMARBUILDER_H_ #include "parser.h" // ============================================================================= namespace belr { class ABNFAlternation; class ABNFBuilder { public: virtual ~ABNFBuilder() = default; virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) = 0; virtual std::ostream &describe(std::ostream &) const = 0; }; class ABNFRule : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void setName(const std::string &name); void setDefinedAs(const std::string &defined_as); void setAlternation(const std::shared_ptr &a); bool isExtension() const; const std::string &getName() const { return mName; } static std::shared_ptr create(); private: std::shared_ptr mAlternation; std::string mName; std::string mDefinedAs; }; class ABNFRuleList : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void addRule(const std::shared_ptr &rule); static std::shared_ptr create(); private: std::list> mRules; }; class ABNFNumval : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void setDecVal(const std::string &decval); void setHexVal(const std::string &hexval); void setBinVal(const std::string &binval); static std::shared_ptr create(); private: void parseValues(const std::string &val, int base); std::vector mValues; bool mIsRange = false; }; class ABNFElement : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void setElement(const std::shared_ptr &e); void setRulename(const std::string &rulename); void setCharVal(const std::string &charval); void setProseVal(const std::string &prose); bool isDefined() const; static std::shared_ptr create(); private: std::shared_ptr mElement; std::string mRulename; std::string mCharVal; }; class ABNFGroup : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void setAlternation(const std::shared_ptr &a); static std::shared_ptr create(); private: std::shared_ptr mAlternation; }; class ABNFRepetition : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void setRepeat(const std::string &r); void setMin(int min); void setMax(int max); void setCount(int count); void setElement(const std::shared_ptr &e); static std::shared_ptr create(); private: int mMin = 0; int mMax = -1; int mCount = -1; std::string mRepeat; std::shared_ptr mElement; }; class ABNFOption : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void setAlternation(const std::shared_ptr &a); static std::shared_ptr create(); private: std::shared_ptr mAlternation; }; class ABNFConcatenation : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void addRepetition(const std::shared_ptr &r); static std::shared_ptr create(); private: std::list> mRepetitions; }; class ABNFAlternation : public ABNFBuilder { public: virtual std::shared_ptr buildRecognizer(const std::shared_ptr &grammar) override; virtual std::ostream &describe(std::ostream &ostr) const override; void addConcatenation(const std::shared_ptr &c); std::shared_ptr buildRecognizerNoOptim(const std::shared_ptr &grammar); static std::shared_ptr create(); private: std::list> mConcatenations; }; /** * The ABNFGrammarBuilder builds a Grammar object from an ABNF grammar defined in a text file. **/ class ABNFGrammarBuilder { public: /** * Initialize the builder. **/ BELR_PUBLIC ABNFGrammarBuilder(); /** * Create a grammar from an ABNF grammar defined in the string pointed by abnf. * An optional Grammar argument corresponding to a grammar to include can be passed. * Usually the belr::CoreRules grammar is required for most IETF text protocols. * The returned grammar can be used to instanciate a belr::Parser object capable of parsing * the protocol or language described in the grammar. * @param abnf the string that contains the abnf grammar. * @param grammar an optional grammar to include. * @return the Grammar object corresponding to the text definition loaded, nullptr if an error occured. **/ BELR_PUBLIC std::shared_ptr createFromAbnf(const std::string &abnf, const std::shared_ptr &grammar = nullptr); /** * Create a grammar from an ABNF grammar defined in the text file pointed by path. * An optional Grammar argument corresponding to a grammar to include can be passed. * Usually the belr::CoreRules grammar is required for most IETF text protocols. * The returned grammar can be used to instanciate a belr::Parser object capable of parsing * the protocol or language described in the grammar. * @param path the path from where to load the abnf definition. * @param grammar an optional grammar to include. * @return the Grammar object corresponding to the text definition loaded, nullptr if an error occured. **/ BELR_PUBLIC std::shared_ptr createFromAbnfFile(const std::string &path, const std::shared_ptr &grammar = nullptr); private: Parser> mParser; }; /** * The GrammarLoader creates Grammar objects from binary files lookup and loaded from a pre-defined set of paths. * The binary files have to be created from the ABNF grammar files using the belr-compiler tool. **/ class GrammarLoader { public: /** * Obtain the GrammarLoader singleton. **/ BELR_PUBLIC static GrammarLoader &get(); /** * Clear all specific lookup paths previously set in the GrammarLoader. * The system paths are not erased. **/ BELR_PUBLIC void clear(); /** * Add a specific path to lookup for grammar binary files. * Any specific paths added by this method is actually prepended to the list of paths. * @param path a path **/ BELR_PUBLIC void addPath(const std::string &path); /** * Build a grammar loaded from a binary file whose name is 'fileName' argument. * The file searched from the list of specific paths eventually added by addPath(), and the system paths. * That the GrammarLoader is initialized with two system paths used for searching: * - ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATADIR}/belr/grammars * - ${CMAKE_INSTALL_DATADIR}/belr/grammars * @param fileName the file name of grammar **/ BELR_PUBLIC std::shared_ptr load(const std::string &fileName); private: GrammarLoader(); GrammarLoader(const GrammarLoader &other); // forbids copy constructor std::string lookup(const std::string &fileName, const std::list &dirs); std::list mSystemPaths; std::list mAppPaths; bool isAbsolutePath(const std::string &path); static GrammarLoader *sInstance; }; } // namespace belr #endif belr-5.3.105/include/belr/parser.h000066400000000000000000000644441464614247000166510ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef _PARSER_H_ #define _PARSER_H_ #include #include #include #include #include #define BELR_USE_ATOMIC 1 #if BELR_USE_ATOMIC #include #endif #include "bctoolbox/defs.h" #include "belr.h" // ============================================================================= namespace belr { template class CollectorBase { public: virtual ~CollectorBase() = default; virtual void invokeWithChild(_parserElementT obj, _parserElementT child) = 0; virtual void invokeWithValue(_parserElementT obj, const std::string &value) = 0; }; template inline T universal_pointer_cast(const std::shared_ptr &sp) { return std::static_pointer_cast(sp); } // template // inline std::shared_ptr universal_pointer_cast(const std::shared_ptr& sp){ // return std::static_pointer_cast(sp); // } template inline T universal_pointer_cast(U *p) { return static_cast(p); } template class ParserCollector : public CollectorBase<_parserElementT> { public: ParserCollector(_functorT func) : mFunc(func) { } private: virtual void invokeWithChild(_parserElementT obj, _parserElementT child) override; virtual void invokeWithValue(_parserElementT obj, const std::string &value) override; template inline void _invokeWithValue( _parserElementT obj, typename std::enable_if::value, const std::string &>::type value) { mFunc(universal_pointer_cast(obj), value); } template inline void _invokeWithValue( _parserElementT, typename std::enable_if::value, const std::string &>::type) { // no op. } #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4244) #endif template inline void _invokeWithValue(_parserElementT obj, typename std::enable_if::value, const std::string &>::type value) { mFunc(universal_pointer_cast(obj), std::atoll(value.c_str())); } #if defined(_MSC_VER) #pragma warning(pop) #endif template inline void _invokeWithValue(_parserElementT obj, typename std::enable_if::value, const std::string &>::type value) { mFunc(universal_pointer_cast(obj), std::atof(value.c_str())); } template inline void _invokeWithChild(_parserElementT, typename std::enable_if::value, _parserElementT>::type) { } template inline void _invokeWithChild(_parserElementT, typename std::enable_if::value, _parserElementT>::type) { } template inline void _invokeWithChild(_parserElementT, typename std::enable_if::value, _parserElementT>::type) { } template inline void _invokeWithChild( typename std::enable_if::value, _parserElementT>::type obj, typename std::enable_if::value, _parserElementT>::type child) { mFunc( universal_pointer_cast::type>(obj), universal_pointer_cast::type>( child)); } _functorT mFunc; }; template class HandlerContext; template class Parser; class HandlerContextBase; template class ParserHandlerBase { friend class HandlerContext<_parserElementT>; public: virtual ~ParserHandlerBase() = default; virtual _parserElementT invoke(const std::string &input, size_t begin, size_t count) = 0; std::shared_ptr> createContext(); inline const std::string &getRulename() const { return mRulename; } protected: void releaseContext(const std::shared_ptr> &ctx); ParserHandlerBase(const Parser<_parserElementT> &parser, const std::string &name); void installCollector(const std::string &rulename, CollectorBase<_parserElementT> *collector); CollectorBase<_parserElementT> *getCollector(unsigned int rule_id) const; private: std::map>> mCollectors; const Parser<_parserElementT> &mParser; std::string mRulename; std::shared_ptr> mCachedContext; #if BELR_USE_ATOMIC std::atomic_flag mCacheLocked = ATOMIC_FLAG_INIT; #endif }; template class ParserHandler : public ParserHandlerBase<_parserElementT> { public: typedef typename _createElementFn::result_type _derivedParserElementT; ParserHandler(const Parser<_parserElementT> &parser, const std::string &rulename, _createElementFn create) : ParserHandlerBase<_parserElementT>(parser, rulename), mHandlerCreateFunc(create) { } _parserElementT invoke(const std::string &input, size_t begin, size_t count) override; template ParserHandler<_createElementFn, _parserElementT> *setCollector(const std::string &child_rule_name, _functorT fn) { this->installCollector(child_rule_name, new ParserCollector<_functorT, _parserElementT>(fn)); return this; } private: template typename std::enable_if::value, _derivedParserElementT>::type _invoke(const std::string &value, size_t begin, size_t count) { // Case where the create func accepts two strings for rulename and matched characters. return mHandlerCreateFunc(this->getRulename(), value.substr(begin, count)); } template typename std::enable_if>::value, _derivedParserElementT>::type _invoke(const std::string &, size_t, size_t) { return mHandlerCreateFunc(); } _createElementFn mHandlerCreateFunc; }; template class Assignment { public: Assignment(CollectorBase<_parserElementT> *c, size_t begin, size_t count, const std::shared_ptr> &child) : mCollector(c), mBegin(begin), mCount(count), mChild(child) { } void invoke(_parserElementT parent, const std::string &input); private: CollectorBase<_parserElementT> *mCollector; // not a shared_ptr for optimization, the collector cannot disapear size_t mBegin; size_t mCount; std::shared_ptr> mChild; }; class HandlerContextBase : public std::enable_shared_from_this { public: BELR_PUBLIC virtual ~HandlerContextBase() = default; }; template class HandlerContext : public HandlerContextBase { public: HandlerContext(ParserHandlerBase<_parserElementT> *handler); void setChild(unsigned int subrule_id, size_t begin, size_t count, const std::shared_ptr &child); _parserElementT realize(const std::string &input, size_t begin, size_t count); std::shared_ptr> branch(); void merge(const std::shared_ptr> &other); size_t getLastIterator() const; void undoAssignments(size_t pos); void recycle(); private: ParserHandlerBase<_parserElementT> &mHandler; std::vector> mAssignments; }; struct ParserLocalContext { void set(const std::shared_ptr &hc, const std::shared_ptr &rec, size_t pos) { mHandlerContext = hc; mRecognizer = rec.get(); mAssignmentPos = pos; } std::shared_ptr mHandlerContext; Recognizer *mRecognizer = nullptr; // not a shared ptr to optimize, the object can't disapear in the context of use of ParserLocalContext. size_t mAssignmentPos = 0; }; class ParserContextBase { public: virtual ~ParserContextBase() = default; virtual void beginParse(ParserLocalContext &ctx, const std::shared_ptr &rec) = 0; virtual void endParse(const ParserLocalContext &ctx, const std::string &input, size_t begin, size_t count) = 0; virtual std::shared_ptr branch() = 0; virtual void merge(const std::shared_ptr &other) = 0; virtual void removeBranch(const std::shared_ptr &other) = 0; }; template class ParserContext : public ParserContextBase { public: ParserContext(Parser<_parserElementT> &parser); _parserElementT createRootObject(const std::string &input, size_t count); protected: void beginParse(ParserLocalContext &ctx, const std::shared_ptr &rec) override; void endParse(const ParserLocalContext &ctx, const std::string &input, size_t begin, size_t count) override; std::shared_ptr branch() override; void merge(const std::shared_ptr &other) override; void removeBranch(const std::shared_ptr &other) override; void _beginParse(ParserLocalContext &ctx, const std::shared_ptr &rec); void _endParse(const ParserLocalContext &ctx, const std::string &input, size_t begin, size_t count); std::shared_ptr> _branch(); void _merge(const std::shared_ptr> &other); void _removeBranch(const std::shared_ptr> &other); private: Parser<_parserElementT> &mParser; std::list>> mHandlerStack; std::shared_ptr> mRoot; }; /** * Parser class. * This template class allows to parse a text input using a Grammar object describing the language of the input to be *parsed. The template argument _parserElementT must be a base class for all elements that will be created to represent *the result of the parsing. This can be 'void*' if the parser is implemented in C, but can also be any C++ class *provided that each type representing a parsed entity inherits from this class. **/ template class Parser { friend class ParserContext<_parserElementT>; friend class ParserHandlerBase<_parserElementT>; public: Parser(const std::shared_ptr &grammar); template ParserHandler<_createElementFn, _parserElementT> *setHandler(const std::string &rulename, _createElementFn handler) { auto ret = new ParserHandler<_createElementFn, _parserElementT>(*this, rulename, handler); installHandler(ret); return ret; } _parserElementT parseInput(const std::string &rulename, const std::string &input, size_t *parsed_size); private: ParserHandlerBase<_parserElementT> *getHandler(unsigned int); void installHandler(ParserHandlerBase<_parserElementT> *handler); std::shared_ptr mGrammar; std::map>> mHandlers; std::unique_ptr> mNullHandler; std::unique_ptr> mNullCollector; }; class DebugElement { public: DebugElement(const std::string &rulename, const std::string &value); static std::shared_ptr create(const std::string &rulename, const std::string &value); void addChild(const std::shared_ptr &e); BELR_PUBLIC void findChildren(const std::string &rulename, std::list> &retlist) const; BELR_PUBLIC std::ostream &tostream(int level, std::ostream &str) const; BELR_PUBLIC const std::string &getValue() const; private: std::string mRulename; std::string mValue; std::list> mChildren; }; class DebugParser : protected Parser> { public: BELR_PUBLIC DebugParser(const std::shared_ptr &grammar); BELR_PUBLIC void setObservedRules(const std::list &rules); BELR_PUBLIC std::shared_ptr parseInput(const std::string &rulename, const std::string &input, size_t *parsed_size); }; // // Utility functions for handlers/collectors objects instantiation and properties accessors // /* For parser relying on raw pointers */ template inline std::function<_retT()> make_fn(_retT (*arg)()) { return std::function<_retT()>(arg); } template inline std::function<_retT(_arg1T, _arg2T)> make_fn(_retT (*arg)(_arg1T, _arg2T)) { return std::function<_retT(_arg1T, _arg2T)>(arg); } template struct StringToCharMapper { StringToCharMapper(const std::function<_retT(_arg1T, const char *)> &cfunc) : mCFunc(cfunc) { } std::function<_retT(_arg1T, const char *)> mCFunc; _retT operator()(_arg1T arg1, const std::string &arg2) { return mCFunc(arg1, arg2.c_str()); } }; template inline std::function<_retT(_arg1T, const std::string &)> make_fn(_retT (*arg)(_arg1T, const char *)) { return StringToCharMapper<_retT, _arg1T>(arg); } template inline std::function make_fn(void (_klassT::*arg)(_argT)) { return std::function(std::mem_fn(arg)); } /* For parsers using shared_ptr<> */ template inline std::function()> make_fn() { return std::bind(&std::make_shared<_retT>); } template inline std::function, _argT)> make_sfn(void (_klassT::*arg)(_argT)) { return std::function, _argT)>(std::mem_fn(arg)); } // ============================================================================= // Parser impl. // ============================================================================= BELR_PUBLIC void fatal(const char *message); template void ParserCollector<_functorT, _parserElementT>::invokeWithChild(_parserElementT obj, _parserElementT child) { _invokeWithChild(obj, child); } template void ParserCollector<_functorT, _parserElementT>::invokeWithValue(_parserElementT obj, const std::string &value) { _invokeWithValue(obj, value); } template void Assignment<_parserElementT>::invoke(_parserElementT parent, const std::string &input) { if (mChild) { mCollector->invokeWithChild(parent, mChild->realize(input, mBegin, mCount)); } else { mCollector->invokeWithValue(parent, input.substr(mBegin, mCount)); } } // // HandlerContext template class implementation // template HandlerContext<_parserElementT>::HandlerContext(ParserHandlerBase<_parserElementT> *handler) : mHandler(*handler) { } template void HandlerContext<_parserElementT>::setChild(unsigned int subrule_id, size_t begin, size_t count, const std::shared_ptr> &child) { auto collector = mHandler.getCollector(subrule_id); if (collector) { mAssignments.push_back(Assignment<_parserElementT>(collector, begin, count, child)); } } template _parserElementT HandlerContext<_parserElementT>::realize(const std::string &input, size_t begin, size_t count) { _parserElementT ret = mHandler.invoke(input, begin, count); for (auto it = mAssignments.begin(); it != mAssignments.end(); ++it) { (*it).invoke(ret, input); } return ret; } template std::shared_ptr> HandlerContext<_parserElementT>::branch() { return mHandler.createContext(); } template void HandlerContext<_parserElementT>::merge(const std::shared_ptr> &other) { for (auto it = other->mAssignments.begin(); it != other->mAssignments.end(); ++it) { mAssignments.emplace_back(*it); } } template size_t HandlerContext<_parserElementT>::getLastIterator() const { return mAssignments.size(); } template void HandlerContext<_parserElementT>::undoAssignments(size_t pos) { mAssignments.erase(mAssignments.begin() + (long)pos, mAssignments.end()); } template void HandlerContext<_parserElementT>::recycle() { mAssignments.clear(); mHandler.releaseContext(std::static_pointer_cast>(shared_from_this())); } // // ParserHandlerBase template class implementation // template ParserHandlerBase<_parserElementT>::ParserHandlerBase(const Parser<_parserElementT> &parser, const std::string &name) : mParser(parser), mRulename(tolower(name)), mCachedContext(nullptr) { } template void ParserHandlerBase<_parserElementT>::installCollector(const std::string &rulename, CollectorBase<_parserElementT> *collector) { std::shared_ptr rec = mParser.mGrammar->findRule(rulename); if (!rec) { std::ostringstream ostr; ostr << "There is no rule '" << rulename << "' in the grammar."; fatal(ostr.str().c_str()); return; } mCollectors[rec->getId()].reset(collector); } template CollectorBase<_parserElementT> *ParserHandlerBase<_parserElementT>::getCollector(unsigned int rule_id) const { auto it = mCollectors.find(rule_id); if (it != mCollectors.end()) return (*it).second.get(); return mParser.mNullCollector.get(); } template void ParserHandlerBase<_parserElementT>::releaseContext(const std::shared_ptr> &ctx) { #if BELR_USE_ATOMIC if (mCacheLocked.test_and_set(std::memory_order_relaxed) == false){ mCachedContext = ctx; mCacheLocked.clear(std::memory_order_relaxed); } #else mCachedContext=ctx; #endif } template std::shared_ptr> ParserHandlerBase<_parserElementT>::createContext() { #if BELR_USE_ATOMIC std::shared_ptr> ret; if (mCacheLocked.test_and_set(std::memory_order_relaxed) == false){ if (mCachedContext){ ret = mCachedContext; mCachedContext.reset(); } mCacheLocked.clear(std::memory_order_relaxed); } if (!ret) ret = std::make_shared>(this); return ret; #else if (mCachedContext) { std::shared_ptr> ret = mCachedContext; mCachedContext.reset(); return ret; } return std::make_shared>(this); #endif } // // ParserHandler template implementation // template _parserElementT ParserHandler<_createElementFn, _parserElementT>::invoke(const std::string &input, size_t begin, size_t count) { return universal_pointer_cast<_parserElementT>(_invoke<_createElementFn>(input, begin, count)); } // // ParserContext template class implementation // template ParserContext<_parserElementT>::ParserContext(Parser<_parserElementT> &parser) : mParser(parser) { } template inline void ParserContext<_parserElementT>::_beginParse(ParserLocalContext &lctx, const std::shared_ptr &rec) { std::shared_ptr ctx; auto h = mParser.getHandler(rec->getId()); if (h) { ctx = h->createContext(); mHandlerStack.push_back(std::static_pointer_cast>(ctx)); } if (mHandlerStack.empty()) { fatal("Cannot parse when mHandlerStack is empty. You must define a top-level rule handler."); } lctx.set(ctx, rec, mHandlerStack.back()->getLastIterator()); } template inline void ParserContext<_parserElementT>::_endParse(const ParserLocalContext &localctx, const std::string &, size_t begin, size_t count) { if (localctx.mHandlerContext) { mHandlerStack.pop_back(); if (count != std::string::npos && count > 0) { if (!mHandlerStack.empty()) { /*assign object to parent */ mHandlerStack.back()->setChild( localctx.mRecognizer->getId(), begin, count, std::static_pointer_cast>(localctx.mHandlerContext)); } else { /*no parent, this is our root object*/ mRoot = std::static_pointer_cast>(localctx.mHandlerContext); } } else { // no match std::static_pointer_cast>(localctx.mHandlerContext)->recycle(); } } else { if (count != std::string::npos && count > 0) { /*assign std::string to parent */ if (localctx.mRecognizer->getId() != 0) mHandlerStack.back()->setChild(localctx.mRecognizer->getId(), begin, count, nullptr); } else { mHandlerStack.back()->undoAssignments(localctx.mAssignmentPos); } } } template _parserElementT ParserContext<_parserElementT>::createRootObject(const std::string &input, size_t count) { return mRoot ? mRoot->realize(input, 0, count) : nullptr; } template inline std::shared_ptr> ParserContext<_parserElementT>::_branch() { if (mHandlerStack.empty()) { fatal("Cannot branch while stack is empty"); } std::shared_ptr> ret = mHandlerStack.back()->branch(); mHandlerStack.push_back(ret); return ret; } template inline void ParserContext<_parserElementT>::_merge(const std::shared_ptr> &other) { if (mHandlerStack.back() != other) { fatal("The branch being merged is not the last one of the stack !"); } mHandlerStack.pop_back(); mHandlerStack.back()->merge(other); other->recycle(); } template inline void ParserContext<_parserElementT>::_removeBranch(const std::shared_ptr> &other) { auto it = find(mHandlerStack.rbegin(), mHandlerStack.rend(), other); if (it == mHandlerStack.rend()) { fatal("A branch could not be found in the stack while removing it !"); } else { advance(it, 1); mHandlerStack.erase(it.base()); } other->recycle(); } template void ParserContext<_parserElementT>::beginParse(ParserLocalContext &ctx, const std::shared_ptr &rec) { _beginParse(ctx, rec); } template void ParserContext<_parserElementT>::endParse(const ParserLocalContext &localctx, const std::string &input, size_t begin, size_t count) { _endParse(localctx, input, begin, count); } template std::shared_ptr ParserContext<_parserElementT>::branch() { return _branch(); } template void ParserContext<_parserElementT>::merge(const std::shared_ptr &other) { _merge(std::static_pointer_cast>(other)); } template void ParserContext<_parserElementT>::removeBranch(const std::shared_ptr &other) { _removeBranch(std::static_pointer_cast>(other)); } // // Parser template class implementation // template Parser<_parserElementT>::Parser(const std::shared_ptr &grammar) : mGrammar(grammar) { if (!mGrammar->isComplete()) { fatal("Grammar not complete, aborting."); return; } } template ParserHandlerBase<_parserElementT> *Parser<_parserElementT>::getHandler(unsigned int rule_id) { auto it = mHandlers.find(rule_id); if (it == mHandlers.end()) return mNullHandler.get(); return (*it).second.get(); } template void Parser<_parserElementT>::installHandler(ParserHandlerBase<_parserElementT> *handler) { std::shared_ptr rec = mGrammar->findRule(handler->getRulename()); if (!rec) { std::ostringstream str; str << "There is no rule '" << handler->getRulename() << "' in the grammar."; fatal(str.str().c_str()); } mHandlers[rec->getId()].reset(handler); } template _parserElementT Parser<_parserElementT>::parseInput(const std::string &rulename, const std::string &input, size_t *parsed_size) { size_t parsed; std::shared_ptr rec = mGrammar->getRule(rulename); ParserContext<_parserElementT> pctx(*this); auto h = getHandler(rec->getId()); if (!h) { std::ostringstream str; str << "There is no handler for rule '" << rulename << "'."; fatal(str.str().c_str()); } // auto t_start = std::chrono::high_resolution_clock::now(); parsed = rec->feed(pctx, input, 0); // auto t_end = std::chrono::high_resolution_clock::now(); // cout<<"Recognition done in "<(t_end-t_start).count()<<" // milliseconds"< $ ) target_compile_definitions(belr PRIVATE "BCTBX_LOG_DOMAIN=\"belr\"") target_link_libraries(belr PUBLIC ${BCToolbox_TARGET} PRIVATE ${LIBS}) if(BUILD_SHARED_LIBS) if(APPLE) set_target_properties(belr PROPERTIES FRAMEWORK TRUE MACOSX_FRAMEWORK_IDENTIFIER org.linphone.belr MACOSX_FRAMEWORK_INFO_PLIST "${PROJECT_SOURCE_DIR}/build/osx/Info.plist.in" PUBLIC_HEADER "${BELR_HEADER_FILES}" ) endif() if(MSVC) install(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE CONFIGURATIONS Debug RelWithDebInfo ) endif() endif() install(TARGETS belr EXPORT ${PROJECT_NAME}Targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} FRAMEWORK DESTINATION Frameworks PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE ) install(FILES ${BELR_HEADER_FILES} DESTINATION include/belr PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ ) belr-5.3.105/src/abnf.cpp000066400000000000000000000375461464614247000150410ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "belr/abnf.h" using namespace std; using namespace belr; // ============================================================================= /* * CoreRules grammar **/ CoreRules::CoreRules() : Grammar("core rules") { alpha(); bit(); char_(); cr(); lf(); crlf(); ctl(); digit(); hexdig(); dquote(); htab(); octet(); sp(); vchar(); wsp(); lwsp(); } void CoreRules::alpha() { shared_ptr selector = Foundation::selector(true); selector->addRecognizer(Utils::char_range('a', 'z')); selector->addRecognizer(Utils::char_range('A', 'Z')); addRule("alpha", selector); } void CoreRules::bit() { shared_ptr selector = Foundation::selector(true); selector->addRecognizer(make_shared('0')); selector->addRecognizer(make_shared('1')); addRule("bit", selector); } void CoreRules::char_() { addRule("char", Utils::char_range(0x1, 0x7f)); } void CoreRules::cr() { addRule("cr", Foundation::charRecognizer(0x0d, true)); } void CoreRules::lf() { addRule("lf", Foundation::charRecognizer(0x0a, true)); } void CoreRules::crlf() { addRule("crlf", Foundation::sequence()->addRecognizer(getRule("cr"))->addRecognizer(getRule("lf"))); } void CoreRules::ctl() { addRule("ctl", Foundation::selector(true) ->addRecognizer(Utils::char_range(0x00, 0x1f)) ->addRecognizer(Foundation::charRecognizer(0x7f, true))); } void CoreRules::digit() { addRule("digit", Utils::char_range(0x30, 0x39)); } void CoreRules::dquote() { addRule("dquote", Foundation::charRecognizer(0x22, true)); } void CoreRules::hexdig() { addRule("hexdig", Foundation::selector(true) ->addRecognizer(getRule("digit")) ->addRecognizer(Foundation::charRecognizer('A')) ->addRecognizer(Foundation::charRecognizer('B')) ->addRecognizer(Foundation::charRecognizer('C')) ->addRecognizer(Foundation::charRecognizer('D')) ->addRecognizer(Foundation::charRecognizer('E')) ->addRecognizer(Foundation::charRecognizer('F'))); } void CoreRules::htab() { addRule("htab", Foundation::charRecognizer(0x09, true)); } void CoreRules::octet() { addRule("octet", Utils::char_range(0, 0xff)); } void CoreRules::sp() { addRule("sp", Foundation::charRecognizer(0x20, true)); } void CoreRules::vchar() { addRule("vchar", Utils::char_range(0x21, 0x7e)); } void CoreRules::wsp() { addRule("wsp", Foundation::selector(true)->addRecognizer(getRule("sp"))->addRecognizer(getRule("htab"))); } void CoreRules::lwsp() { addRule("lwsp", Foundation::loop()->setRecognizer( Foundation::selector(true) ->addRecognizer(getRule("wsp")) ->addRecognizer( Foundation::sequence()->addRecognizer(getRule("crlf"))->addRecognizer(getRule("wsp"))))); } /* * ABNF grammar **/ ABNFGrammar::ABNFGrammar() : Grammar("ABNF") { include(make_shared()); char_val(); bin_val(); dec_val(); hex_val(); num_val(); prose_val(); comment(); c_nl(); c_wsp(); rulename(); repeat_count(); repeat_max(); repeat_min(); repeat(); defined_as(); rulelist(); rule(); elements(); alternation(); concatenation(); repetition(); element(); group(); option(); crlf_or_lf(); } void ABNFGrammar::crlf_or_lf() { addRule("crlf-or-lf", Foundation::selector()->addRecognizer(getRule("crlf"))->addRecognizer(getRule("lf"))); } void ABNFGrammar::comment() { addRule("comment", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer(';', true)) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::selector(true)->addRecognizer(getRule("wsp"))->addRecognizer(getRule("vchar")))) //->addRecognizer(getRule("crlf")) ->addRecognizer(getRule("crlf-or-lf"))); } void ABNFGrammar::c_nl() { addRule("c-nl", Foundation::selector() ->addRecognizer(getRule("comment")) //->addRecognizer(getRule("crlf"))); ->addRecognizer(getRule("crlf-or-lf"))); } void ABNFGrammar::c_wsp() { addRule("c-wsp", Foundation::selector() ->addRecognizer(getRule("wsp")) ->addRecognizer(Foundation::sequence()->addRecognizer(getRule("c-nl"))->addRecognizer(getRule("wsp")))); } /* ALPHA *(ALPHA / DIGIT / "-")*/ void ABNFGrammar::rulename() { addRule("rulename", Foundation::sequence() ->addRecognizer(getRule("alpha")) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::selector(true) ->addRecognizer(getRule("alpha")) ->addRecognizer(getRule("digit")) ->addRecognizer(Foundation::charRecognizer('-'))))); } void ABNFGrammar::repeat_count() { addRule("repeat-count", Foundation::loop()->setRecognizer(getRule("digit"), 1)); } void ABNFGrammar::repeat_max() { addRule("repeat-max", Foundation::loop()->setRecognizer(getRule("digit"))); } void ABNFGrammar::repeat_min() { addRule("repeat-min", Foundation::loop()->setRecognizer(getRule("digit"))); } /* 1*DIGIT / (*DIGIT "*" *DIGIT) */ void ABNFGrammar::repeat() { addRule("repeat", Foundation::selector() ->addRecognizer(getRule("repeat-count")) ->addRecognizer(Foundation::sequence() ->addRecognizer(getRule("repeat-min")) ->addRecognizer(Foundation::charRecognizer('*')) ->addRecognizer(getRule("repeat-max")))); } /* *c-wsp ("=" / "=/") *c-wsp */ void ABNFGrammar::defined_as() { addRule("defined-as", Foundation::sequence() ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(Foundation::selector() ->addRecognizer(Foundation::charRecognizer('=')) ->addRecognizer(Utils::literal("=/"))) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp")))); } /* 1*( rule / (*c-wsp c-nl) ) */ void ABNFGrammar::rulelist() { addRule("rulelist", Foundation::loop()->setRecognizer( Foundation::selector() ->addRecognizer(getRule("rule")) ->addRecognizer(Foundation::sequence() ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(getRule("c-nl"))), 1)); } /* rulename defined-as elements c-nl */ void ABNFGrammar::rule() { addRule("rule", Foundation::sequence() ->addRecognizer(getRule("rulename")) ->addRecognizer(getRule("defined-as")) ->addRecognizer(getRule("elements")) ->addRecognizer(getRule("c-nl"))); } /* alternation *c-wsp */ void ABNFGrammar::elements() { addRule("elements", Foundation::sequence() ->addRecognizer(getRule("alternation")) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp")))); } /* alternation = concatenation *(*c-wsp "/" *c-wsp concatenation) */ void ABNFGrammar::alternation() { addRule("alternation", Foundation::sequence() ->addRecognizer(getRule("concatenation")) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::sequence() ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(Foundation::charRecognizer('/')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(getRule("concatenation"))))); } /* concatenation = repetition *(1*c-wsp repetition) */ void ABNFGrammar::concatenation() { addRule("concatenation", Foundation::sequence() ->addRecognizer(getRule("repetition")) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::sequence() ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"), 1)) ->addRecognizer(getRule("repetition"))))); } /* repetition = [repeat] element */ void ABNFGrammar::repetition() { addRule("repetition", Foundation::sequence() ->addRecognizer(Foundation::loop()->setRecognizer(getRule("repeat"), 0, 1)) ->addRecognizer(getRule("element"))); } /* * element = rulename / group / option / * char-val / num-val / prose-val */ void ABNFGrammar::element() { addRule("element", Foundation::selector() ->addRecognizer(getRule("rulename")) ->addRecognizer(getRule("group")) ->addRecognizer(getRule("option")) ->addRecognizer(getRule("char-val")) ->addRecognizer(getRule("num-val")) ->addRecognizer(getRule("prose-val"))); } /* "(" *c-wsp alternation *c-wsp ")" */ void ABNFGrammar::group() { addRule("group", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('(')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(getRule("alternation")) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(Foundation::charRecognizer(')'))); } /* "[" *c-wsp alternation *c-wsp "]" */ void ABNFGrammar::option() { addRule("option", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('[')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(getRule("alternation")) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("c-wsp"))) ->addRecognizer(Foundation::charRecognizer(']'))); } /* * DQUOTE *(%x20-21 / %x23-7E) DQUOTE **/ void ABNFGrammar::char_val() { addRule("char-val", Foundation::sequence() ->addRecognizer(getRule("dquote")) ->addRecognizer(Foundation::loop()->setRecognizer(Foundation::selector(true) ->addRecognizer(Utils::char_range(0x20, 0x21)) ->addRecognizer(Utils::char_range(0x23, 0x7e)))) ->addRecognizer(getRule("dquote"))); } /* * num-val = "%" (bin-val / dec-val / hex-val) */ void ABNFGrammar::num_val() { addRule("num-val", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('%')) ->addRecognizer(Foundation::selector(true) ->addRecognizer(getRule("bin-val")) ->addRecognizer(getRule("dec-val")) ->addRecognizer(getRule("hex-val")))); } /* * prose-val = "<" *(%x20-3D / %x3F-7E) ">" */ void ABNFGrammar::prose_val() { addRule("prose-val", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('<')) ->addRecognizer(Foundation::loop()->setRecognizer(Foundation::selector(true) ->addRecognizer(Utils::char_range(0x20, 0x3d)) ->addRecognizer(Utils::char_range(0x3f, 0x7e)))) ->addRecognizer(Foundation::charRecognizer('>'))); } /* * "b" 1*BIT [ 1*("." 1*BIT) / ("-" 1*BIT) ] */ void ABNFGrammar::bin_val() { addRule("bin-val", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('b')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("bit"), 1)) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::selector() ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('.')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("bit"), 1)))) ->addRecognizer(Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('-')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("bit"), 1))), 0, 1))); } /* dec-val = "d" 1*DIGIT [ 1*("." 1*DIGIT) / ("-" 1*DIGIT) ] */ void ABNFGrammar::dec_val() { addRule("dec-val", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('d')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("digit"), 1)) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::selector() ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('.')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("digit"), 1)))) ->addRecognizer(Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('-')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("digit"), 1))), 0, 1))); } /* * hex-val = "x" 1*HEXDIG [ 1*("." 1*HEXDIG) / ("-" 1*HEXDIG) ] */ void ABNFGrammar::hex_val() { addRule("hex-val", Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('x')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("hexdig"), 1)) ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::selector() ->addRecognizer(Foundation::loop()->setRecognizer( Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('.')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("hexdig"), 1)))) ->addRecognizer(Foundation::sequence() ->addRecognizer(Foundation::charRecognizer('-')) ->addRecognizer(Foundation::loop()->setRecognizer(getRule("hexdig"), 1))), 0, 1))); } belr-5.3.105/src/belr.cpp000066400000000000000000000553121464614247000150460ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /* * To troubleshoot parsing, un comment the two following defines to get _very_ verbose logs. */ // #define BCTBX_DEBUG_MODE 1 // #define BELR_DEBUG 1 #include #include "belr/belr.h" #include "belr/parser.h" #include "binarystream.h" #include "common.h" using namespace std; namespace belr { void fatal(const char *message) { bctbx_fatal("%s", message); } /* Dummy ParserContext, actually used for optimization phase, to let invoke the feed() function without * instanciating anything.*/ class DummyParserContext : public ParserContextBase { public: virtual void beginParse(BCTBX_UNUSED(ParserLocalContext &ctx), BCTBX_UNUSED(const std::shared_ptr &rec)) override { } virtual void endParse(BCTBX_UNUSED(const ParserLocalContext &ctx), BCTBX_UNUSED(const std::string &input), BCTBX_UNUSED(size_t begin), BCTBX_UNUSED(size_t count)) override { } virtual std::shared_ptr branch() override { return nullptr; } virtual void merge(BCTBX_UNUSED(const std::shared_ptr &other)) override { } virtual void removeBranch(BCTBX_UNUSED(const std::shared_ptr &other)) override { } }; // ============================================================================= TransitionMap::TransitionMap() { for (size_t i = 0; i < sizeof(mPossibleChars) / sizeof(bool); ++i) mPossibleChars[i] = false; } bool TransitionMap::intersect(const TransitionMap *other) { for (size_t i = 0; i < sizeof(mPossibleChars) / sizeof(bool); ++i) { if (mPossibleChars[i] && other->mPossibleChars[i]) return true; } return false; } bool TransitionMap::intersect(const TransitionMap *other, TransitionMap *result) { bool ret = false; for (size_t i = 0; i < sizeof(mPossibleChars) / sizeof(bool); ++i) { bool tmp = mPossibleChars[i] && other->mPossibleChars[i]; result->mPossibleChars[i] = tmp; if (tmp) ret = true; } return ret; } void TransitionMap::merge(const TransitionMap *other) { for (size_t i = 0; i < sizeof(mPossibleChars) / sizeof(bool); ++i) { if (other->mPossibleChars[i]) mPossibleChars[i] = true; } } void Recognizer::setName(const std::string &name) { static unsigned int id_base = 0; mName = name; /* every recognizer that is given a name is given also a unique id*/ mId = ++id_base; } void Recognizer::serialize(BinaryOutputStream &fstr, bool topLevel) { RecognizerTypeId tid = CharRecognizerId; if (typeid(*this) == typeid(CharRecognizer)) tid = CharRecognizerId; else if (typeid(*this) == typeid(Selector)) tid = SelectorId; else if (typeid(*this) == typeid(Loop)) tid = LoopId; else if (typeid(*this) == typeid(ExclusiveSelector)) tid = ExclusiveSelectorId; else if (typeid(*this) == typeid(CharRange)) tid = CharRangeId; else if (typeid(*this) == typeid(Literal)) tid = LiteralId; else if (typeid(*this) == typeid(Sequence)) tid = SequenceId; else if (typeid(*this) == typeid(RecognizerPointer)) tid = PointerId; else if (typeid(*this) == typeid(RecognizerAlias)) tid = AliasId; else bctbx_fatal("Unsupported Recognizer derived type."); unsigned char type_byte = (unsigned char)tid; if (tid == PointerId) { /* * It is useless to serialize a RecognizerPointer, which is only a trick to break loops in recognizer chains. * Instead we follow the pointer and serialize the pointed recognizer. **/ dynamic_cast(this)->getPointed()->serialize(fstr, topLevel); return; } if (topLevel || mName.empty()) { // write the type fstr << type_byte; fstr << mName; // then invoked derived class serialization _serialize(fstr); } else { /* If we are not a top level, and mName is defined, we are referencing another rule of the grammar. * There is then no need to recurse.*/ type_byte = (unsigned char)RuleRefId; fstr << type_byte; fstr << mName; } } Recognizer::Recognizer(BinaryGrammarBuilder &istr) { // read the recognizer name: string name; istr >> name; if (!name.empty()) setName(name); } std::shared_ptr Recognizer::build(BinaryGrammarBuilder &istr) { shared_ptr ret; unsigned char byte; RecognizerTypeId tid; // read the type byte istr >> byte; tid = (RecognizerTypeId)byte; switch (tid) { case CharRecognizerId: ret = make_shared(istr); break; case SelectorId: ret = make_shared(istr); break; case ExclusiveSelectorId: ret = make_shared(istr); break; case LoopId: ret = make_shared(istr); break; case SequenceId: ret = make_shared(istr); break; case CharRangeId: ret = make_shared(istr); break; case LiteralId: ret = make_shared(istr); break; case RuleRefId: { string name; istr >> name; ret = istr.getRule(name); } break; case PointerId: break; case AliasId: ret = make_shared(istr); break; } if (!ret) { BCTBX_SLOGE << "Unsupported recognizer id " << (int)byte << " at pos " << istr.tellg(); } else { // if (!ret->getName().empty()){ // BCTBX_SLOGD<<"Built recognizer "<getName(); // } } return ret; } const string &Recognizer::getName() const { return mName; } size_t Recognizer::feed(ParserContextBase &ctx, const string &input, size_t pos) { size_t match; #ifdef BELR_DEBUG BCTBX_SLOGD << "Trying to match: " << mName; #endif ParserLocalContext hctx; ctx.beginParse(hctx, shared_from_this()); match = _feed(ctx, input, pos); if (match != string::npos && match > 0) { #ifdef BELR_DEBUG if (mName.size() > 0) { string matched = input.substr(pos, match); BCTBX_SLOGD << "Matched recognizer '" << mName << "' with sequence '" << matched << "'."; } #endif } ctx.endParse(hctx, input, pos, match); return match; } bool Recognizer::getTransitionMap(TransitionMap *mask) { bool ret = _getTransitionMap(mask); if (0 /*!mName.empty()*/) { BCTBX_SLOGD << "TransitionMap after " << mName; ostringstream mapss; for (int i = 0; i < 256; ++i) { if (mask->mPossibleChars[i]) mapss << (char)i; } BCTBX_SLOGD << mapss.str(); } return ret; } bool Recognizer::_getTransitionMap(TransitionMap *mask) { string input; input.resize(2, '\0'); for (int i = 0; i < 256; ++i) { input[0] = i; DummyParserContext pctx; if (feed(pctx, input, 0) == 1) mask->mPossibleChars[i] = true; } return true; } void Recognizer::optimize() { optimize(0); } void Recognizer::optimize(int recursionLevel) { if (recursionLevel != 0 && mId != 0) return; /*stop on rule except at level 0*/ _optimize(++recursionLevel); } CharRecognizer::CharRecognizer(int to_recognize, bool caseSensitive) : mToRecognize(to_recognize), mCaseSensitive(caseSensitive) { if (::tolower(to_recognize) == ::toupper(to_recognize)) { /*not a case caseSensitive character*/ mCaseSensitive = true; /*no need to perform a case insensitive match*/ } else if (!caseSensitive) { mToRecognize = ::tolower(mToRecognize); } } size_t CharRecognizer::_feed(BCTBX_UNUSED(ParserContextBase &ctx), const string &input, size_t pos) { int c = (unsigned char)input[pos]; if (mCaseSensitive) { return c == mToRecognize ? 1 : string::npos; } return ::tolower(c) == mToRecognize ? 1 : string::npos; } void CharRecognizer::_optimize(BCTBX_UNUSED(int recursionLevel)) { } void CharRecognizer::_serialize(BinaryOutputStream &fstr) { unsigned char charToRecognize = (unsigned char)mToRecognize; fstr << charToRecognize; fstr << (unsigned char)mCaseSensitive; } CharRecognizer::CharRecognizer(BinaryGrammarBuilder &istr) : Recognizer(istr) { unsigned char toRecognize; istr >> toRecognize; mToRecognize = toRecognize; unsigned char tmp; istr >> tmp; mCaseSensitive = !!tmp; } shared_ptr Selector::addRecognizer(const shared_ptr &r) { mElements.push_back(r); return static_pointer_cast(shared_from_this()); } bool Selector::_getTransitionMap(TransitionMap *mask) { for (auto it = mElements.begin(); it != mElements.end(); ++it) { (*it)->getTransitionMap(mask); } return true; } size_t Selector::_feedExclusive(ParserContextBase &ctx, const string &input, size_t pos) { size_t matched = 0; for (auto it = mElements.begin(); it != mElements.end(); ++it) { matched = (*it)->feed(ctx, input, pos); if (matched != string::npos && matched > 0) { return matched; } } return string::npos; } size_t Selector::_feed(ParserContextBase &ctx, const string &input, size_t pos) { if (mIsExclusive) return _feedExclusive(ctx, input, pos); size_t matched = 0; size_t bestmatch = string::npos; shared_ptr bestBranch; for (auto it = mElements.begin(); it != mElements.end(); ++it) { shared_ptr br; br = ctx.branch(); matched = (*it)->feed(ctx, input, pos); /* Matching 0 characters is considered as a valid match (string::npos is returned in case of no match) */ if (matched != string::npos && (matched > bestmatch || bestmatch == string::npos)) { bestmatch = matched; if (bestBranch) ctx.removeBranch(bestBranch); bestBranch = br; } else { ctx.removeBranch(br); } } if (bestmatch != string::npos) { ctx.merge(bestBranch); } return bestmatch; } void Selector::_serialize(BinaryOutputStream &fstr) { fstr << (unsigned char)mIsExclusive; fstr << (int)mElements.size(); for (auto it = mElements.begin(); it != mElements.end(); ++it) { (*it)->serialize(fstr); } } Selector::Selector(BinaryGrammarBuilder &istr) : Recognizer(istr) { unsigned char tmp; istr >> tmp; mIsExclusive = !!tmp; int count; istr >> count; for (int i = 0; i < count; ++i) { auto rec = Recognizer::build(istr); if (rec) mElements.push_back(rec); else break; } } /* The purpose of the optimization is to determine if a selector is exclusive, ie that only a single branch can match. * This is done by examining if the character transitions to jump to each branch (sub-recognizers) do intersect. * If no, it means that the first branch that will match during the parsing will necessarily be the good one, so that * there is no need to examine others. */ void Selector::_optimize(int recursionLevel) { for (auto it = mElements.begin(); it != mElements.end(); ++it) { (*it)->optimize(recursionLevel); } TransitionMap *all = nullptr; bool intersectionFound = false; for (auto it = mElements.begin(); it != mElements.end() && !intersectionFound; ++it) { TransitionMap *cur = new TransitionMap(); (*it)->getTransitionMap(cur); if (all) { if (cur->intersect(all)) { intersectionFound = true; } all->merge(cur); delete cur; } else all = cur; } if (all) delete all; if (!intersectionFound) { mIsExclusive = true; } } Selector::Selector(bool isExclusive) : mIsExclusive(isExclusive) { } ExclusiveSelector::ExclusiveSelector() : Selector(true) { } ExclusiveSelector::ExclusiveSelector(BinaryGrammarBuilder &istr) : Selector(istr) { } size_t ExclusiveSelector::_feed(ParserContextBase &ctx, const string &input, size_t pos) { return Selector::_feedExclusive(ctx, input, pos); } shared_ptr Sequence::addRecognizer(const shared_ptr &element) { mElements.push_back(element); return static_pointer_cast(shared_from_this()); } bool Sequence::_getTransitionMap(TransitionMap *mask) { bool isComplete = false; for (auto it = mElements.begin(); it != mElements.end(); ++it) { if ((*it)->getTransitionMap(mask)) { isComplete = true; break; } } return isComplete; } size_t Sequence::_feed(ParserContextBase &ctx, const string &input, size_t pos) { size_t matched = 0; size_t total = 0; for (auto it = mElements.begin(); it != mElements.end(); ++it) { matched = (*it)->feed(ctx, input, pos); if (matched == string::npos) { return string::npos; } pos += matched; total += matched; } return total; } void Sequence::_optimize(int recursionLevel) { for (auto it = mElements.begin(); it != mElements.end(); ++it) (*it)->optimize(recursionLevel); } void Sequence::_serialize(BinaryOutputStream &fstr) { fstr << (int)mElements.size(); for (auto it = mElements.begin(); it != mElements.end(); ++it) { (*it)->serialize(fstr); } } Sequence::Sequence(BinaryGrammarBuilder &istr) : Recognizer(istr) { int count; istr >> count; for (int i = 0; i < count; ++i) { shared_ptr rec; rec = Recognizer::build(istr); if (rec) mElements.push_back(rec); else break; } } shared_ptr Loop::setRecognizer(const shared_ptr &element, int min, int max) { mMin = min; mMax = max; mRecognizer = element; return static_pointer_cast(shared_from_this()); } size_t Loop::_feed(ParserContextBase &ctx, const string &input, size_t pos) { size_t matched = 0; size_t total = 0; int repeat; for (repeat = 0; (mMax != -1 ? repeat < mMax : true) && input[pos] != '\0'; repeat++) { matched = mRecognizer->feed(ctx, input, pos); if (matched == string::npos) break; total += matched; pos += matched; } if (repeat < mMin) return string::npos; return total; } bool Loop::_getTransitionMap(TransitionMap *mask) { mRecognizer->getTransitionMap(mask); return mMin != 0; // we must say to upper layer that this loop recognizer is allowed to be optional by returning FALSE } void Loop::_serialize(BinaryOutputStream &fstr) { fstr << mMin; fstr << mMax; mRecognizer->serialize(fstr); } Loop::Loop(BinaryGrammarBuilder &istr) : Recognizer(istr) { istr >> mMin; istr >> mMax; mRecognizer = Recognizer::build(istr); } void Loop::_optimize(int recursionLevel) { mRecognizer->optimize(recursionLevel); } CharRange::CharRange(int begin, int end) : mBegin(begin), mEnd(end) { } size_t CharRange::_feed(BCTBX_UNUSED(ParserContextBase &ctx), const string &input, size_t pos) { int c = (unsigned char)input[pos]; if (c >= mBegin && c <= mEnd) return 1; return string::npos; } void CharRange::_optimize(BCTBX_UNUSED(int recursionLevel)) { } void CharRange::_serialize(BinaryOutputStream &fstr) { unsigned char begin, end; begin = (unsigned char)mBegin; end = (unsigned char)mEnd; fstr << begin; fstr << end; } CharRange::CharRange(BinaryGrammarBuilder &istr) : Recognizer(istr) { unsigned char begin, end; istr >> begin; istr >> end; mBegin = begin; mEnd = end; } shared_ptr Foundation::charRecognizer(int character, bool caseSensitive) { return make_shared(character, caseSensitive); } shared_ptr Foundation::selector(bool isExclusive) { return isExclusive ? make_shared() : make_shared(); } shared_ptr Foundation::sequence() { return make_shared(); } shared_ptr Foundation::loop() { return make_shared(); } Literal::Literal(const string &lit) : mLiteral(tolower(lit)), mLiteralSize(mLiteral.size()) { } size_t Literal::_feed(BCTBX_UNUSED(ParserContextBase &ctx), const string &input, size_t pos) { size_t i; for (i = 0; i < mLiteralSize; ++i) { if (::tolower(input[pos + i]) != mLiteral[i]) return string::npos; } return mLiteralSize; } void Literal::_serialize(BinaryOutputStream &fstr) { fstr << mLiteral; } Literal::Literal(BinaryGrammarBuilder &istr) : Recognizer(istr) { istr >> mLiteral; mLiteralSize = mLiteral.size(); } void Literal::_optimize(BCTBX_UNUSED(int recursionLevel)) { } bool Literal::_getTransitionMap(TransitionMap *mask) { mask->mPossibleChars[::tolower(mLiteral[0])] = true; mask->mPossibleChars[::toupper(mLiteral[0])] = true; return true; } shared_ptr Utils::literal(const string <) { return make_shared(lt); } shared_ptr Utils::char_range(int begin, int end) { return make_shared(begin, end); } shared_ptr RecognizerPointer::getPointed() { return mRecognizer; } size_t RecognizerPointer::_feed(ParserContextBase &ctx, const string &input, size_t pos) { if (mRecognizer) { return mRecognizer->feed(ctx, input, pos); } else { bctbx_fatal("RecognizerPointer with name '%s' is undefined", mName.c_str()); } return string::npos; } void RecognizerPointer::_serialize(BCTBX_UNUSED(BinaryOutputStream &fstr)) { bctbx_fatal("The RecognizerPointer is not supposed to be serialized."); } // RecognizerPointer::RecognizerPointer(BinaryGrammarBuilder& istr) : Recognizer(istr){ // //nothing to do // } void RecognizerPointer::setPointed(const shared_ptr &r) { mRecognizer = r; } void RecognizerPointer::_optimize(BCTBX_UNUSED(int recursionLevel)) { /*do not call optimize() on the pointed value to avoid a loop. * The grammar will do it for all rules anyway*/ } shared_ptr RecognizerAlias::getPointed() { return mRecognizer; } size_t RecognizerAlias::_feed(ParserContextBase &ctx, const string &input, size_t pos) { if (mRecognizer) { return mRecognizer->feed(ctx, input, pos); } else { bctbx_fatal("RecognizerAlias with name '%s' is undefined", mName.c_str()); } return string::npos; } void RecognizerAlias::_serialize(BinaryOutputStream &fstr) { mRecognizer->serialize(fstr); } RecognizerAlias::RecognizerAlias(BinaryGrammarBuilder &istr) : Recognizer(istr) { mRecognizer = Recognizer::build(istr); } void RecognizerAlias::setPointed(const shared_ptr &r) { mRecognizer = r; } void RecognizerAlias::_optimize(BCTBX_UNUSED(int recursionLevel)) { /*do not call optimize() on the pointed value to avoid a loop. * The grammar will do it for all rules anyway*/ } Grammar::Grammar(const string &name) : mName(name) { } Grammar::~Grammar() { for (auto it = mRecognizerPointers.begin(); it != mRecognizerPointers.end(); ++it) { shared_ptr pointer = dynamic_pointer_cast(*it); pointer->setPointed(nullptr); } } void Grammar::addRule(const string &argname, const shared_ptr &rule) { string name = tolower(argname); rule->setName(name); auto it = mRules.find(name); if (it != mRules.end()) { shared_ptr pointer = dynamic_pointer_cast((*it).second); if (pointer) { pointer->setPointed(rule); } else { bctbx_fatal("Rule '%s' is being redefined !", name.c_str()); } } /*in any case the map should contain real recognizers (not just pointers) */ mRules[name] = rule; } void Grammar::extendRule(const string &argname, const shared_ptr &rule) { string name = tolower(argname); rule->setName(""); auto it = mRules.find(name); if (it != mRules.end()) { shared_ptr sel = dynamic_pointer_cast((*it).second); if (sel) { sel->addRecognizer(rule); } else { bctbx_fatal("rule '%s' cannot be extended because it was not defined with a Selector.", name.c_str()); } } else { bctbx_fatal("rule '%s' cannot be extended because it is not defined.", name.c_str()); } } shared_ptr Grammar::findRule(const string &argname) { string name = tolower(argname); auto it = mRules.find(name); if (it != mRules.end()) { return (*it).second; } return nullptr; } shared_ptr Grammar::getRule(const string &argname) { shared_ptr ret = findRule(argname); if (ret) { shared_ptr pointer = dynamic_pointer_cast(ret); if (pointer) { if (pointer->getPointed()) { /*if pointer is defined return the pointed value directly*/ return pointer->getPointed(); } else { return pointer; } } return ret; } else { /*the rule doesn't exist yet: return a pointer*/ shared_ptr recognizerPointer = make_shared(); ret = recognizerPointer; string name = tolower(argname); ret->setName(string("@") + name); mRules[name] = ret; mRecognizerPointers.push_back(recognizerPointer); } return ret; } void Grammar::include(const shared_ptr &grammar) { for (auto it = grammar->mRules.begin(); it != grammar->mRules.end(); ++it) { if (mRules.find((*it).first) != mRules.end()) { BCTBX_SLOGE << "Rule '" << (*it).first << "' is being redefined while including grammar '" << grammar->mName << "' into '" << mName << "'"; } mRules[(*it).first] = (*it).second; } } bool Grammar::isComplete() const { bool ret = true; for (auto it = mRules.begin(); it != mRules.end(); ++it) { shared_ptr pointer = dynamic_pointer_cast((*it).second); if (pointer && !pointer->getPointed()) { BCTBX_SLOGE << "Rule '" << (*it).first << "' is not defined."; ret = false; } } return ret; } void Grammar::optimize() { for (auto it = mRules.begin(); it != mRules.end(); ++it) { (*it).second->optimize(); } } int Grammar::getNumRules() const { return (int)mRules.size(); } int Grammar::save(const std::string &filename) { BinaryOutputStream of; of.open(filename, ofstream::out | ofstream::trunc | ofstream::binary); if (of.fail()) { BCTBX_SLOGE << "Could not open " << filename; return -1; } // magic string of << "#!belr"; // grammar name: of << mName; // iterate over rules for (auto it = mRules.begin(); it != mRules.end(); ++it) { (*it).second->serialize(of, true); } of.close(); return 0; } int Grammar::load(const std::string &filename) { BinaryGrammarBuilder ifs(*this); int err = 0; ifs.open(filename, ifstream::in | ifstream::binary); if (ifs.fail()) { BCTBX_SLOGE << "Could not open " << filename; return -1; } /*extract the magic string*/ string magic; ifs >> magic; if (magic != "#!belr") { ifs.close(); BCTBX_SLOGE << filename << " is not a belr grammar binary file."; return -1; } /*extract the name of the grammar*/ ifs >> mName; // load rules while (true) { /*check if we are going to reach end of file at next read operation*/ ifs.get(); if (ifs.eof()) break; ifs.unget(); shared_ptr rule = Recognizer::build(ifs); if (!rule) { bctbx_error("Fail to parse recognizer."); err = -1; break; } if (rule->getName().empty()) { bctbx_error("Top level rule has no name"); err = -1; break; } BCTBX_SLOGD << "Added rule " << rule->getName(); addRule(rule->getName(), rule); } ifs.close(); if (!isComplete()) { bctbx_error("Grammar is not complete"); err = -1; } return err; } string tolower(const string &str) { string ret(str); transform(ret.begin(), ret.end(), ret.begin(), ::tolower); return ret; } } // namespace belr belr-5.3.105/src/binarystream.cpp000066400000000000000000000037511464614247000166220ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifdef _WIN32 #include #else #include #endif #include "belr/belr.h" #include "binarystream.h" using namespace std; namespace belr { /** * The BinaryInputStream is used internally to read grammars from a binary file. **/ int BinaryInputStream::readInt() { int tmp = 0; read((char *)&tmp, sizeof(tmp)); return ntohl(tmp); } unsigned char BinaryInputStream::readUChar() { unsigned char ret = 0; read((char *)&ret, 1); return ret; } std::string BinaryInputStream::readString() { string ret; unsigned char c; while (good()) { read((char *)&c, 1); if (c != '\0') ret.push_back(c); else break; } return ret; } BinaryGrammarBuilder::BinaryGrammarBuilder(Grammar &grammar) : mGrammar(grammar) { } std::shared_ptr BinaryGrammarBuilder::getRule(const string &name) { return mGrammar.getRule(name); } void BinaryOutputStream::writeInt(int val) { int tmp = htonl(val); write((char *)&tmp, sizeof(tmp)); } void BinaryOutputStream::writeUChar(unsigned char val) { write((char *)&val, 1); } void BinaryOutputStream::writeString(const string &val) { write((char *)val.c_str(), val.size() + 1); // because we want to write the null byte. } } // namespace belr belr-5.3.105/src/binarystream.h000066400000000000000000000053351464614247000162670ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef binarystream_h #define binarystream_h #include #include namespace belr { class Grammar; /** * The BinaryInputStream is used internally to read grammars from a binary file. **/ class BinaryInputStream : public std::ifstream { public: unsigned char readUChar(); int readInt(); std::string readString(); }; inline BinaryInputStream &operator>>(BinaryInputStream &istr, unsigned char &val) { val = istr.readUChar(); return istr; } inline BinaryInputStream &operator>>(BinaryInputStream &istr, int &val) { val = istr.readInt(); return istr; } inline BinaryInputStream &operator>>(BinaryInputStream &istr, unsigned int &val) { val = (unsigned int)istr.readInt(); return istr; } inline BinaryInputStream &operator>>(BinaryInputStream &istr, std::string &val) { val = istr.readString(); return istr; } /** * The BinaryOutputStream is used internally to serialize grammars into a binary file. **/ class BinaryOutputStream : public std::ofstream { public: void writeUChar(unsigned char val); void writeInt(int val); void writeString(const std::string &val); }; inline BinaryOutputStream &operator<<(BinaryOutputStream &ostr, unsigned char val) { ostr.writeUChar(val); return ostr; } inline BinaryOutputStream &operator<<(BinaryOutputStream &ostr, int val) { ostr.writeInt(val); return ostr; } inline BinaryOutputStream &operator<<(BinaryOutputStream &ostr, unsigned int val) { ostr.writeInt((int)val); return ostr; } inline BinaryOutputStream &operator<<(BinaryOutputStream &ostr, const std::string &val) { ostr.writeString(val); return ostr; } inline BinaryOutputStream &operator<<(BinaryOutputStream &ostr, const char *val) { ostr.writeString(val); return ostr; } class Recognizer; class BinaryGrammarBuilder : public BinaryInputStream { public: BinaryGrammarBuilder(Grammar &grammar); std::shared_ptr getRule(const std::string &name); private: Grammar &mGrammar; }; } // namespace belr #endif belr-5.3.105/src/common.h000066400000000000000000000015731464614247000150570ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef belr_common_h #define belr_common_h #include "bctoolbox/logging.h" #endif belr-5.3.105/src/grammarbuilder.cpp000066400000000000000000000363141464614247000171200ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include "belr/abnf.h" #include "belr/grammarbuilder.h" #include "belr/parser.h" #include "config.h" using namespace std; // ============================================================================= namespace belr { shared_ptr ABNFNumval::create() { return make_shared(); } shared_ptr ABNFNumval::buildRecognizer(BCTBX_UNUSED(const shared_ptr &grammar)) { if (mIsRange) { return Utils::char_range(mValues[0], mValues[1]); } else { auto seq = Foundation::sequence(); for (auto it = mValues.begin(); it != mValues.end(); ++it) { seq->addRecognizer(Foundation::charRecognizer(*it, true)); } return seq; } } void ABNFNumval::parseValues(const string &val, int base) { size_t dash = val.find('-'); if (dash != string::npos) { mIsRange = true; string first = val.substr(1, dash - 1); string last = val.substr(dash + 1, string::npos); mValues.push_back(strtol(first.c_str(), nullptr, base)); mValues.push_back(strtol(last.c_str(), nullptr, base)); } else { mIsRange = false; string tmp = val.substr(1, string::npos); const char *s = tmp.c_str(); char *endptr = nullptr; do { long lv = strtol(s, &endptr, base); if (lv == 0 && s == endptr) { break; } if (*endptr == '.') s = endptr + 1; else s = endptr; mValues.push_back(lv); } while (*s != '\0'); } } void ABNFNumval::setDecVal(const string &decval) { parseValues(decval, 10); } void ABNFNumval::setHexVal(const string &hexval) { parseValues(hexval, 16); } void ABNFNumval::setBinVal(const string &binval) { parseValues(binval, 2); } ostream &ABNFNumval::describe(ostream &ostr) const { ostr << "num-val with values ["; bool needSeparator = false; for (auto v : mValues) { if (needSeparator) ostr << ", "; ostr << v; needSeparator = true; } return ostr; } shared_ptr ABNFOption::buildRecognizer(const shared_ptr &grammar) { return Foundation::loop()->setRecognizer(mAlternation->buildRecognizer(grammar), 0, 1); } shared_ptr ABNFOption::create() { return make_shared(); } void ABNFOption::setAlternation(const shared_ptr &a) { mAlternation = a; } ostream &ABNFOption::describe(ostream &ostr) const { ostr << "option with alternation ["; mAlternation->describe(ostr); ostr << "]"; return ostr; } shared_ptr ABNFGroup::create() { return make_shared(); } shared_ptr ABNFGroup::buildRecognizer(const shared_ptr &grammar) { return mAlternation->buildRecognizer(grammar); } void ABNFGroup::setAlternation(const shared_ptr &a) { mAlternation = a; } ostream &ABNFGroup::describe(ostream &ostr) const { ostr << "group with alternation ["; mAlternation->describe(ostr); ostr << "]"; return ostr; } shared_ptr ABNFElement::buildRecognizer(const shared_ptr &grammar) { if (mElement) return mElement->buildRecognizer(grammar); if (!mRulename.empty()) return grammar->getRule(mRulename); if (!mCharVal.empty()) { if (mCharVal.size() == 1) return Foundation::charRecognizer(mCharVal[0], false); else return Utils::literal(mCharVal); } bctbx_fatal("ABNFElement is empty, should not happen!"); return nullptr; } shared_ptr ABNFElement::create() { return make_shared(); } bool ABNFElement::isDefined() const { if (!mElement || !mRulename.empty() || !mCharVal.empty()) { return true; } return false; } ostream &ABNFElement::describe(ostream &ostr) const { if (mElement) { ostringstream st; mElement->describe(st); ostr << "Element referencing [" << st.str() << "]"; } else if (!mRulename.empty()) ostr << "Element referencing rule name [" << mRulename << "]"; else if (!mCharVal.empty()) ostr << "Element containing char-val [" << mCharVal << "]"; else ostr << "Empty element !"; return ostr; } void ABNFElement::setElement(const shared_ptr &e) { mElement = e; } void ABNFElement::setRulename(const string &rulename) { mRulename = rulename; } void ABNFElement::setCharVal(const string &charval) { mCharVal = charval.substr(1, charval.size() - 2); // in order to remove surrounding quotes } void ABNFElement::setProseVal(const string &prose) { if (!prose.empty()) { bctbx_fatal("prose-val '%s' is not supported.", prose.c_str()); } } shared_ptr ABNFRepetition::create() { return make_shared(); } void ABNFRepetition::setCount(int count) { mCount = count; } void ABNFRepetition::setMin(int min) { mMin = min; } void ABNFRepetition::setMax(int max) { mMax = max; } void ABNFRepetition::setRepeat(const string &r) { mRepeat = r; } void ABNFRepetition::setElement(const shared_ptr &e) { mElement = e; } shared_ptr ABNFRepetition::buildRecognizer(const shared_ptr &grammar) { if (mRepeat.empty()) return mElement->buildRecognizer(grammar); if (mCount != -1) { return Foundation::loop()->setRecognizer(mElement->buildRecognizer(grammar), mCount, mCount); } else { return Foundation::loop()->setRecognizer(mElement->buildRecognizer(grammar), mMin, mMax); } } ostream &ABNFRepetition::describe(ostream &ostr) const { ostringstream st; mElement->describe(st); ostr << "repetition of [" << st.str() << "]"; return ostr; } shared_ptr ABNFConcatenation::create() { return make_shared(); } shared_ptr ABNFConcatenation::buildRecognizer(const shared_ptr &grammar) { if (mRepetitions.size() == 0) { bctbx_fatal("No repetitions set !"); } if (mRepetitions.size() == 1) { return mRepetitions.front()->buildRecognizer(grammar); } else { auto seq = Foundation::sequence(); for (auto it = mRepetitions.begin(); it != mRepetitions.end(); ++it) { seq->addRecognizer((*it)->buildRecognizer(grammar)); } return seq; } return nullptr; } void ABNFConcatenation::addRepetition(const shared_ptr &r) { mRepetitions.push_back(r); } ostream &ABNFConcatenation::describe(ostream &ostr) const { ostr << "concatenation of ["; bool needSeparator = false; for (auto r : mRepetitions) { if (needSeparator) ostr << " followed by "; r->describe(ostr); needSeparator = true; } ostr << "]"; return ostr; } shared_ptr ABNFAlternation::create() { return make_shared(); } void ABNFAlternation::addConcatenation(const shared_ptr &c) { mConcatenations.push_back(c); } shared_ptr ABNFAlternation::buildRecognizer(const shared_ptr &grammar) { if (mConcatenations.size() == 1) return mConcatenations.front()->buildRecognizer(grammar); return buildRecognizerNoOptim(grammar); } shared_ptr ABNFAlternation::buildRecognizerNoOptim(const shared_ptr &grammar) { auto sel = Foundation::selector(); for (auto it = mConcatenations.begin(); it != mConcatenations.end(); ++it) { sel->addRecognizer((*it)->buildRecognizer(grammar)); } return sel; } ostream &ABNFAlternation::describe(ostream &ostr) const { bool needSeparator = false; ostr << "alternation of ["; for (auto c : mConcatenations) { if (needSeparator) ostr << " or "; c->describe(ostr); needSeparator = true; } ostr << "]"; return ostr; } shared_ptr ABNFRule::create() { return make_shared(); } void ABNFRule::setName(const string &name) { if (!mName.empty()) bctbx_error("Rule %s is renamed !!!!!", name.c_str()); mName = name; } void ABNFRule::setAlternation(const shared_ptr &a) { mAlternation = a; } bool ABNFRule::isExtension() const { return mDefinedAs.find('/') != string::npos; } shared_ptr ABNFRule::buildRecognizer(const shared_ptr &grammar) { return mAlternation->buildRecognizer(grammar); } void ABNFRule::setDefinedAs(const string &defined_as) { mDefinedAs = defined_as; } ostream &ABNFRule::describe(ostream &ostr) const { ostr << "rule with name [" << mName << "] " << (isExtension() ? "extended with " : "defined as "); ostr << "["; mAlternation->describe(ostr); ostr << "]"; return ostr; } shared_ptr ABNFRuleList::create() { return make_shared(); } void ABNFRuleList::addRule(const shared_ptr &rule) { mRules.push_back(rule); } shared_ptr ABNFRuleList::buildRecognizer(const shared_ptr &grammar) { for (auto it = mRules.begin(); it != mRules.end(); ++it) { shared_ptr rule = (*it); if (rule->isExtension()) { grammar->extendRule(rule->getName(), rule->buildRecognizer(grammar)); } else { auto rec = rule->buildRecognizer(grammar); /* Special case: if the returned recognizer is a rule that was already added to the grammar, * we should not add it a second time, otherwise the name of the recognizer and the name in the grammar * entry will be different. To solve this problem, we use an intermediary AliasRecognizer*/ if (!rec->getName().empty()) { /*only rules (that is recognizers added to the grammar) have a name defined*/ if (rec->getName() != rule->getName()) { /* we are facing a statement like rule2 = rule1 */ auto alias = make_shared(); alias->setPointed(rec); rec = alias; } } grammar->addRule(rule->getName(), rec); } } return nullptr; } ostream &ABNFRuleList::describe(ostream &ostr) const { ostr << "rule-list contaning:" << endl; for (auto r : mRules) { r->describe(ostr); ostr << endl; } return ostr; } ABNFGrammarBuilder::ABNFGrammarBuilder() : mParser(make_shared()) { mParser.setHandler("rulelist", make_fn(&ABNFRuleList::create)) ->setCollector("rule", make_sfn(&ABNFRuleList::addRule)); mParser.setHandler("rule", make_fn(&ABNFRule::create)) ->setCollector("rulename", make_sfn(&ABNFRule::setName)) ->setCollector("defined-as", make_sfn(&ABNFRule::setDefinedAs)) ->setCollector("alternation", make_sfn(&ABNFRule::setAlternation)); mParser.setHandler("alternation", make_fn(&ABNFAlternation::create)) ->setCollector("concatenation", make_sfn(&ABNFAlternation::addConcatenation)); mParser.setHandler("concatenation", make_fn(&ABNFConcatenation::create)) ->setCollector("repetition", make_sfn(&ABNFConcatenation::addRepetition)); mParser.setHandler("repetition", make_fn(&ABNFRepetition::create)) ->setCollector("repeat", make_sfn(&ABNFRepetition::setRepeat)) ->setCollector("repeat-min", make_sfn(&ABNFRepetition::setMin)) ->setCollector("repeat-max", make_sfn(&ABNFRepetition::setMax)) ->setCollector("repeat-count", make_sfn(&ABNFRepetition::setCount)) ->setCollector("element", make_sfn(&ABNFRepetition::setElement)); mParser.setHandler("element", make_fn(&ABNFElement::create)) ->setCollector("rulename", make_sfn(&ABNFElement::setRulename)) ->setCollector("group", make_sfn(&ABNFElement::setElement)) ->setCollector("option", make_sfn(&ABNFElement::setElement)) ->setCollector("char-val", make_sfn(&ABNFElement::setCharVal)) ->setCollector("num-val", make_sfn(&ABNFElement::setElement)) ->setCollector("prose-val", make_sfn(&ABNFElement::setProseVal)); mParser.setHandler("group", make_fn(&ABNFGroup::create)) ->setCollector("alternation", make_sfn(&ABNFGroup::setAlternation)); mParser.setHandler("option", make_fn(&ABNFOption::create)) ->setCollector("alternation", make_sfn(&ABNFOption::setAlternation)); mParser.setHandler("num-val", make_fn(&ABNFNumval::create)) ->setCollector("bin-val", make_sfn(&ABNFNumval::setBinVal)) ->setCollector("hex-val", make_sfn(&ABNFNumval::setHexVal)) ->setCollector("dec-val", make_sfn(&ABNFNumval::setDecVal)); } shared_ptr ABNFGrammarBuilder::createFromAbnf(const string &abnf, const shared_ptr &gram) { size_t parsed; shared_ptr builder = mParser.parseInput("rulelist", abnf, &parsed); if (!builder) { bctbx_error("Failed to create builder."); return nullptr; } if (parsed < (size_t)abnf.size()) { bctbx_error("Only %llu bytes parsed over a total of %llu.", (unsigned long long)parsed, (unsigned long long)abnf.size()); return nullptr; } bctbx_message("Grammar parsed."); // ostringstream ostr; // builder->describe(ostr); // bctbx_message("Dump of grammar:\n %s", ostr.str().c_str()); shared_ptr retGram; if (gram == nullptr) retGram = make_shared(""); else retGram = gram; builder->buildRecognizer(retGram); bctbx_message("Succesfully created grammar with %i rules.", retGram->getNumRules()); if (retGram->isComplete()) { bctbx_message("Grammar is complete."); retGram->optimize(); bctbx_message("Grammar has been optimized."); } else { bctbx_warning("Grammar is not complete."); } return retGram; } shared_ptr ABNFGrammarBuilder::createFromAbnfFile(const string &path, const shared_ptr &gram) { ifstream istr(path); if (!istr.is_open()) { bctbx_error("Could not open %s", path.c_str()); return nullptr; } stringstream sstr; sstr << istr.rdbuf(); return createFromAbnf(sstr.str(), gram); } GrammarLoader *GrammarLoader::sInstance = nullptr; GrammarLoader::GrammarLoader() { mSystemPaths.push_back(BELR_GRAMMARS_DIR); mSystemPaths.push_back(BELR_GRAMMARS_RELATIVE_DIR); } GrammarLoader &GrammarLoader::get() { if (sInstance == nullptr) { sInstance = new GrammarLoader(); } return *sInstance; } void GrammarLoader::addPath(const string &path) { mAppPaths.push_front(path); } void GrammarLoader::clear() { mAppPaths.clear(); } string GrammarLoader::lookup(const string &fileName, const list &paths) { for (auto &it : paths) { ostringstream absFilename; absFilename << it << "/" << fileName; if (bctbx_file_exist(absFilename.str().c_str()) == 0) { return absFilename.str(); } } return ""; } bool GrammarLoader::isAbsolutePath(const string &fileName) { if (fileName[0] == '/') return TRUE; #ifdef _WIN32 /* for windows:*/ if (fileName.size() > 2 && fileName[1] == ':') return TRUE; #endif return FALSE; } shared_ptr GrammarLoader::load(const string &fileName) { string absFilename; if (isAbsolutePath(fileName)) { absFilename = fileName; } if (absFilename.empty()) { absFilename = lookup(fileName, mAppPaths); } if (absFilename.empty()) { absFilename = lookup(fileName, mSystemPaths); } if (absFilename.empty()) { bctbx_error("Could not load grammar %s because the file could not be located.", fileName.c_str()); return nullptr; } shared_ptr ret = make_shared(fileName); if (ret->load(absFilename) == 0) return ret; return nullptr; } } // namespace belr belr-5.3.105/src/parser.cpp000066400000000000000000000060151464614247000154120ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "belr/parser.h" #include "common.h" using namespace std; // ============================================================================= namespace belr { DebugElement::DebugElement(const string &rulename, const string &value) : mRulename(rulename), mValue(value) { } shared_ptr DebugElement::create(const string &rulename, const string &value) { return make_shared(rulename, value); } void DebugElement::addChild(const shared_ptr &e) { // cout<mRulename<<"["<> &retlist) const { for (std::list>::const_iterator it = mChildren.begin(); it != mChildren.end(); ++it) { if ((*it)->mRulename == rulename) { retlist.push_back(*it); } else { findChildren(rulename, retlist); } } } ostream &DebugElement::tostream(int level, ostream &str) const { int i; for (i = 0; i < level; i++) str << '\t'; if (!mChildren.empty()) { str << mRulename << endl; for (auto it = mChildren.begin(); it != mChildren.end(); ++it) { (*it)->tostream(level + 1, str); } } else { size_t pos; string value(mValue); while ((pos = value.find("\r")) != string::npos) { value.replace(pos, 1, "\\r"); }; while ((pos = value.find("\n")) != string::npos) { value.replace(pos, 1, "\\n"); }; str << mRulename << " : " << "'" << value << "'" << endl; } return str; } DebugParser::DebugParser(const shared_ptr &grammar) : Parser>(grammar) { } shared_ptr DebugParser::parseInput(const string &rulename, const string &input, size_t *parsed_size) { return Parser>::parseInput(rulename, input, parsed_size); } void DebugParser::setObservedRules(const list &rules) { for (auto it = rules.begin(); it != rules.end(); ++it) { auto h = setHandler(*it, make_fn(&DebugElement::create)); for (auto it2 = rules.begin(); it2 != rules.end(); ++it2) { h->setCollector(*it2, make_sfn(&DebugElement::addChild)); } } } } // namespace belr belr-5.3.105/tester/000077500000000000000000000000001464614247000141275ustar00rootroot00000000000000belr-5.3.105/tester/CMakeLists.txt000066400000000000000000000043111464614247000166660ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2015-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ set(BELR_LIBRARIES_FOR_TESTER belr) set(GRAMMAR_FILES res/basicgrammar.txt res/vcardgrammar.txt res/sipgrammar.txt res/response.txt res/register.txt ) set(BINARY_GRAMMAR_FILES res/belr-grammar-example.blr) set(HEADER_FILES_CXX belr-tester.h) set(SOURCE_FILES_CXX belr-tester.cpp grammar-tester.cpp parser.cpp ) bc_apply_compile_flags(SOURCE_FILES_CXX STRICT_OPTIONS_CPP STRICT_OPTIONS_CXX) add_executable(belr-tester ${SOURCE_FILES_CXX} ${HEADER_FILES_CXX}) set_target_properties(belr-tester PROPERTIES LINKER_LANGUAGE CXX) target_include_directories(belr-tester PUBLIC ${BCTOOLBOX_INCLUDE_DIRS}) target_link_libraries(belr-tester PRIVATE belr ${BCToolbox_tester_TARGET}) if(NOT IOS) install(TARGETS belr-tester RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE ) endif() install(FILES ${GRAMMAR_FILES} DESTINATION "${CMAKE_INSTALL_DATADIR}/belr-tester/res") install(FILES ${BINARY_GRAMMAR_FILES} DESTINATION "${CMAKE_INSTALL_DATADIR}/belr/grammars") belr-5.3.105/tester/belr-tester.cpp000066400000000000000000000063641464614247000170740ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "belr-tester.h" #include #include #include #include "config.h" using namespace ::std; namespace belr { std::string bcTesterFile(const std::string &name) { char *file = bc_tester_file(name.c_str()); std::string ret(file); bc_free(file); return ret; } std::string bcTesterRes(const std::string &name) { char *file = bc_tester_res(name.c_str()); std::string ret(file); bc_free(file); return ret; } std::string openFile(const std::string &name) { std::ifstream istr(name, std::ios::binary); if (!istr.is_open()) { bctbx_error("Fail to open %s", name.c_str()); BC_FAIL("Fail to open file"); return ""; } std::stringstream tmpStream; tmpStream << istr.rdbuf(); return tmpStream.str(); ; } } // namespace belr int main(int argc, char *argv[]) { int i; int ret; belr_tester_init(NULL); char *dirname = bctbx_dirname(argv[0]); std::string resDir = string(dirname) + "/../share/belr-tester/res/"; std::string testResource = resDir + "sipgrammar.txt"; bctbx_free(dirname); if (bctbx_file_exist(testResource.c_str()) == 0) { bc_tester_set_resource_dir_prefix(resDir.c_str()); printf("Resource dir set to %s\n", resDir.c_str()); } else { bc_tester_set_resource_dir_prefix(BELR_LOCAL_RESOURCE_LOCATION); printf("Resource dir set to %s\n", BELR_LOCAL_RESOURCE_LOCATION); } bc_tester_set_writable_dir_prefix("./"); for (i = 1; i < argc; ++i) { ret = bc_tester_parse_args(argc, argv, i); if (ret > 0) { i += ret - 1; continue; } else if (ret < 0) { bc_tester_helper(argv[0], ""); } return ret; } ret = bc_tester_start(argv[0]); belr_tester_uninit(); return ret; } static void log_handler(int lev, const char *fmt, va_list args) { #ifdef _WIN32 vfprintf(lev == BCTBX_LOG_ERROR ? stderr : stdout, fmt, args); fprintf(lev == BCTBX_LOG_ERROR ? stderr : stdout, "\n"); #else va_list cap; va_copy(cap, args); /* Otherwise, we must use stdio to avoid log formatting (for autocompletion etc.) */ vfprintf(lev == BCTBX_LOG_ERROR ? stderr : stdout, fmt, cap); fprintf(lev == BCTBX_LOG_ERROR ? stderr : stdout, "\n"); va_end(cap); #endif } void belr_tester_init(void (*ftester_printf)(int level, const char *fmt, va_list args)) { if (ftester_printf == NULL) ftester_printf = log_handler; bc_tester_init(ftester_printf, BCTBX_LOG_MESSAGE, BCTBX_LOG_ERROR, "."); bc_tester_add_suite(&grammar_suite); bc_tester_add_suite(&parser_suite); } void belr_tester_uninit(void) { bc_tester_uninit(); } belr-5.3.105/tester/belr-tester.h000066400000000000000000000030171464614247000165310ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef belr_tester_hpp #define belr_tester_hpp #include "belr/abnf.h" #include "belr/belr.h" #include "belr/grammarbuilder.h" #include #include #include #include #include #include #include #include namespace belr { std::string bcTesterFile(const std::string &name); std::string bcTesterRes(const std::string &name); std::string openFile(const std::string &name); } // namespace belr #ifdef __cplusplus extern "C" { #endif extern test_suite_t grammar_suite; extern test_suite_t parser_suite; void belr_tester_init(void (*ftester_printf)(int level, const char *fmt, va_list args)); void belr_tester_uninit(void); #ifdef __cplusplus }; #endif #endif belr-5.3.105/tester/grammar-tester.cpp000066400000000000000000000112621464614247000175670ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "bctoolbox/logging.h" #include "belr-tester.h" #include using namespace ::std; using namespace ::belr; static bool parseMessage(shared_ptr grammar, const string &message) { shared_ptr parser = make_shared(grammar); parser->setObservedRules({"sip-message"}); size_t pos = 0; shared_ptr elem = parser->parseInput("sip-message", message, &pos); BC_ASSERT_TRUE(elem != nullptr); if (!elem) return FALSE; BC_ASSERT_EQUAL((int)pos, (int)message.size(), int, "%i"); BC_ASSERT_TRUE(message == elem->getValue()); return message.size() == pos && message == elem->getValue(); } static void sipgrammar_save_and_load(void) { string grammarToParse = bcTesterRes("sipgrammar.txt"); string grammarDump = bcTesterFile("grammarDump.bin"); string sipmessage = openFile(bcTesterRes("register.txt")); remove(grammarDump.c_str()); BC_ASSERT_TRUE(sipmessage.size() > 0); ABNFGrammarBuilder builder; // Read grammar put it in object grammar auto start = std::chrono::high_resolution_clock::now(); shared_ptr grammar = builder.createFromAbnfFile(grammarToParse, make_shared()); auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration elapsedFirst = finish - start; BC_ASSERT_FALSE(!grammar); if (!grammar) return; // make sure we're able to parse a SIP message with the created grammar BC_ASSERT_TRUE(parseMessage(grammar, sipmessage)); // Save grammar grammar->save(grammarDump); // Load grammar start = std::chrono::high_resolution_clock::now(); shared_ptr loadedGram = make_shared("loaded"); BC_ASSERT_TRUE(loadedGram->load(grammarDump) == 0); finish = std::chrono::high_resolution_clock::now(); std::chrono::duration elapsedSecond = finish - start; // Make sure the loaded from binary file grammar is still able to parse the sip message: BC_ASSERT_TRUE(parseMessage(loadedGram, sipmessage)); BC_ASSERT_TRUE(elapsedFirst.count() > 2 * elapsedSecond.count()); } /** * In SIP grammar, we have: * header-name = token * This kind of rules were causing issues in previous version of belr because "header-name" rule could not be attached * with a parser handler, as the recognizer behind it was named "token". */ static void aliases_rules(void) { string grammarToParse = bcTesterRes("sipgrammar.txt"); string sipmessage = openFile(bcTesterRes("response.txt")); BC_ASSERT_TRUE(sipmessage.size() > 0); ABNFGrammarBuilder builder; // Read grammar put it in object grammar shared_ptr grammar = builder.createFromAbnfFile(grammarToParse, make_shared()); BC_ASSERT_FALSE(!grammar); if (!grammar) return; shared_ptr parser = make_shared(grammar); parser->setObservedRules({"sip-message", "header-name"}); size_t pos = 0; shared_ptr elem = parser->parseInput("sip-message", sipmessage, &pos); BC_ASSERT_TRUE(elem != nullptr); if (!elem) return; BC_ASSERT_EQUAL((int)pos, (int)sipmessage.size(), int, "%i"); BC_ASSERT_TRUE(sipmessage == elem->getValue()); list> headerNames; elem->findChildren("header-name", headerNames); BC_ASSERT_TRUE(headerNames.size() == 1); if (!headerNames.empty()) { BC_ASSERT_TRUE(headerNames.front()->getValue() == "Custom-header"); } } static void test_grammar_loader(void) { GrammarLoader &loader = GrammarLoader::get(); loader.addPath(std::string(bc_tester_get_resource_dir_prefix())); shared_ptr grammar = loader.load("belr-grammar-example.blr"); BC_ASSERT_PTR_NOT_NULL(grammar); } static test_t tests[] = {TEST_NO_TAG("SIP grammar save and load", sipgrammar_save_and_load), TEST_NO_TAG("SIP grammar with aliases rules", aliases_rules), TEST_NO_TAG("Grammar loader", test_grammar_loader)}; test_suite_t grammar_suite = {"Grammar", NULL, NULL, NULL, NULL, sizeof(tests) / sizeof(tests[0]), tests, 0, 0}; belr-5.3.105/tester/parser.cpp000066400000000000000000000205221464614247000161300ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "belr-tester.h" #include using namespace ::std; using namespace ::belr; typedef struct sip_uri { char *user; char *host; int port; } sip_uri_t; typedef struct sip_response { sip_uri_t *from; sip_uri_t *to; } sip_response_t; sip_uri_t *sip_uri_create(void) { return bctbx_new0(sip_uri_t, 1); } void sip_uri_set_user(sip_uri_t *uri, const char *user) { uri->user = bctbx_strdup(user); } void sip_uri_set_host(sip_uri_t *uri, const char *host) { uri->host = bctbx_strdup(host); } void sip_uri_set_port(sip_uri_t *uri, int port) { uri->port = port; } void sip_uri_destroy(sip_uri_t *uri) { if (uri->host) bctbx_free(uri->host); if (uri->user) bctbx_free(uri->user); bctbx_free(uri); } sip_response_t *sip_response_create(void) { return bctbx_new0(sip_response_t, 1); } void sip_response_set_from(sip_response_t *resp, sip_uri_t *uri) { resp->from = uri; } void sip_response_set_to(sip_response_t *resp, sip_uri_t *uri) { resp->to = uri; } void sip_response_destroy(sip_response_t *resp) { if (resp->from) sip_uri_destroy(resp->from); if (resp->to) sip_uri_destroy(resp->to); bctbx_free(resp); } static void parser_connected_to_c_functions(void) { string grammarToParse = bcTesterRes("sipgrammar.txt"); string sipmessage = openFile(bcTesterRes("response.txt")); BC_ASSERT_TRUE(sipmessage.size() > 0); ABNFGrammarBuilder builder; // Read grammar put it in object grammar shared_ptr grammar = builder.createFromAbnfFile(grammarToParse, make_shared()); BC_ASSERT_FALSE(!grammar); if (!grammar) return; shared_ptr> parser = make_shared>(grammar); parser->setHandler("response", make_fn(&sip_response_create)) ->setCollector("from", make_fn(&sip_response_set_from)) ->setCollector("to", make_fn(&sip_response_set_to)); parser->setHandler("from", make_fn(&sip_uri_create)) ->setCollector("user", make_fn(&sip_uri_set_user)) ->setCollector("host", make_fn(&sip_uri_set_host)); parser->setHandler("to", make_fn(&sip_uri_create)) ->setCollector("user", make_fn(&sip_uri_set_user)) ->setCollector("host", make_fn(&sip_uri_set_host)) ->setCollector("port", make_fn(&sip_uri_set_port)); size_t pos = 0; void *elem = parser->parseInput("response", sipmessage, &pos); BC_ASSERT_PTR_NOT_NULL(elem); if (!elem) return; BC_ASSERT_EQUAL((int)pos, (int)sipmessage.size(), int, "%i"); sip_response_t *resp = (sip_response_t *)elem; sip_uri_t *from = resp->from; sip_uri_t *to = resp->to; BC_ASSERT_PTR_NOT_NULL(from); BC_ASSERT_PTR_NOT_NULL(to); if (from && to) { BC_ASSERT_STRING_EQUAL(from->user, "smorlat2"); BC_ASSERT_STRING_EQUAL(to->user, "smorlat2"); BC_ASSERT_STRING_EQUAL(from->host, "siptest.linphone.org"); BC_ASSERT_STRING_EQUAL(to->host, "siptest.linphone.org"); BC_ASSERT_EQUAL(to->port, 5060, int, "%i"); } sip_response_destroy(resp); } // // Parser with inheritance. // /* Base class for all parser elements*/ class Object { public: virtual ~Object() = default; }; /* Base class for SIP headers */ class SipHeader : public Object { public: SipHeader(const string &headerName) : mHeaderName(headerName) { } const string &getName() const { return mHeaderName; } protected: void setHeaderName(const string &headerName) { mHeaderName = headerName; } private: string mHeaderName; }; /* * The SipHeaderHolder is a kind of container for all possible types of SIP headers. * This special type is needed so that it is possible to parse headers in an unitary way (not in a full message). * It does not have to be part of the parser API. Keep it internal as an utility. */ class SipHeaderHolder : public Object { public: SipHeaderHolder(){}; void setHeader(const shared_ptr &header) { mHeader = header; } shared_ptr getHeader() const { return mHeader; } private: shared_ptr mHeader; }; /* * SIP From */ class SipFrom : public SipHeader { public: SipFrom() : SipHeader("From"){}; void setUri(const string &uri) { mUri = uri; } const string &getUri() const { return mUri; } private: string mUri; }; /* * Extension header */ class ExtensionHeader : public SipHeader { public: ExtensionHeader() : SipHeader("generic"){}; void setName(const string &headerName) { SipHeader::setHeaderName(headerName); } void setValue(const string &headerValue) { mHeaderValue = headerValue; } const string &getValue() const { return mHeaderValue; } private: string mHeaderValue; }; /* * SIP request. Contains headers. */ class SipRequest : public Object { public: SipRequest(){}; void addHeader(const shared_ptr &header) { mHeaders.push_back(header); } shared_ptr getHeader(const string &name) { for (auto h : mHeaders) { if (strcasecmp(h->getName().c_str(), name.c_str()) == 0) return h; } return nullptr; } /* Hide this from the API documentation */ void addHeaderHolder(const shared_ptr &holder) { if (holder->getHeader()) addHeader(holder->getHeader()); } private: list> mHeaders; }; static void parser_with_inheritance(void) { string grammarToParse = bcTesterRes("sipgrammar.txt"); string sipmessage = openFile(bcTesterRes("register.txt")); size_t pos = 0; BC_ASSERT_TRUE(sipmessage.size() > 0); ABNFGrammarBuilder builder; // Read grammar put it in object grammar shared_ptr grammar = builder.createFromAbnfFile(grammarToParse, make_shared()); BC_ASSERT_FALSE(!grammar); if (!grammar) return; shared_ptr>> parser = make_shared>>(grammar); /* The request collects headers in a generic way, thanks to the SipHeaderHolder. */ parser->setHandler("request", make_fn()) ->setCollector("message-header", make_sfn(&SipRequest::addHeaderHolder)); parser->setHandler("from", make_fn())->setCollector("sip-uri", make_sfn(&SipFrom::setUri)); parser->setHandler("extension-header", make_fn()) ->setCollector("header-name", make_sfn(&ExtensionHeader::setName)) ->setCollector("header-value", make_sfn(&ExtensionHeader::setValue)); /* The message-header rule (representing all sub-rules of SIP headers) is handled by the SipHeaderHolder. * It requires explicit collectors for all sub-rules. */ parser->setHandler("message-header", make_fn()) ->setCollector("from", make_sfn(&SipHeaderHolder::setHeader)) ->setCollector("extension-header", make_sfn(&SipHeaderHolder::setHeader)); // Parse the full message shared_ptr elem = parser->parseInput("request", sipmessage, &pos); BC_ASSERT_TRUE(elem != nullptr); if (!elem) return; BC_ASSERT_EQUAL(pos, sipmessage.size(), size_t, "%zu"); shared_ptr request = dynamic_pointer_cast(elem); BC_ASSERT_TRUE(request != nullptr); if (!request) return; BC_ASSERT_TRUE(request->getHeader("from") != nullptr); BC_ASSERT_TRUE(request->getHeader("CustomHeader") != nullptr); // Parse a single sip header elem = parser->parseInput("message-header", "From: \r\n", &pos); BC_ASSERT_TRUE(elem != nullptr); if (!elem) return; auto holder = dynamic_pointer_cast(elem); BC_ASSERT_TRUE(holder != nullptr); if (!holder) return; BC_ASSERT_TRUE(dynamic_pointer_cast(holder->getHeader()) != nullptr); } static test_t tests[] = {TEST_NO_TAG("Parser connected to C functions", parser_connected_to_c_functions), TEST_NO_TAG("Parser with inheritance", parser_with_inheritance)}; test_suite_t parser_suite = {"Parser", NULL, NULL, NULL, NULL, sizeof(tests) / sizeof(tests[0]), tests, 0, 0}; belr-5.3.105/tester/res/000077500000000000000000000000001464614247000147205ustar00rootroot00000000000000belr-5.3.105/tester/res/basicgrammar.txt000066400000000000000000000012571464614247000201160ustar00rootroot00000000000000mark = ALPHA alphanum = DIGIT escaped = "%" HEXDIG HEXDIG separators = "(" / "(" / "<" / ">" / "@" / "," / ";" / ":" unknown = 1*(mark) multipke = mark alphanum alphamine = escaped [unknown] scheme = *("+") kalimoon = *( "(" "^" "$" "``") INVITEm = %x49.4E.56.49.54.45 ; INVITE in caps ACKm = %x41.43.4B ; ACK in caps OPTIONSm = %x4F.50.54.49.4F.4E.53 ; OPTIONS in caps BYEm = %x42.59.45 ; BYE in caps CANCELm = %x43.41.4E.43.45.4C ; CANCEL in caps REGISTERm = %x52.45.47.49.53.54.45.52 ; REGISTER in caps Method = INVITEm / ACKm / OPTIONSm / BYEm / CANCELm / REGISTERm belr-5.3.105/tester/res/belr-grammar-example.blr000066400000000000000000000066321464614247000214310ustar00rootroot00000000000000#!belrcore rulesalphaazAZany-param iana-token x-name= param-value, param-valuebit01booleantruefalsecharcontentline group. name; param: value crlfcr crlf cr lfctldate year month day year- month-- month day--- daydate-and-or-time date-time date time-designator timedate-and-or-time-list date-and-or-time, date-and-or-timedate-complete year month daydate-list date, datedate-noreduc year month day-- month day--- daydate-time date-noreduc time-designator time-notruncdate-time-list date-time, date-timeday digitdigit09dquote"float sign digit. digitfloat-list float, floatgroup alpha digit-hexdig digitabcdefhour digithtab iana-token alpha digit-integer sign digitinteger-list integer, integerlf lwsp wsp crlf wspminute digitmonth digitname%sourcekindfnnnicknamephotobdayanniversarygenderadrtelemailimpplangtzgeotitlerolelogoorgmemberrelatedcategoriesnoteprodidrevsounduidclientpidmapurlkeyfburlcaladruricalurixml iana-token x-namenon-ascii utf8-2 utf8-3 utf8-4octet param any-paramparam-value safe-char dquote qsafe-char dquoteqsafe-char wsp!#~ non-asciisafe-char wsp!#9<~ non-asciisecond digitsign+-sp text text-chartext-char\\\,\n wsp non-ascii!+-[]~text-list text, texttime hour minute second zone- minute second zone-- second zonetime-complete hour minute second zonetime-designatorTtime-list time, timetime-notrunc hour minute second zonetimestamp date-complete time-designator time-completetimestamp-list timestamp, timestamputc-designatorZutc-offset sign hour minuteutf8-1utf8-2 utf8-tailutf8-3 utf8-tail utf8-tail utf8-tail utf8-tailutf8-4 utf8-tail utf8-tail utf8-tailutf8-tailvalue text text-list date-list time-list date-time-list date-and-or-time-list timestamp-list boolean integer-list float-list utc-offsetvalue-char wsp vchar non-asciivcardbegin:vcard crlfversion:4.0 crlf contentlineend:vcard crlfvcard-entity vcardvchar!~wsp sp htabx-namex- alpha digit-year digitzone utc-designator utc-offsetbelr-5.3.105/tester/res/register.txt000066400000000000000000000014541464614247000173110ustar00rootroot00000000000000REGISTER sip:siptest.linphone.org SIP/2.0 Via: SIP/2.0/TLS 192.168.0.25:41076;alias;branch=z9hG4bK.m-SPAXXd3;rport From: "François" ;tag=HW3X1aviU To: marie CSeq: 21 REGISTER Call-ID: s69J2OQ4h4 Max-Forwards: 70 Supported: outbound Contact: ;+sip.instance="" Expires: 3600 User-Agent: Linphone/3.7.0 (belle-sip/1.3.3) CustomHeader: some-custom-value Content-Length: 0 Authorization: Digest realm="siptest.linphone.org", nonce="f5Zb2AAAAABXkU1AAAD253sZEAsAAAAA", algorithm=MD5, opaque="+GNywA==", username="smorlat2", uri="sip:siptest.linphone.org", response="f86327204e4c826f47d761c9ad3afdb3", cnonce="faaa9595", nc=00000001, qop=auth belr-5.3.105/tester/res/response.txt000066400000000000000000000005721464614247000173230ustar00rootroot00000000000000SIP/2.0 403 Forbidden Via: SIP/2.0/TLS 192.168.0.25:41076;alias;branch=z9hG4bK.m-SPAXXd3;rport=41076;received=78.220.48.77 From: ;tag=HW3X1aviU To: ;tag=yDXec8ej8Hrea Call-ID: s69J2OQ4h4 CSeq: 21 REGISTER Server: Flexisip/0.8.0 (sofia-sip-nta/2.0) Custom-header: some-value Content-Length: 0 belr-5.3.105/tester/res/sipgrammar.txt000066400000000000000000000513321464614247000176270ustar00rootroot00000000000000alphanum = ALPHA / DIGIT reserved = ";" / "/" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / "," unreserved = alphanum / mark mark = "-" / "_" / "." / "!" / "~" / "*" / "'" / "(" / ")" escaped = "%" HEXDIG HEXDIG LWS = [*WSP CRLF] 1*WSP ; linear whitespace SWS = [LWS] ; sep whitespace HCOLON = *( SP / HTAB ) ":" SWS TEXT-UTF8-TRIM = 1*TEXT-UTF8char *(*LWS TEXT-UTF8char) TEXT-UTF8char = %x21-7E / UTF8-NONASCII UTF8-NONASCII = %xC0-DF 1UTF8-CONT / %xE0-EF 2UTF8-CONT / %xF0-F7 3UTF8-CONT / %xF8-Fb 4UTF8-CONT / %xFC-FD 5UTF8-CONT UTF8-CONT = %x80-BF LHEX = DIGIT / %x61-66 ;lowercase a-f token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" ) separators = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "\" / DQUOTE / "/" / "[" / "]" / "?" / "=" / "{" / "}" / SP / HTAB word = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" / "(" / ")" / "<" / ">" / ":" / "\" / DQUOTE / "/" / "[" / "]" / "?" / "{" / "}" ) STAR = SWS "*" SWS ; asterisk SLASH = SWS "/" SWS ; slash EQUAL = SWS "=" SWS ; equal LPAREN = SWS "(" SWS ; left parenthesis RPAREN = SWS ")" SWS ; right parenthesis RAQUOT = ">" SWS ; right angle quote LAQUOT = SWS "<"; left angle quote COMMA = SWS "," SWS ; comma SEMI = SWS ";" SWS ; semicolon COLON = SWS ":" SWS ; colon LDQUOT = SWS DQUOTE; open double quotation mark RDQUOT = DQUOTE SWS ; close double quotation mark comment = LPAREN *(ctext / quoted-pair / comment) RPAREN ctext = %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII / LWS quoted-string = SWS DQUOTE *(qdtext / quoted-pair ) DQUOTE qdtext = LWS / %x21 / %x23-5B / %x5D-7E / UTF8-NONASCII quoted-pair = "\" (%x00-09 / %x0B-0C / %x0E-7F) SIP-URI = "sip:" [ userinfo ] hostport uri-parameters [ headers ] SIPS-URI = "sips:" [ userinfo ] hostport uri-parameters [ headers ] ;userinfo = ( user / telephone-subscriber ) [ ":" password ] "@" ;what is the interest of telephone-subscriber ? userinfo = user [ ":" password ] "@" user = 1*( unreserved / escaped / user-unreserved ) user-unreserved = "&" / "=" / "+" / "$" / "," / ";" / "?" / "/" password = *( unreserved / escaped / "&" / "=" / "+" / "$" / "," ) hostport = host [ ":" port ] host = hostname / IPv4address / IPv6reference hostname = *( domainlabel "." ) toplabel [ "." ] ;domainlabel is modified to avoid an ambiguity domainlabel = alphanum / (alphanum *( alphanum / ( *("-") alphanum) ) ) ;toplabel is modified to avoid an ambiguity toplabel = ALPHA / (ALPHA *( alphanum / (*("-") alphanum ) ) ) IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT IPv6reference = "[" IPv6address "]" IPv6address = hexpart [ ":" IPv4address ] hexpart = hexseq / hexseq "::" [ hexseq ] / "::" [ hexseq ] hexseq = hex4 *( ":" hex4) hex4 = 1*4HEXDIG port = 1*DIGIT uri-parameters = *( ";" uri-parameter) uri-parameter = transport-param / user-param / method-param / ttl-param / maddr-param / lr-param / other-param transport-param = "transport=" ( "udp" / "tcp" / "sctp" / "tls" / other-transport) other-transport = token user-param = "user=" ( "phone" / "ip" / other-user) other-user = token method-param = "method=" Method ttl-param = "ttl=" ttl maddr-param = "maddr=" host lr-param = "lr" other-param = pname [ "=" pvalue ] pname = 1*paramchar pvalue = 1*paramchar paramchar = param-unreserved / unreserved / escaped param-unreserved = "[" / "]" / "/" / ":" / "&" / "+" / "$" headers = "?" header *( "&" header ) header = hname "=" hvalue hname = 1*( hnv-unreserved / unreserved / escaped ) hvalue = *( hnv-unreserved / unreserved / escaped ) hnv-unreserved = "[" / "]" / "/" / "?" / ":" / "+" / "$" SIP-message = Request / Response Request = Request-Line *( message-header ) CRLF [ message-body ] Request-Line = Method SP Request-URI SP SIP-Version CRLF Request-URI = SIP-URI / SIPS-URI / absoluteURI absoluteURI = scheme ":" ( hier-part / opaque-part ) hier-part = ( net-path / abs-path ) [ "?" query ] net-path = "//" authority [ abs-path ] abs-path = "/" path-segments opaque-part = uric-no-slash *uric uric = reserved / unreserved / escaped uric-no-slash = unreserved / escaped / ";" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / "," path-segments = segment *( "/" segment ) segment = *pchar *( ";" param ) param = *pchar pchar = unreserved / escaped / ":" / "@" / "&" / "=" / "+" / "$" / "," scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) authority = srvr / reg-name srvr = [ [ userinfo "@" ] hostport ] reg-name = 1*( unreserved / escaped / "$" / "," / ";" / ":" / "@" / "&" / "=" / "+" ) query = *uric SIP-Version = "SIP" "/" 1*DIGIT "." 1*DIGIT message-header = (Accept / Accept-Encoding / Accept-Language / Alert-Info / Allow / Authentication-Info / Authorization / Call-ID / Call-Info / Contact / Content-Disposition / Content-Encoding / Content-Language / Content-Length / Content-Type / CSeq / Date / Error-Info / Expires / From / In-Reply-To / Max-Forwards / MIME-Version / Min-Expires / Organization / Priority / Proxy-Authenticate / Proxy-Authorization / Proxy-Require / Record-Route / Reply-To / Require / Retry-After / Route / Server / Subject / Supported / Timestamp / To / Unsupported / User-Agent / Via / Warning / WWW-Authenticate / extension-header) CRLF INVITEm = %x49.4E.56.49.54.45 ; INVITE in caps ACKm = %x41.43.4B ; ACK in caps OPTIONSm = %x4F.50.54.49.4F.4E.53 ; OPTIONS in caps BYEm = %x42.59.45 ; BYE in caps CANCELm = %x43.41.4E.43.45.4C ; CANCEL in caps REGISTERm = %x52.45.47.49.53.54.45.52 ; REGISTER in caps Method = INVITEm / ACKm / OPTIONSm / BYEm / CANCELm / REGISTERm / extension-method extension-method = token Response = Status-Line *( message-header ) CRLF [ message-body ] Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF Status-Code = Informational / Redirection / Success / Client-Error / Server-Error / Global-Failure / extension-code extension-code = 3DIGIT Reason-Phrase = *(reserved / unreserved / escaped / UTF8-NONASCII / UTF8-CONT / SP / HTAB) Informational = "100" ; Trying / "180" ; Ringing / "181" ; Call Is Being Forwarded / "182" ; Queued / "183" ; Session Progress Success = "200" ; OK Redirection = "300" ; Multiple Choices / "301" ; Moved Permanently / "302" ; Moved Temporarily / "305" ; Use Proxy / "380" ; Alternative Service Client-Error = "400" ; Bad Request / "401" ; Unauthorized / "402" ; Payment Required / "403" ; Forbidden / "404" ; Not Found / "405" ; Method Not Allowed / "406" ; Not Acceptable / "407" ; Proxy Authentication Required / "408" ; Request Timeout / "410" ; Gone / "413" ; Request Entity Too Large / "414" ; Request-URI Too Large / "415" ; Unsupported Media Type / "416" ; Unsupported URI Scheme / "420" ; Bad Extension / "421" ; Extension Required / "423" ; Interval Too Brief / "480" ; Temporarily not available / "481" ; Call Leg/Transaction Does Not Exist / "482" ; Loop Detected / "483" ; Too Many Hops / "484" ; Address Incomplete / "485" ; Ambiguous / "486" ; Busy Here / "487" ; Request Terminated / "488" ; Not Acceptable Here / "491" ; Request Pending / "493" ; Undecipherable Server-Error = "500" ; Internal Server Error / "501" ; Not Implemented / "502" ; Bad Gateway / "503" ; Service Unavailable / "504" ; Server Time-out / "505" ; SIP Version not supported / "513" ; Message Too Large Global-Failure = "600" ; Busy Everywhere / "603" ; Decline / "604" ; Does not exist anywhere / "606" ; Not Acceptable Accept = "Accept" HCOLON [ accept-range *(COMMA accept-range) ] accept-range = media-range *(SEMI accept-param) media-range = ( "*/*" / ( m-type SLASH "*" ) / ( m-type SLASH m-subtype ) ) *( SEMI m-parameter ) accept-param = ("q" EQUAL qvalue) / generic-param qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) generic-param = token [ EQUAL gen-value ] gen-value = token / host / quoted-string Accept-Encoding = "Accept-Encoding" HCOLON [ encoding *(COMMA encoding) ] encoding = codings *(SEMI accept-param) codings = content-coding / "*" content-coding = token Accept-Language = "Accept-Language" HCOLON [ language *(COMMA language) ] language = language-range *(SEMI accept-param) language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) / "*" ) Alert-Info = "Alert-Info" HCOLON alert-param *(COMMA alert-param) alert-param = LAQUOT absoluteURI RAQUOT *( SEMI generic-param ) Allow = "Allow" HCOLON [Method *(COMMA Method)] Authorization = "Authorization" HCOLON credentials credentials = ("Digest" LWS digest-response) / other-response digest-response = dig-resp *(COMMA dig-resp) dig-resp = username / realm / nonce / digest-uri / dresponse / algorithm / cnonce / opaque / message-qop / nonce-count / auth-param username = "username" EQUAL username-value username-value = quoted-string digest-uri = "uri" EQUAL LDQUOT digest-uri-value RDQUOT digest-uri-value = request-uri ; Equal to request-uri as specified ; by HTTP/1.1 message-qop = "qop" EQUAL qop-value cnonce = "cnonce" EQUAL cnonce-value cnonce-value = nonce-value nonce-count = "nc" EQUAL nc-value nc-value = 8LHEX dresponse = "response" EQUAL request-digest request-digest = LDQUOT 32LHEX RDQUOT auth-param = auth-param-name EQUAL ( token / quoted-string ) auth-param-name = token other-response = auth-scheme LWS auth-param *(COMMA auth-param) auth-scheme = token Authentication-Info = "Authentication-Info" HCOLON ainfo *(COMMA ainfo) ainfo = nextnonce / message-qop / response-auth / cnonce / nonce-count nextnonce = "nextnonce" EQUAL nonce-value response-auth = "rspauth" EQUAL response-digest response-digest = LDQUOT *LHEX RDQUOT Call-ID = ( "Call-ID" / "i" ) HCOLON callid callid = word [ "@" word ] Call-Info = "Call-Info" HCOLON info *(COMMA info) info = LAQUOT absoluteURI RAQUOT *( SEMI info-param) info-param = ( "purpose" EQUAL ( "icon" / "info" / "card" / token ) ) / generic-param Contact = ("Contact" / "m" ) HCOLON ( STAR / (contact-param *(COMMA contact-param))) contact-param = (name-addr / addr-spec) *(SEMI contact-params) name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI display-name = *(token LWS)/ quoted-string contact-params = c-p-q / c-p-expires / contact-extension c-p-q = "q" EQUAL qvalue c-p-expires = "expires" EQUAL delta-seconds contact-extension = generic-param delta-seconds = 1*DIGIT Content-Disposition = "Content-Disposition" HCOLON disp-type *( SEMI disp-param ) disp-type = "render" / "session" / "icon" / "alert" / disp-extension-token disp-param = handling-param / generic-param handling-param = "handling" EQUAL ( "optional" / "required" / other-handling ) other-handling = token disp-extension-token = token Content-Encoding = ( "Content-Encoding" / "e" ) HCOLON content-coding *(COMMA content-coding) Content-Language = "Content-Language" HCOLON language-tag *(COMMA language-tag) language-tag = primary-tag *( "-" subtag ) primary-tag = 1*8ALPHA subtag = 1*8ALPHA Content-Length = ( "Content-Length" / "l" ) HCOLON 1*DIGIT Content-Type = ( "Content-Type" / "c" ) HCOLON media-type media-type = m-type SLASH m-subtype *(SEMI m-parameter) m-type = discrete-type / composite-type discrete-type = "text" / "image" / "audio" / "video" / "application" / extension-token composite-type = "message" / "multipart" / extension-token extension-token = ietf-token / x-token ietf-token = token x-token = "x-" token m-subtype = extension-token / iana-token iana-token = token m-parameter = m-attribute EQUAL m-value m-attribute = token m-value = token / quoted-string cseq-number = 1*DIGIT CSeq = "CSeq" HCOLON cseq-number LWS Method Date = "Date" HCOLON SIP-date SIP-date = rfc1123-date rfc1123-date = wkday "," SP date1 SP time SP "GMT" date1 = 2DIGIT SP month SP 4DIGIT ; day month year (e.g., 02 Jun 1982) time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00 - 23:59:59 wkday = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" Error-Info = "Error-Info" HCOLON error-uri *(COMMA error-uri) error-uri = LAQUOT absoluteURI RAQUOT *( SEMI generic-param ) Expires = "Expires" HCOLON delta-seconds From = ( "From" / "f" ) HCOLON from-spec from-spec = ( name-addr / addr-spec ) *( SEMI from-param ) from-param = tag-param / generic-param tag-param = "tag" EQUAL token In-Reply-To = "In-Reply-To" HCOLON callid *(COMMA callid) Max-Forwards = "Max-Forwards" HCOLON 1*DIGIT MIME-Version = "MIME-Version" HCOLON 1*DIGIT "." 1*DIGIT Min-Expires = "Min-Expires" HCOLON delta-seconds Organization = "Organization" HCOLON [TEXT-UTF8-TRIM] Priority = "Priority" HCOLON priority-value priority-value = "emergency" / "urgent" / "normal" / "non-urgent" / other-priority other-priority = token Proxy-Authenticate = "Proxy-Authenticate" HCOLON challenge challenge = ("Digest" LWS digest-cln *(COMMA digest-cln)) / other-challenge other-challenge = auth-scheme LWS auth-param *(COMMA auth-param) digest-cln = realm / domain / nonce / opaque / stale / algorithm / qop-options / auth-param realm = "realm" EQUAL realm-value realm-value = quoted-string domain = "domain" EQUAL LDQUOT URI *( 1*SP URI ) RDQUOT URI = absoluteURI / abs-path nonce = "nonce" EQUAL nonce-value nonce-value = quoted-string opaque = "opaque" EQUAL quoted-string stale = "stale" EQUAL ( "true" / "false" ) algorithm = "algorithm" EQUAL ( "MD5" / "MD5-sess" / token ) qop-options = "qop" EQUAL LDQUOT qop-value *("," qop-value) RDQUOT qop-value = "auth" / "auth-int" / token Proxy-Authorization = "Proxy-Authorization" HCOLON credentials Proxy-Require = "Proxy-Require" HCOLON option-tag *(COMMA option-tag) option-tag = token Record-Route = "Record-Route" HCOLON rec-route *(COMMA rec-route) rec-route = name-addr *( SEMI rr-param ) rr-param = generic-param Reply-To = "Reply-To" HCOLON rplyto-spec rplyto-spec = ( name-addr / addr-spec ) *( SEMI rplyto-param ) rplyto-param = generic-param Require = "Require" HCOLON option-tag *(COMMA option-tag) Retry-After = "Retry-After" HCOLON delta-seconds [ comment ] *( SEMI retry-param ) retry-param = ("duration" EQUAL delta-seconds) / generic-param Route = "Route" HCOLON route-param *(COMMA route-param) route-param = name-addr *( SEMI rr-param ) Server = "Server" HCOLON server-val *(LWS server-val) server-val = product / comment product = token [SLASH product-version] product-version = token Subject = ( "Subject" / "s" ) HCOLON [TEXT-UTF8-TRIM] Supported = ( "Supported" / "k" ) HCOLON [option-tag *(COMMA option-tag)] Timestamp = "Timestamp" HCOLON 1*(DIGIT) [ "." *(DIGIT) ] [ LWS delay ] delay = *(DIGIT) [ "." *(DIGIT) ] To = ( "To" / "t" ) HCOLON ( name-addr / addr-spec ) *( SEMI to-param ) to-param = tag-param / generic-param Unsupported = "Unsupported" HCOLON option-tag *(COMMA option-tag) User-Agent = "User-Agent" HCOLON server-val *(LWS server-val) Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm) via-parm = sent-protocol LWS sent-by *( SEMI via-params ) via-params = via-ttl / via-maddr / via-received / via-branch / via-extension via-ttl = "ttl" EQUAL ttl via-maddr = "maddr" EQUAL host via-received = "received" EQUAL (IPv4address / IPv6address) via-branch = "branch" EQUAL token via-extension = generic-param sent-protocol = protocol-name SLASH protocol-version SLASH transport protocol-name = "SIP" / token protocol-version = token transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport sent-by = host [ COLON port ] ttl = 1*3DIGIT ; 0 to 255 Warning = "Warning" HCOLON warning-value *(COMMA warning-value) warning-value = warn-code SP warn-agent SP warn-text warn-code = 3DIGIT warn-agent = hostport / pseudonym ; the name or pseudonym of the server adding ; the Warning header, for use in debugging warn-text = quoted-string pseudonym = token WWW-Authenticate = "WWW-Authenticate" HCOLON challenge extension-header = header-name HCOLON header-value header-name = token header-value = *(TEXT-UTF8char / UTF8-CONT / LWS) message-body = *OCTET belr-5.3.105/tester/res/vcardgrammar.txt000066400000000000000000000111771464614247000201360ustar00rootroot00000000000000vcard-entity = 1*vcard vcard = "BEGIN:VCARD" CRLF "VERSION:4.0" CRLF 1*contentline "END:VCARD" CRLF ; A vCard object MUST include the VERSION and FN properties. ; VERSION MUST come immediately after BEGIN:VCARD. contentline = [group "."] name *(";" param) ":" value CRLF ; When parsing a content line, folded lines must first ; be unfolded according to the unfolding procedure ; described in Section 3.2. ; When generating a content line, lines longer than 75 ; characters SHOULD be folded according to the folding ; procedure described in Section 3.2. group = 1*(ALPHA / DIGIT / "-") name = "SOURCE" / "KIND" / "FN" / "N" / "NICKNAME" / "PHOTO" / "BDAY" / "ANNIVERSARY" / "GENDER" / "ADR" / "TEL" / "EMAIL" / "IMPP" / "LANG" / "TZ" / "GEO" / "TITLE" / "ROLE" / "LOGO" / "ORG" / "MEMBER" / "RELATED" / "CATEGORIES" / "NOTE" / "PRODID" / "REV" / "SOUND" / "UID" / "CLIENTPIDMAP" / "URL" / "KEY" / "FBURL" / "CALADRURI" / "CALURI" / "XML" / iana-token / x-name ; Parsing of the param and value is based on the "name" as ; defined in ABNF sections below. ; Group and name are case-insensitive. iana-token = 1*(ALPHA / DIGIT / "-") ; identifier registered with IANA x-name = "x-" 1*(ALPHA / DIGIT / "-") ; Names that begin with "x-" or "X-" are ; reserved for experimental use, not intended for released ; products, or for use in bilateral agreements. param = any-param ; Allowed parameters depend on property name. param-value = *SAFE-CHAR / DQUOTE *QSAFE-CHAR DQUOTE any-param = (iana-token / x-name) "=" param-value *("," param-value) value = text / text-list / date-list / time-list / date-time-list / date-and-or-time-list / timestamp-list / boolean / integer-list / float-list ;/ URI ; from Section 3 of [RFC3986] / utc-offset ;/ Language-Tag ;/ iana-valuespec text = *TEXT-CHAR TEXT-CHAR = "\\" / "\," / "\n" / WSP / NON-ASCII / %x21-2B / %x2D-5B / %x5D-7E ; Backslashes, commas, and newlines must be encoded. text-list = text *("," text) date-list = date *("," date) time-list = time *("," time) date-time-list = date-time *("," date-time) date-and-or-time-list = date-and-or-time *("," date-and-or-time) timestamp-list = timestamp *("," timestamp) integer-list = integer *("," integer) float-list = float *("," float) boolean = "TRUE" / "FALSE" integer = [sign] 1*DIGIT float = [sign] 1*DIGIT ["." 1*DIGIT] sign = "+" / "-" year = 4DIGIT ; 0000-9999 month = 2DIGIT ; 01-12 day = 2DIGIT ; 01-28/29/30/31 depending on month and leap year hour = 2DIGIT ; 00-23 minute = 2DIGIT ; 00-59 second = 2DIGIT ; 00-58/59/60 depending on leap second zone = utc-designator / utc-offset utc-designator = %x5A ; uppercase "Z" date = year [month day] / year "-" month / "--" month [day] / "--" "-" day date-noreduc = year month day / "--" month day / "--" "-" day date-complete = year month day time = hour [minute [second]] [zone] / "-" minute [second] [zone] / "-" "-" second [zone] time-notrunc = hour [minute [second]] [zone] time-complete = hour minute second [zone] time-designator = %x54 ; uppercase "T" date-time = date-noreduc time-designator time-notrunc timestamp = date-complete time-designator time-complete date-and-or-time = date-time / date / time-designator time utc-offset = sign hour [minute] NON-ASCII = UTF8-2 / UTF8-3 / UTF8-4 ; UTF8-{2,3,4} are defined in [RFC3629] QSAFE-CHAR = WSP / "!" / %x23-7E / NON-ASCII ; Any character except CTLs, DQUOTE SAFE-CHAR = WSP / "!" / %x23-39 / %x3C-7E / NON-ASCII ; Any character except CTLs, DQUOTE, ";", ":" VALUE-CHAR = WSP / VCHAR / NON-ASCII ; Any textual character UTF8-1 = %x00-7F UTF8-2 = %xC2-DF UTF8-tail UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / %xF4 %x80-8F 2( UTF8-tail ) UTF8-tail = %x80-BF ;Language-Tag = ;iana-valuespec = ; a publicly defined valuetype format, registered ; with IANA, as defined in Section 12 of this ; document. belr-5.3.105/tools/000077500000000000000000000000001464614247000137615ustar00rootroot00000000000000belr-5.3.105/tools/CMakeLists.txt000066400000000000000000000034041464614247000165220ustar00rootroot00000000000000############################################################################ # CMakeLists.txt # Copyright (C) 2015-2023 Belledonne Communications, Grenoble France # ############################################################################ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ############################################################################ set(BELR_LIBRARIES_FOR_TOOLS belr) foreach(EXECUTABLE belr-parse belr-demo belr-compiler) set(SOURCE_FILES_CXX ${EXECUTABLE}.cc) bc_apply_compile_flags(SOURCE_FILES_CXX STRICT_OPTIONS_CPP STRICT_OPTIONS_CXX) add_executable(${EXECUTABLE} ${SOURCE_FILES_CXX}) set_target_properties(${EXECUTABLE} PROPERTIES LINKER_LANGUAGE CXX) target_link_libraries(${EXECUTABLE} ${BELR_LIBRARIES_FOR_TOOLS} bctoolbox) endforeach() if(NOT IOS) install(TARGETS belr-parse belr-compiler RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE ) endif() belr-5.3.105/tools/belr-compiler.cc000066400000000000000000000027401464614247000170270ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "belr/abnf.h" #include "belr/grammarbuilder.h" using namespace std; using namespace belr; int main(int argc, char *argv[]) { string file, ofile; if (argc < 3) { cerr << argv[0] << " " << endl; return -1; } file = argv[1]; ofile = argv[2]; // Create a GrammarBuilder: ABNFGrammarBuilder builder; // construct the grammar from the grammar file, the core rules are included since required by most RFCs. shared_ptr grammar = builder.createFromAbnfFile(file, make_shared()); if (!grammar) { cerr << "Fail to create grammar." << endl; return -1; } if (grammar->save(ofile) != 0) { return -1; } return 0; } belr-5.3.105/tools/belr-demo.cc000066400000000000000000000137241464614247000161450ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include "belr/abnf.h" #include "belr/grammarbuilder.h" using namespace ::belr; using namespace ::std; /* * This demo program instanciates a SIP parser from the SIP grammar in a text file. * Then it attempts to parse a SIP URI and fill URI components in our custom C++ object. **/ /*This is our base class for all our parsed elements. It does nothing but is required for run time type identification*/ class SipElement { public: virtual ~SipElement() = default; }; /*this the class representing uri "other" params, per the grammar. They will be added to the SIP-URI when found.*/ class OtherParam : public SipElement { private: string mName; string mValue; public: OtherParam() { } static shared_ptr create() { return make_shared(); } void setName(const string &name) { mName = name; } const string &getName() const { return mName; } void setValue(const string &value) { mValue = value; } const string &getValue() const { return mValue; } }; /*This is our SipUri class, representing sip uris. It has accessors for most common field, including accessing * parameters*/ class SipUri : public SipElement { private: string mUsername; string mHost; string mPasswd; int mPort; list> mOtherParams; public: static shared_ptr create() { return make_shared(); } SipUri() { mPort = 0; } /*follows all the setter/getters of SIP-URI fields*/ void setUsername(const string &username) { mUsername = username; } const string &getUsername() const { return mUsername; } void setHost(const string &host) { mHost = host; } const string &getHost() const { return mHost; } void setPasswd(const string &passwd) { mPasswd = passwd; } const string &getPasswd() const { return mPasswd; } void setPort(int port) { mPort = port; } int getPort() const { return mPort; } void addOtherParam(const shared_ptr ¶ms) { mOtherParams.push_back(params); } const list> &getOtherParams() const { return mOtherParams; } }; int main(int argc, char *argv[]) { string uriToParse; if (argc < 2) { cerr << argv[0] << " " << endl; return -1; } uriToParse = argv[1]; // Create a GrammarBuilder: ABNFGrammarBuilder builder; // construct the grammar from the grammar file, the core rules are included since required by most RFCs. shared_ptr grammar = builder.createFromAbnfFile("sipgrammar.txt", make_shared()); if (!grammar) { cerr << "Could not build grammar from sipgrammar.txt" << endl; return -1; } // now instanciate a parser and assign it collectors and handlers // This parser expects to build objects which are all inherited from SipElement, and that are stored as shared_ptr. Parser> parser(grammar); // Now, tell our parser where to assign elements when they are found during parsing. parser .setHandler( "SIP-URI", make_fn(&SipUri::create)) // tells that whenever a SIP-URI is found, a SipUri object must be created. ->setCollector("user", make_sfn(&SipUri::setUsername)) // tells that when a "user" field is found, SipUri::setUsername() // is to be called for assigning the "user" ->setCollector("host", make_sfn(&SipUri::setHost)) // tells that when host is encountered, use SipUri::setHost() // to assign it to our SipUri object. ->setCollector("port", make_sfn(&SipUri::setPort)) // understood ? ->setCollector("password", make_sfn(&SipUri::setPasswd)) ->setCollector("other-param", make_sfn(&SipUri::addOtherParam)); parser .setHandler("other-param", make_fn(&OtherParam::create)) // when other-param is matched, construct an OtherParam object to hold // the name and value of the other-params. ->setCollector("pname", make_sfn(&OtherParam::setName)) ->setCollector("pvalue", make_sfn(&OtherParam::setValue)); // now, parse the input. We have to tell the parser the root object, which is the SIP-URI in this example. size_t parsedSize = 0; shared_ptr ret = parser.parseInput("SIP-URI", uriToParse, &parsedSize); // if a sip uri is found, the return value is non null and should cast into a SipUri object. if (ret) { shared_ptr sipUri = dynamic_pointer_cast(ret); // now let's print the content of uri object to make sure that its content is consistent with the input passed. cout << "user: " << sipUri->getUsername() << endl; cout << "passord: " << sipUri->getPasswd() << endl; cout << "host: " << sipUri->getHost() << endl; cout << "port: " << sipUri->getPort() << endl; cout << "Listing of other-params:" << endl; for (auto it = sipUri->getOtherParams().begin(); it != sipUri->getOtherParams().end(); ++it) { cout << "name: " << (*it)->getName() << " value: " << (*it)->getValue() << endl; } } else { cerr << "Could not parse [" << uriToParse << "]" << endl; } // so nice, so easy to use belr, isn't it ? return 0; }; belr-5.3.105/tools/belr-parse.cc000066400000000000000000000076001464614247000163270ustar00rootroot00000000000000/* * Copyright (c) 2016-2019 Belledonne Communications SARL. * * This file is part of belr - a language recognition library for ABNF-defined grammars. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include #include "bctoolbox/logging.h" #include "belr/abnf.h" #include "belr/grammarbuilder.h" using namespace belr; using namespace std; int main(int argc, char *argv[]) { const char *file = nullptr, *message_file = nullptr; int rules_first = 0; int i; int repeat_count = 1; if (argc < 2) { cerr << argv[0] << " [--repeat ] [--debug] - test an abnf and instanciate the parser" << endl; cerr << argv[0] << " [--repeat ] [--debug] [rule1] " "[rule2]..." << endl; cerr << argv[0] << " The grammar file may be either an ABNF grammar text file, or a compiled grammar generated by " "belr-compiler tool." << endl; return -1; } for (i = 1; i < argc; ++i) { if (strcmp(argv[i], "--repeat") == 0) { ++i; if (i < argc) { repeat_count = atoi(argv[i]); } } else if (strcmp(argv[i], "--debug") == 0) { bctbx_set_log_level(NULL, BCTBX_LOG_DEBUG); } else { file = argv[i]; ++i; if (i < argc) message_file = argv[i]; break; } } rules_first = i + 1; ifstream ifs; ifs.open(file); if (!ifs.good()) { cerr << "Cannot open " << file << endl; return -1; } char marker[10] = {0}; ifs.read(marker, sizeof(marker) - 1); ifs.close(); shared_ptr grammar; auto t_start = std::chrono::high_resolution_clock::now(); if (string(marker) == "#!belr") { grammar = make_shared(file); if (grammar->load(file) == -1) { cerr << "Fail to load compiled grammar " << file << endl; return -1; } } else { ABNFGrammarBuilder builder; grammar = make_shared(file); grammar->include(make_shared()); grammar = builder.createFromAbnfFile(file, grammar); } auto t_end = std::chrono::high_resolution_clock::now(); cout << "Grammar loading completed in " << std::chrono::duration(t_end - t_start).count() << " milliseconds" << endl; if (message_file) { ifstream istr(message_file); if (!istr.is_open()) { cerr << "Could not open " << message_file << endl; return -1; } stringstream str; str << istr.rdbuf(); DebugParser parser(grammar); list rules; for (int i = rules_first; i < argc; ++i) { rules.push_back(argv[i]); } parser.setObservedRules(rules); size_t parsed; shared_ptr ret; auto t_start = std::chrono::high_resolution_clock::now(); for (int r = 0; r < repeat_count; ++r) { ret = parser.parseInput(argv[rules_first], str.str(), &parsed); } auto t_end = std::chrono::high_resolution_clock::now(); if (parsed < str.str().size()) { cerr << "Parsing ended prematuraly at pos " << parsed << endl; } else { cout << "Parsing done in " << std::chrono::duration(t_end - t_start).count() / repeat_count << " milliseconds" << endl; } if (ret) { ret->tostream(0, cout); } else { cerr << "Parsing failed." << endl; return -1; } } return 0; }; belr-5.3.105/tools/identitygrammar.txt000066400000000000000000000007101464614247000177200ustar00rootroot00000000000000address = scheme ":" [user] "@" host [ gruu-parameter ] scheme = "sip" / "sips" user = 1*( alphanum / escaped / "-" / "+" / "_" / "~" / "." ) escaped = "%" HEXDIG HEXDIG host = *( domainlabel "." ) toplabel [ "." ] domainlabel = alphanum / (alphanum *( alphanum / ( *("-") alphanum) ) ) toplabel = ALPHA / (ALPHA *( alphanum / (*("-") alphanum ) ) ) gruu-parameter = ";gr=" gruu-value gruu-value = 1*( alphanum / "-" / "_" / ":" ) alphanum = ALPHA / DIGIT belr-5.3.105/tools/sipgrammar.txt000066400000000000000000000513321464614247000166700ustar00rootroot00000000000000alphanum = ALPHA / DIGIT reserved = ";" / "/" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / "," unreserved = alphanum / mark mark = "-" / "_" / "." / "!" / "~" / "*" / "'" / "(" / ")" escaped = "%" HEXDIG HEXDIG LWS = [*WSP CRLF] 1*WSP ; linear whitespace SWS = [LWS] ; sep whitespace HCOLON = *( SP / HTAB ) ":" SWS TEXT-UTF8-TRIM = 1*TEXT-UTF8char *(*LWS TEXT-UTF8char) TEXT-UTF8char = %x21-7E / UTF8-NONASCII UTF8-NONASCII = %xC0-DF 1UTF8-CONT / %xE0-EF 2UTF8-CONT / %xF0-F7 3UTF8-CONT / %xF8-Fb 4UTF8-CONT / %xFC-FD 5UTF8-CONT UTF8-CONT = %x80-BF LHEX = DIGIT / %x61-66 ;lowercase a-f token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" ) separators = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "\" / DQUOTE / "/" / "[" / "]" / "?" / "=" / "{" / "}" / SP / HTAB word = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" / "(" / ")" / "<" / ">" / ":" / "\" / DQUOTE / "/" / "[" / "]" / "?" / "{" / "}" ) STAR = SWS "*" SWS ; asterisk SLASH = SWS "/" SWS ; slash EQUAL = SWS "=" SWS ; equal LPAREN = SWS "(" SWS ; left parenthesis RPAREN = SWS ")" SWS ; right parenthesis RAQUOT = ">" SWS ; right angle quote LAQUOT = SWS "<"; left angle quote COMMA = SWS "," SWS ; comma SEMI = SWS ";" SWS ; semicolon COLON = SWS ":" SWS ; colon LDQUOT = SWS DQUOTE; open double quotation mark RDQUOT = DQUOTE SWS ; close double quotation mark comment = LPAREN *(ctext / quoted-pair / comment) RPAREN ctext = %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII / LWS quoted-string = SWS DQUOTE *(qdtext / quoted-pair ) DQUOTE qdtext = LWS / %x21 / %x23-5B / %x5D-7E / UTF8-NONASCII quoted-pair = "\" (%x00-09 / %x0B-0C / %x0E-7F) SIP-URI = "sip:" [ userinfo ] hostport uri-parameters [ headers ] SIPS-URI = "sips:" [ userinfo ] hostport uri-parameters [ headers ] ;userinfo = ( user / telephone-subscriber ) [ ":" password ] "@" ;what is the interest of telephone-subscriber ? userinfo = user [ ":" password ] "@" user = 1*( unreserved / escaped / user-unreserved ) user-unreserved = "&" / "=" / "+" / "$" / "," / ";" / "?" / "/" password = *( unreserved / escaped / "&" / "=" / "+" / "$" / "," ) hostport = host [ ":" port ] host = hostname / IPv4address / IPv6reference hostname = *( domainlabel "." ) toplabel [ "." ] ;domainlabel is modified to avoid an ambiguity domainlabel = alphanum / (alphanum *( alphanum / ( *("-") alphanum) ) ) ;toplabel is modified to avoid an ambiguity toplabel = ALPHA / (ALPHA *( alphanum / (*("-") alphanum ) ) ) IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT IPv6reference = "[" IPv6address "]" IPv6address = hexpart [ ":" IPv4address ] hexpart = hexseq / hexseq "::" [ hexseq ] / "::" [ hexseq ] hexseq = hex4 *( ":" hex4) hex4 = 1*4HEXDIG port = 1*DIGIT uri-parameters = *( ";" uri-parameter) uri-parameter = transport-param / user-param / method-param / ttl-param / maddr-param / lr-param / other-param transport-param = "transport=" ( "udp" / "tcp" / "sctp" / "tls" / other-transport) other-transport = token user-param = "user=" ( "phone" / "ip" / other-user) other-user = token method-param = "method=" Method ttl-param = "ttl=" ttl maddr-param = "maddr=" host lr-param = "lr" other-param = pname [ "=" pvalue ] pname = 1*paramchar pvalue = 1*paramchar paramchar = param-unreserved / unreserved / escaped param-unreserved = "[" / "]" / "/" / ":" / "&" / "+" / "$" headers = "?" header *( "&" header ) header = hname "=" hvalue hname = 1*( hnv-unreserved / unreserved / escaped ) hvalue = *( hnv-unreserved / unreserved / escaped ) hnv-unreserved = "[" / "]" / "/" / "?" / ":" / "+" / "$" SIP-message = Request / Response Request = Request-Line *( message-header ) CRLF [ message-body ] Request-Line = Method SP Request-URI SP SIP-Version CRLF Request-URI = SIP-URI / SIPS-URI / absoluteURI absoluteURI = scheme ":" ( hier-part / opaque-part ) hier-part = ( net-path / abs-path ) [ "?" query ] net-path = "//" authority [ abs-path ] abs-path = "/" path-segments opaque-part = uric-no-slash *uric uric = reserved / unreserved / escaped uric-no-slash = unreserved / escaped / ";" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / "," path-segments = segment *( "/" segment ) segment = *pchar *( ";" param ) param = *pchar pchar = unreserved / escaped / ":" / "@" / "&" / "=" / "+" / "$" / "," scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) authority = srvr / reg-name srvr = [ [ userinfo "@" ] hostport ] reg-name = 1*( unreserved / escaped / "$" / "," / ";" / ":" / "@" / "&" / "=" / "+" ) query = *uric SIP-Version = "SIP" "/" 1*DIGIT "." 1*DIGIT message-header = (Accept / Accept-Encoding / Accept-Language / Alert-Info / Allow / Authentication-Info / Authorization / Call-ID / Call-Info / Contact / Content-Disposition / Content-Encoding / Content-Language / Content-Length / Content-Type / CSeq / Date / Error-Info / Expires / From / In-Reply-To / Max-Forwards / MIME-Version / Min-Expires / Organization / Priority / Proxy-Authenticate / Proxy-Authorization / Proxy-Require / Record-Route / Reply-To / Require / Retry-After / Route / Server / Subject / Supported / Timestamp / To / Unsupported / User-Agent / Via / Warning / WWW-Authenticate / extension-header) CRLF INVITEm = %x49.4E.56.49.54.45 ; INVITE in caps ACKm = %x41.43.4B ; ACK in caps OPTIONSm = %x4F.50.54.49.4F.4E.53 ; OPTIONS in caps BYEm = %x42.59.45 ; BYE in caps CANCELm = %x43.41.4E.43.45.4C ; CANCEL in caps REGISTERm = %x52.45.47.49.53.54.45.52 ; REGISTER in caps Method = INVITEm / ACKm / OPTIONSm / BYEm / CANCELm / REGISTERm / extension-method extension-method = token Response = Status-Line *( message-header ) CRLF [ message-body ] Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF Status-Code = Informational / Redirection / Success / Client-Error / Server-Error / Global-Failure / extension-code extension-code = 3DIGIT Reason-Phrase = *(reserved / unreserved / escaped / UTF8-NONASCII / UTF8-CONT / SP / HTAB) Informational = "100" ; Trying / "180" ; Ringing / "181" ; Call Is Being Forwarded / "182" ; Queued / "183" ; Session Progress Success = "200" ; OK Redirection = "300" ; Multiple Choices / "301" ; Moved Permanently / "302" ; Moved Temporarily / "305" ; Use Proxy / "380" ; Alternative Service Client-Error = "400" ; Bad Request / "401" ; Unauthorized / "402" ; Payment Required / "403" ; Forbidden / "404" ; Not Found / "405" ; Method Not Allowed / "406" ; Not Acceptable / "407" ; Proxy Authentication Required / "408" ; Request Timeout / "410" ; Gone / "413" ; Request Entity Too Large / "414" ; Request-URI Too Large / "415" ; Unsupported Media Type / "416" ; Unsupported URI Scheme / "420" ; Bad Extension / "421" ; Extension Required / "423" ; Interval Too Brief / "480" ; Temporarily not available / "481" ; Call Leg/Transaction Does Not Exist / "482" ; Loop Detected / "483" ; Too Many Hops / "484" ; Address Incomplete / "485" ; Ambiguous / "486" ; Busy Here / "487" ; Request Terminated / "488" ; Not Acceptable Here / "491" ; Request Pending / "493" ; Undecipherable Server-Error = "500" ; Internal Server Error / "501" ; Not Implemented / "502" ; Bad Gateway / "503" ; Service Unavailable / "504" ; Server Time-out / "505" ; SIP Version not supported / "513" ; Message Too Large Global-Failure = "600" ; Busy Everywhere / "603" ; Decline / "604" ; Does not exist anywhere / "606" ; Not Acceptable Accept = "Accept" HCOLON [ accept-range *(COMMA accept-range) ] accept-range = media-range *(SEMI accept-param) media-range = ( "*/*" / ( m-type SLASH "*" ) / ( m-type SLASH m-subtype ) ) *( SEMI m-parameter ) accept-param = ("q" EQUAL qvalue) / generic-param qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) generic-param = token [ EQUAL gen-value ] gen-value = token / host / quoted-string Accept-Encoding = "Accept-Encoding" HCOLON [ encoding *(COMMA encoding) ] encoding = codings *(SEMI accept-param) codings = content-coding / "*" content-coding = token Accept-Language = "Accept-Language" HCOLON [ language *(COMMA language) ] language = language-range *(SEMI accept-param) language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) / "*" ) Alert-Info = "Alert-Info" HCOLON alert-param *(COMMA alert-param) alert-param = LAQUOT absoluteURI RAQUOT *( SEMI generic-param ) Allow = "Allow" HCOLON [Method *(COMMA Method)] Authorization = "Authorization" HCOLON credentials credentials = ("Digest" LWS digest-response) / other-response digest-response = dig-resp *(COMMA dig-resp) dig-resp = username / realm / nonce / digest-uri / dresponse / algorithm / cnonce / opaque / message-qop / nonce-count / auth-param username = "username" EQUAL username-value username-value = quoted-string digest-uri = "uri" EQUAL LDQUOT digest-uri-value RDQUOT digest-uri-value = request-uri ; Equal to request-uri as specified ; by HTTP/1.1 message-qop = "qop" EQUAL qop-value cnonce = "cnonce" EQUAL cnonce-value cnonce-value = nonce-value nonce-count = "nc" EQUAL nc-value nc-value = 8LHEX dresponse = "response" EQUAL request-digest request-digest = LDQUOT 32LHEX RDQUOT auth-param = auth-param-name EQUAL ( token / quoted-string ) auth-param-name = token other-response = auth-scheme LWS auth-param *(COMMA auth-param) auth-scheme = token Authentication-Info = "Authentication-Info" HCOLON ainfo *(COMMA ainfo) ainfo = nextnonce / message-qop / response-auth / cnonce / nonce-count nextnonce = "nextnonce" EQUAL nonce-value response-auth = "rspauth" EQUAL response-digest response-digest = LDQUOT *LHEX RDQUOT Call-ID = ( "Call-ID" / "i" ) HCOLON callid callid = word [ "@" word ] Call-Info = "Call-Info" HCOLON info *(COMMA info) info = LAQUOT absoluteURI RAQUOT *( SEMI info-param) info-param = ( "purpose" EQUAL ( "icon" / "info" / "card" / token ) ) / generic-param Contact = ("Contact" / "m" ) HCOLON ( STAR / (contact-param *(COMMA contact-param))) contact-param = (name-addr / addr-spec) *(SEMI contact-params) name-addr = [ display-name ] LAQUOT addr-spec RAQUOT addr-spec = SIP-URI / SIPS-URI / absoluteURI display-name = *(token LWS)/ quoted-string contact-params = c-p-q / c-p-expires / contact-extension c-p-q = "q" EQUAL qvalue c-p-expires = "expires" EQUAL delta-seconds contact-extension = generic-param delta-seconds = 1*DIGIT Content-Disposition = "Content-Disposition" HCOLON disp-type *( SEMI disp-param ) disp-type = "render" / "session" / "icon" / "alert" / disp-extension-token disp-param = handling-param / generic-param handling-param = "handling" EQUAL ( "optional" / "required" / other-handling ) other-handling = token disp-extension-token = token Content-Encoding = ( "Content-Encoding" / "e" ) HCOLON content-coding *(COMMA content-coding) Content-Language = "Content-Language" HCOLON language-tag *(COMMA language-tag) language-tag = primary-tag *( "-" subtag ) primary-tag = 1*8ALPHA subtag = 1*8ALPHA Content-Length = ( "Content-Length" / "l" ) HCOLON 1*DIGIT Content-Type = ( "Content-Type" / "c" ) HCOLON media-type media-type = m-type SLASH m-subtype *(SEMI m-parameter) m-type = discrete-type / composite-type discrete-type = "text" / "image" / "audio" / "video" / "application" / extension-token composite-type = "message" / "multipart" / extension-token extension-token = ietf-token / x-token ietf-token = token x-token = "x-" token m-subtype = extension-token / iana-token iana-token = token m-parameter = m-attribute EQUAL m-value m-attribute = token m-value = token / quoted-string cseq-number = 1*DIGIT CSeq = "CSeq" HCOLON cseq-number LWS Method Date = "Date" HCOLON SIP-date SIP-date = rfc1123-date rfc1123-date = wkday "," SP date1 SP time SP "GMT" date1 = 2DIGIT SP month SP 4DIGIT ; day month year (e.g., 02 Jun 1982) time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00 - 23:59:59 wkday = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" Error-Info = "Error-Info" HCOLON error-uri *(COMMA error-uri) error-uri = LAQUOT absoluteURI RAQUOT *( SEMI generic-param ) Expires = "Expires" HCOLON delta-seconds From = ( "From" / "f" ) HCOLON from-spec from-spec = ( name-addr / addr-spec ) *( SEMI from-param ) from-param = tag-param / generic-param tag-param = "tag" EQUAL token In-Reply-To = "In-Reply-To" HCOLON callid *(COMMA callid) Max-Forwards = "Max-Forwards" HCOLON 1*DIGIT MIME-Version = "MIME-Version" HCOLON 1*DIGIT "." 1*DIGIT Min-Expires = "Min-Expires" HCOLON delta-seconds Organization = "Organization" HCOLON [TEXT-UTF8-TRIM] Priority = "Priority" HCOLON priority-value priority-value = "emergency" / "urgent" / "normal" / "non-urgent" / other-priority other-priority = token Proxy-Authenticate = "Proxy-Authenticate" HCOLON challenge challenge = ("Digest" LWS digest-cln *(COMMA digest-cln)) / other-challenge other-challenge = auth-scheme LWS auth-param *(COMMA auth-param) digest-cln = realm / domain / nonce / opaque / stale / algorithm / qop-options / auth-param realm = "realm" EQUAL realm-value realm-value = quoted-string domain = "domain" EQUAL LDQUOT URI *( 1*SP URI ) RDQUOT URI = absoluteURI / abs-path nonce = "nonce" EQUAL nonce-value nonce-value = quoted-string opaque = "opaque" EQUAL quoted-string stale = "stale" EQUAL ( "true" / "false" ) algorithm = "algorithm" EQUAL ( "MD5" / "MD5-sess" / token ) qop-options = "qop" EQUAL LDQUOT qop-value *("," qop-value) RDQUOT qop-value = "auth" / "auth-int" / token Proxy-Authorization = "Proxy-Authorization" HCOLON credentials Proxy-Require = "Proxy-Require" HCOLON option-tag *(COMMA option-tag) option-tag = token Record-Route = "Record-Route" HCOLON rec-route *(COMMA rec-route) rec-route = name-addr *( SEMI rr-param ) rr-param = generic-param Reply-To = "Reply-To" HCOLON rplyto-spec rplyto-spec = ( name-addr / addr-spec ) *( SEMI rplyto-param ) rplyto-param = generic-param Require = "Require" HCOLON option-tag *(COMMA option-tag) Retry-After = "Retry-After" HCOLON delta-seconds [ comment ] *( SEMI retry-param ) retry-param = ("duration" EQUAL delta-seconds) / generic-param Route = "Route" HCOLON route-param *(COMMA route-param) route-param = name-addr *( SEMI rr-param ) Server = "Server" HCOLON server-val *(LWS server-val) server-val = product / comment product = token [SLASH product-version] product-version = token Subject = ( "Subject" / "s" ) HCOLON [TEXT-UTF8-TRIM] Supported = ( "Supported" / "k" ) HCOLON [option-tag *(COMMA option-tag)] Timestamp = "Timestamp" HCOLON 1*(DIGIT) [ "." *(DIGIT) ] [ LWS delay ] delay = *(DIGIT) [ "." *(DIGIT) ] To = ( "To" / "t" ) HCOLON ( name-addr / addr-spec ) *( SEMI to-param ) to-param = tag-param / generic-param Unsupported = "Unsupported" HCOLON option-tag *(COMMA option-tag) User-Agent = "User-Agent" HCOLON server-val *(LWS server-val) Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm) via-parm = sent-protocol LWS sent-by *( SEMI via-params ) via-params = via-ttl / via-maddr / via-received / via-branch / via-extension via-ttl = "ttl" EQUAL ttl via-maddr = "maddr" EQUAL host via-received = "received" EQUAL (IPv4address / IPv6address) via-branch = "branch" EQUAL token via-extension = generic-param sent-protocol = protocol-name SLASH protocol-version SLASH transport protocol-name = "SIP" / token protocol-version = token transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport sent-by = host [ COLON port ] ttl = 1*3DIGIT ; 0 to 255 Warning = "Warning" HCOLON warning-value *(COMMA warning-value) warning-value = warn-code SP warn-agent SP warn-text warn-code = 3DIGIT warn-agent = hostport / pseudonym ; the name or pseudonym of the server adding ; the Warning header, for use in debugging warn-text = quoted-string pseudonym = token WWW-Authenticate = "WWW-Authenticate" HCOLON challenge extension-header = header-name HCOLON header-value header-name = token header-value = *(TEXT-UTF8char / UTF8-CONT / LWS) message-body = *OCTET belr-5.3.105/tools/vcardgrammar.txt000066400000000000000000000111771464614247000171770ustar00rootroot00000000000000vcard-entity = 1*vcard vcard = "BEGIN:VCARD" CRLF "VERSION:4.0" CRLF 1*contentline "END:VCARD" CRLF ; A vCard object MUST include the VERSION and FN properties. ; VERSION MUST come immediately after BEGIN:VCARD. contentline = [group "."] name *(";" param) ":" value CRLF ; When parsing a content line, folded lines must first ; be unfolded according to the unfolding procedure ; described in Section 3.2. ; When generating a content line, lines longer than 75 ; characters SHOULD be folded according to the folding ; procedure described in Section 3.2. group = 1*(ALPHA / DIGIT / "-") name = "SOURCE" / "KIND" / "FN" / "N" / "NICKNAME" / "PHOTO" / "BDAY" / "ANNIVERSARY" / "GENDER" / "ADR" / "TEL" / "EMAIL" / "IMPP" / "LANG" / "TZ" / "GEO" / "TITLE" / "ROLE" / "LOGO" / "ORG" / "MEMBER" / "RELATED" / "CATEGORIES" / "NOTE" / "PRODID" / "REV" / "SOUND" / "UID" / "CLIENTPIDMAP" / "URL" / "KEY" / "FBURL" / "CALADRURI" / "CALURI" / "XML" / iana-token / x-name ; Parsing of the param and value is based on the "name" as ; defined in ABNF sections below. ; Group and name are case-insensitive. iana-token = 1*(ALPHA / DIGIT / "-") ; identifier registered with IANA x-name = "x-" 1*(ALPHA / DIGIT / "-") ; Names that begin with "x-" or "X-" are ; reserved for experimental use, not intended for released ; products, or for use in bilateral agreements. param = any-param ; Allowed parameters depend on property name. param-value = *SAFE-CHAR / DQUOTE *QSAFE-CHAR DQUOTE any-param = (iana-token / x-name) "=" param-value *("," param-value) value = text / text-list / date-list / time-list / date-time-list / date-and-or-time-list / timestamp-list / boolean / integer-list / float-list ;/ URI ; from Section 3 of [RFC3986] / utc-offset ;/ Language-Tag ;/ iana-valuespec text = *TEXT-CHAR TEXT-CHAR = "\\" / "\," / "\n" / WSP / NON-ASCII / %x21-2B / %x2D-5B / %x5D-7E ; Backslashes, commas, and newlines must be encoded. text-list = text *("," text) date-list = date *("," date) time-list = time *("," time) date-time-list = date-time *("," date-time) date-and-or-time-list = date-and-or-time *("," date-and-or-time) timestamp-list = timestamp *("," timestamp) integer-list = integer *("," integer) float-list = float *("," float) boolean = "TRUE" / "FALSE" integer = [sign] 1*DIGIT float = [sign] 1*DIGIT ["." 1*DIGIT] sign = "+" / "-" year = 4DIGIT ; 0000-9999 month = 2DIGIT ; 01-12 day = 2DIGIT ; 01-28/29/30/31 depending on month and leap year hour = 2DIGIT ; 00-23 minute = 2DIGIT ; 00-59 second = 2DIGIT ; 00-58/59/60 depending on leap second zone = utc-designator / utc-offset utc-designator = %x5A ; uppercase "Z" date = year [month day] / year "-" month / "--" month [day] / "--" "-" day date-noreduc = year month day / "--" month day / "--" "-" day date-complete = year month day time = hour [minute [second]] [zone] / "-" minute [second] [zone] / "-" "-" second [zone] time-notrunc = hour [minute [second]] [zone] time-complete = hour minute second [zone] time-designator = %x54 ; uppercase "T" date-time = date-noreduc time-designator time-notrunc timestamp = date-complete time-designator time-complete date-and-or-time = date-time / date / time-designator time utc-offset = sign hour [minute] NON-ASCII = UTF8-2 / UTF8-3 / UTF8-4 ; UTF8-{2,3,4} are defined in [RFC3629] QSAFE-CHAR = WSP / "!" / %x23-7E / NON-ASCII ; Any character except CTLs, DQUOTE SAFE-CHAR = WSP / "!" / %x23-39 / %x3C-7E / NON-ASCII ; Any character except CTLs, DQUOTE, ";", ":" VALUE-CHAR = WSP / VCHAR / NON-ASCII ; Any textual character UTF8-1 = %x00-7F UTF8-2 = %xC2-DF UTF8-tail UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / %xF4 %x80-8F 2( UTF8-tail ) UTF8-tail = %x80-BF ;Language-Tag = ;iana-valuespec = ; a publicly defined valuetype format, registered ; with IANA, as defined in Section 12 of this ; document. belr-5.3.105/tools/vcardsample.txt000066400000000000000000000000711464614247000170210ustar00rootroot00000000000000BEGIN:VCARD VERSION:4.0 FN:Sylvain Berfini END:VCARD