pax_global_header00006660000000000000000000000064151212105530014505gustar00rootroot0000000000000052 comment=63dd8765d7904c858ceeeeef7d3da81736a27ded rtpengine-mr13.5.1.3/000077500000000000000000000000001512121055300142675ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/000077500000000000000000000000001512121055300156275ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/ISSUE_TEMPLATE/000077500000000000000000000000001512121055300200125ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/ISSUE_TEMPLATE/bug_report.yml000066400000000000000000000046441512121055300227150ustar00rootroot00000000000000--- # vi: ts=2 sw=2 et: name: Bug Report description: Report a problem labels: ["bug"] body: - type: markdown attributes: value: Thanks for taking the time to fill out this bug report! - type: input id: version attributes: label: rtpengine version the issue has been seen with description: | Please use `rtpengine --version` to get the rtpengine version. placeholder: '12.2.0.0+0~mr12.2.0.0+0~20231205160601.20604+bookworm~1.gbpa75a82' validations: required: false - type: input id: distro attributes: label: Used distribution and its version description: | Please use `lsb_release -a` to get the distribution information. placeholder: Debian 12 validations: required: false - type: input id: kernel attributes: label: Linux kernel version used description: | Please use `uname -r` to get linux kernel version. placeholder: 6.1.0-13-amd64 validations: required: false - type: dropdown id: architecture attributes: label: CPU architecture issue was seen on (see `uname -m`) options: - x86_64 - aarch64 - arm - i686 - other validations: required: false - type: textarea id: expected-behaviour attributes: label: Expected behaviour you didn't see validations: required: false - type: textarea id: unexpected-behaviour attributes: label: Unexpected behaviour you saw validations: required: false - type: textarea id: steps-to-reproduce attributes: label: Steps to reproduce the problem validations: required: false - type: textarea id: logs attributes: label: Additional program output to the terminal or logs illustrating the issue description: | Please paste relevant program terminal or log output here. Where copy/paste is not possible, a photo of the screen might do too, but text is always much preferred. placeholder: This will be automatically formatted into code, so no need for backticks. render: shell validations: required: false - type: textarea id: additional-information attributes: label: Anything else? description: | Links? References? Anything that will give us more context about the issue you are encountering! validations: required: false rtpengine-mr13.5.1.3/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000003641512121055300220050ustar00rootroot00000000000000--- # vi: ts=2 sw=2 et: blank_issues_enabled: true contact_links: - name: rtpengine mailing list url: https://rtpengine.com/mailing-list about: Please ask questions on the mailing list. The issue tracker here is NOT a support forum. rtpengine-mr13.5.1.3/.github/ISSUE_TEMPLATE/feature_request.yml000066400000000000000000000025021512121055300237370ustar00rootroot00000000000000--- # vi: ts=2 sw=2 et: name: Feature request description: Suggest an improvement labels: ["feature"] body: - type: markdown attributes: value: Thanks for taking the time to fill out this feature request! - type: textarea id: description attributes: label: Is your feature request related to a problem? Please describe description: A clear and concise description of what the problem is. validations: required: false - type: textarea id: solution attributes: label: Describe the solution you'd like description: A clear and concise description of what you want to happen. validations: required: false - type: textarea id: alternatives attributes: label: Describe alternatives you've considered description: A clear and concise description of any alternative solutions or features you've considered. validations: required: false - type: input id: version attributes: label: The rtpengine version you checked that didn't have the feature you are asking for description: If this is not the most recently released upstream version, then please check first if it has that feature already. placeholder: '12.2.0.0+0~mr12.2.0.0+0~20231205160601.20604+bookworm~1.gbpa75a82' validations: required: false rtpengine-mr13.5.1.3/.github/actions/000077500000000000000000000000001512121055300172675ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/actions/debpkg-bookworm/000077500000000000000000000000001512121055300223605ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/actions/debpkg-bookworm/Dockerfile000066400000000000000000000005621512121055300243550ustar00rootroot00000000000000FROM debian:bookworm COPY entrypoint.sh /entrypoint.sh # avoid "debconf: (TERM is not set, so the dialog frontend is not usable.)" ENV DEBIAN_FRONTEND noninteractive # disable man-db to speed up builds RUN echo 'man-db man-db/auto-update boolean false' | debconf-set-selections RUN apt-get update && apt-get -y install build-essential ENTRYPOINT ["/entrypoint.sh"] rtpengine-mr13.5.1.3/.github/actions/debpkg-bookworm/action.yml000066400000000000000000000002361512121055300243610ustar00rootroot00000000000000name: "Build Docker image based on Debian/bookworm" description: "Build Docker image based on Debian/bookworm" runs: using: 'docker' image: 'Dockerfile' rtpengine-mr13.5.1.3/.github/actions/debpkg-bookworm/entrypoint.sh000077500000000000000000000006611512121055300251350ustar00rootroot00000000000000#!/bin/bash set -eu -o pipefail echo "*** Starting execution of '$0' ***" echo "** Installing build dependencies **" apt-get -y build-dep -Ppkg.ngcp-rtpengine.nobcg729 . echo "** Building Debian package **" dpkg-buildpackage -Ppkg.ngcp-rtpengine.nobcg729 # We're inside /github/workspace/ echo "** Copying Debian package files to workspace **" cp ../*.deb ../*.buildinfo ../workspace/ echo "*** Finished execution of '$0' ***" rtpengine-mr13.5.1.3/.github/actions/debpkg-sid/000077500000000000000000000000001512121055300213005ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/actions/debpkg-sid/Dockerfile000066400000000000000000000005551512121055300232770ustar00rootroot00000000000000FROM debian:sid COPY entrypoint.sh /entrypoint.sh # avoid "debconf: (TERM is not set, so the dialog frontend is not usable.)" ENV DEBIAN_FRONTEND noninteractive # disable man-db to speed up builds RUN echo 'man-db man-db/auto-update boolean false' | debconf-set-selections RUN apt-get update && apt-get -y install build-essential ENTRYPOINT ["/entrypoint.sh"] rtpengine-mr13.5.1.3/.github/actions/debpkg-sid/action.yml000066400000000000000000000002241512121055300232760ustar00rootroot00000000000000name: "Build Docker image based on Debian/sid" description: "Build Docker image based on Debian/sid" runs: using: 'docker' image: 'Dockerfile' rtpengine-mr13.5.1.3/.github/actions/debpkg-sid/entrypoint.sh000077500000000000000000000006611512121055300240550ustar00rootroot00000000000000#!/bin/bash set -eu -o pipefail echo "*** Starting execution of '$0' ***" echo "** Installing build dependencies **" apt-get -y build-dep -Ppkg.ngcp-rtpengine.nobcg729 . echo "** Building Debian package **" dpkg-buildpackage -Ppkg.ngcp-rtpengine.nobcg729 # We're inside /github/workspace/ echo "** Copying Debian package files to workspace **" cp ../*.deb ../*.buildinfo ../workspace/ echo "*** Finished execution of '$0' ***" rtpengine-mr13.5.1.3/.github/workflows/000077500000000000000000000000001512121055300176645ustar00rootroot00000000000000rtpengine-mr13.5.1.3/.github/workflows/coverity.yml000066400000000000000000000040521512121055300222540ustar00rootroot00000000000000name: Coverity Scan on: push: branches: - coverity_scan schedule: - cron: '13 4 */2 * *' workflow_dispatch: jobs: build: runs-on: ubuntu-24.04 env: COVERITY_SCAN_TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }} COVERITY_SCAN_PROG_URL: https://scan.coverity.com/download/cxx/linux64 COVERITY_SCAN_PROJECT_NAME: sipwise/rtpengine COVERITY_SCAN_NOTIFICATION_EMAIL: development@sipwise.com steps: - name: Checkout source uses: actions/checkout@v4 - name: Update APT cache run: | sudo apt-get update - name: Get build dependencies run: | echo "Generating Debian source for usage on Ubuntu/noble / ubuntu-24.04" cd pkg/deb/ ./generator.sh ./backports/noble rm -rf debian mv noble debian echo "Installing Debian packages" sudo apt-get install -q -y --no-install-recommends git ca-certificates curl sudo apt-get build-dep -q -y . - name: Get coverity scan run: | curl -o cov-analysis.tgz \ $COVERITY_SCAN_PROG_URL \ --form project=$COVERITY_SCAN_PROJECT_NAME \ --form token=$COVERITY_SCAN_TOKEN tar xfz cov-analysis.tgz # We need to disable glib deprecation warnings, as coverity-scan does # not support __attributes__ in enums. - name: Analyze run: | CPPFLAGS="-DGLIB_DISABLE_DEPRECATION_WARNINGS" \ cov-analysis-*/bin/cov-build --dir cov-int make -j4 coverity - name: Submit result run: | tar cfz cov-int.tar.gz cov-int curl \ https://scan.coverity.com/builds?project=$COVERITY_SCAN_PROJECT_NAME \ --form token=$COVERITY_SCAN_TOKEN \ --form email=$COVERITY_SCAN_NOTIFICATION_EMAIL \ --form file=@cov-int.tar.gz \ --form version="`git describe --tags --always`" \ --form description="`git describe --tags --always` / $CI_COMMIT_TITLE / $CI_COMMIT_REF_NAME:$CI_PIPELINE_ID" rtpengine-mr13.5.1.3/.github/workflows/debpkg.yml000066400000000000000000000023511512121055300216440ustar00rootroot00000000000000name: Debian Packaging on: push: pull_request: schedule: - cron: '0 8 * * *' jobs: build-deb-bookworm: runs-on: ubuntu-latest name: Debian pipeline for bookworm steps: - name: Checkout source uses: actions/checkout@v4 - name: Execute Docker debpkg action uses: ./.github/actions/debpkg-bookworm - name: Store Debian package artifacts uses: actions/upload-artifact@v4 with: name: Debian binary package files for bookworm path: '*.deb' - name: Store Debian package build info uses: actions/upload-artifact@v4 with: name: Debian buildinfo file for bookworm path: '*.buildinfo' build-deb-sid: runs-on: ubuntu-latest name: Debian pipeline for sid steps: - name: Checkout source uses: actions/checkout@v4 - name: Execute Docker debpkg action uses: ./.github/actions/debpkg-sid - name: Store Debian package artifacts uses: actions/upload-artifact@v4 with: name: Debian binary package files for sid path: '*.deb' - name: Store Debian package build info uses: actions/upload-artifact@v4 with: name: Debian buildinfo file for sid path: '*.buildinfo' rtpengine-mr13.5.1.3/.github/workflows/shellcheck.yml000066400000000000000000000014171512121055300225170ustar00rootroot00000000000000name: Shellcheck on: push: pull_request: schedule: - cron: '0 8 * * *' jobs: test: runs-on: ubuntu-latest steps: - name: Checkout source uses: actions/checkout@v4 - name: Display original shellcheck version run: shellcheck --version - name: Update shellcheck to latest stable version run: | wget -qO- https://github.com/koalaman/shellcheck/releases/download/stable/shellcheck-stable.linux.x86_64.tar.xz | tar -xJv sudo cp shellcheck-stable/shellcheck /usr/bin/ - name: Display current shellcheck version run: shellcheck --version - name: Shellcheck execution run: shellcheck --exclude=SC1090,SC1091 debian/*.init debian/*.post* debian/*.pre* debian/*-setup el/*.init tests/simulator-tcp.sh rtpengine-mr13.5.1.3/.github/workflows/unit-tests.yml000066400000000000000000000013461512121055300225320ustar00rootroot00000000000000name: Unit Tests on: push: pull_request: schedule: - cron: '0 8 * * *' jobs: test: runs-on: ubuntu-24.04 name: Run unit tests steps: - name: Checkout source uses: actions/checkout@v4 - name: Update APT cache run: | sudo apt-get update - name: Get build dependencies run: | echo "Generating Debian source for usage on Ubuntu/noble / ubuntu-24.04" cd pkg/deb/ ./generator.sh ./backports/noble rm -rf debian mv noble debian echo "Installing Debian packages" sudo apt-get build-dep -q -y . - name: Run unit tests with sanitizers enabled run: | make asan-check rtpengine-mr13.5.1.3/.gitignore000066400000000000000000000000571512121055300162610ustar00rootroot00000000000000.*.sw? *.strhash.c docs/_* bencode.c config.mk rtpengine-mr13.5.1.3/.gitreview000066400000000000000000000001021512121055300162660ustar00rootroot00000000000000[gerrit] host=gerrit.mgm.sipwise.com port=29418 project=rtpengine rtpengine-mr13.5.1.3/.mailmap000066400000000000000000000006141512121055300157110ustar00rootroot00000000000000 Pawel Kuzak Stefan Mititelu Sipwise Jenkins Builder Balajee SV Balajee SV rtpengine-mr13.5.1.3/.readthedocs.yaml000066400000000000000000000002501512121055300175130ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3.10" sphinx: configuration: docs/conf.py python: install: - requirements: docs/requirements.txt rtpengine-mr13.5.1.3/.travis.yml000066400000000000000000000014161512121055300164020ustar00rootroot00000000000000language: c compiler: - gcc - clang before_install: - sudo apt-get update - sudo apt-get -y install devscripts equivs # workarounds for Ubuntu xenial/16.04 LTS, # `apt-get -y build-dep -Ppkg.ngcp-rtpengine.nobcg729 .` # as well as several Build-Deps aren't available - sed -i '/libbcg729-dev/d' debian/control - sed -i 's/default-libmysqlclient-dev/libmysqlclient-dev/' debian/control - sed -i 's/libiptc-dev/iptables-dev/' debian/control - sed -i 's/debhelper-compat.*/debhelper,/' debian/control - mk-build-deps --build-dep --install --remove --root-cmd sudo script: - make -C iptables-extension # `dpkg-parsechangelog [...] -STimestamp` is not available # on Ubuntu xenial/16.04 LTS - RELEASE_DATE=travis-$(date +%s) make -C daemon -j$(nproc) rtpengine-mr13.5.1.3/LICENSE000066400000000000000000001045131512121055300153000ustar00rootroot00000000000000 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 How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . rtpengine-mr13.5.1.3/Makefile000066400000000000000000000030021512121055300157220ustar00rootroot00000000000000.DEFAULT_GOAL := all with_transcoding ?= yes export top_srcdir = $(CURDIR) # Initialize all flags, so that we only compute them once. include lib/deps.Makefile include lib/lib.Makefile .PHONY: all distclean clean coverity all: $(MAKE) -C daemon ifeq ($(with_transcoding),yes) $(MAKE) -C recording-daemon $(MAKE) -C perf-tester endif install: $(MAKE) -C daemon install ifeq ($(with_transcoding),yes) $(MAKE) -C recording-daemon install $(MAKE) -C perf-tester install endif mkdir -p $(DESTDIR)/usr/libexec/rtpengine/ $(DESTDIR)/usr/bin $(DESTDIR)/usr/share/man/man1 install -m 0755 utils/rtpengine-get-table $(DESTDIR)/usr/libexec/rtpengine/ install -m 0755 utils/rtpengine-ctl utils/rtpengine-ng-client $(DESTDIR)/usr/bin/ install -m 0644 utils/rtpengine-ctl.1 utils/rtpengine-ng-client.1 $(DESTDIR)/usr/share/man/man1 coverity: $(MAKE) -C daemon ifeq ($(with_transcoding),yes) $(MAKE) -C recording-daemon $(MAKE) -C perf-tester endif .PHONY: with-kernel with-kernel: all $(MAKE) -C kernel-module install-with-kernel: all install $(MAKE) -C kernel-module install distclean clean: $(MAKE) -C daemon clean $(MAKE) -C recording-daemon clean $(MAKE) -C perf-tester clean $(MAKE) -C kernel-module clean $(MAKE) -C t clean $(MAKE) -C lib clean rm -f config.mk .DEFAULT: $(MAKE) -C daemon $@ $(MAKE) -C recording-daemon $@ $(MAKE) -C perf-tester $(MAKE) -C kernel-module $@ .PHONY: check asan-check asan check: all $(MAKE) -C t asan-check: DO_ASAN_FLAGS=1 $(MAKE) check asan: DO_ASAN_FLAGS=1 $(MAKE) rtpengine-mr13.5.1.3/README.md000066400000000000000000000113331512121055300155470ustar00rootroot00000000000000![Code Testing](https://github.com/sipwise/rtpengine/workflows/Code%20Testing/badge.svg) ![Debian Package CI](https://github.com/sipwise/rtpengine/workflows/Debian%20Packaging/badge.svg) ![Coverity](https://img.shields.io/coverity/scan/sipwise-rtpengine.svg) # What is rtpengine? The [Sipwise](http://www.sipwise.com/) NGCP rtpengine is a proxy for RTP traffic and other UDP based media traffic. It's meant to be used with the [Kamailio SIP proxy](http://www.kamailio.org/) and forms a drop-in replacement for any of the other available RTP and media proxies. Currently the only supported platform is GNU/Linux. ## Mailing List For general questions, discussion, requests for support, and community chat, join our [mailing list](https://rtpengine.com/mailing-list). Please do not use the Github issue tracker for this purpose. ## Features * Media traffic running over either IPv4 or IPv6 * Bridging between IPv4 and IPv6 user agents * Bridging between different IP networks or interfaces * TOS/QoS field setting * Customizable port range * Multi-threaded * Advertising different addresses for operation behind NAT * In-kernel packet forwarding for low-latency and low-CPU performance * Automatic fallback to normal userspace operation if kernel module is unavailable * Support for *Kamailio*'s *rtpproxy* module * Legacy support for old *OpenSER* *mediaproxy* module * HTTP, HTTPS, and WebSocket (WS and WSS) interfaces When used through the *rtpengine* module (or its older counterpart called *rtpproxy-ng*), the following additional features are available: - Full SDP parsing and rewriting - Supports non-standard RTCP ports (RFC 3605) - ICE (RFC 5245) support: + Bridging between ICE-enabled and ICE-unaware user agents + Optionally acting only as additional ICE relay/candidate + Optionally forcing relay of media streams by removing other ICE candidates + Optionally act as an "ICE lite" peer only - SRTP (RFC 3711) support: + Support for SDES (RFC 4568) and DTLS-SRTP (RFC 5764) + AES-CM and AES-F8 ciphers, both in userspace and in kernel + HMAC-SHA1 packet authentication + Bridging between RTP and SRTP user agents + Opportunistic SRTP (RFC 8643) + Legacy non-RFC (dual `m=` line) best-effort SRTP + AES-GCM Authenticated Encryption (AEAD) (RFC 7714) + `a=tls-id` as per RFC 8842 - Support for RTCP profile with feedback extensions (RTP/AVPF, RFC 4585 and 5124) - Arbitrary bridging between any of the supported RTP profiles (RTP/AVP, RTP/AVPF, RTP/SAVP, RTP/SAVPF) - RTP/RTCP multiplexing (RFC 5761) and demultiplexing - Breaking of BUNDLE'd media streams (draft-ietf-mmusic-sdp-bundle-negotiation) - Recording of media streams, decrypted if possible - Transcoding and repacketization - Transcoding between RFC 2833/4733 DTMF event packets and in-band DTMF tones (and vice versa) - Injection of DTMF events or PCM DTMF tones into running audio streams - Playback of pre-recorded streams/announcements - Transcoding between T.38 and PCM (G.711 or other audio codecs) - Silence detection and comfort noise (RFC 3389) payloads * Media forking * Publish/subscribe mechanism for N-to-N media forwarding There is also limited support for *rtpengine* to be used as a drop-in replacement for *Janus* using the native Janus control protocol (see below). *Rtpengine* does not (yet) support: * ZRTP, although ZRTP passes through *rtpengine* just fine ## Documentation Check our general documentation here: * [Read-the-Docs](https://rtpengine.readthedocs.io/en/latest/) For quick access, documentation for usage: * [Compiling and Installing](https://rtpengine.readthedocs.io/en/latest/compiling_and_installing.html) * [Usage](https://rtpengine.readthedocs.io/en/latest/usage.html) * [Transcoding](https://rtpengine.readthedocs.io/en/latest/transcoding.html) * [Call recording](https://rtpengine.readthedocs.io/en/latest/call_recording.html) * [The NG Control Protocol](https://rtpengine.readthedocs.io/en/latest/ng_control_protocol.html) * [The TCP-NG Control Protocol](https://rtpengine.readthedocs.io/en/latest/tcpng_control_protocol.html) * [HTTP/WebSocket support](https://rtpengine.readthedocs.io/en/latest/http_websocket_support.html) * [Janus Interface and Replacement Functionality](https://rtpengine.readthedocs.io/en/latest/janus_interface_and_replacement.html) For quick access, documentation for development: * [Architecture Overview](https://rtpengine.readthedocs.io/en/latest/architecture.html) * [Unit-tests](https://rtpengine.readthedocs.io/en/latest/tests.html) * [Troubleshooting Overview](https://rtpengine.readthedocs.io/en/latest/troubleshooting.html) * [Glossary](https://rtpengine.readthedocs.io/en/latest/glossary.html) ## Sponsors * [Dataport AöR](https://www.dataport.de/) ## Contribution Every bit matters. Join us. Make the rtpengine community stronger. rtpengine-mr13.5.1.3/daemon/000077500000000000000000000000001512121055300155325ustar00rootroot00000000000000rtpengine-mr13.5.1.3/daemon/.gitignore000066400000000000000000000000721512121055300175210ustar00rootroot00000000000000.depend *.8 *.o rtpengine core core.* .ycm_extra_conf.pyc rtpengine-mr13.5.1.3/daemon/.ycm_extra_conf.py000066400000000000000000000104161512121055300211640ustar00rootroot00000000000000import os import ycm_core from clang_helpers import PrepareClangFlags # Set this to the absolute path to the folder (NOT the file!) containing the # compile_commands.json file to use that instead of 'flags'. See here for # more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html # Most projects will NOT need to set this to anything; you can just change the # 'flags' list of compilation flags. Notice that YCM itself uses that approach. compilation_database_folder = '' repl_tmpl = '(int)((x)[a]?(((long)((x)[a])<" flag, clang won't # know which language to use when compiling headers. So it will guess. # Badly. So C++ headers will be compiled as C headers. # You don't want that so ALWAYS specify # a "-std=". # For a C project, you would set this to something like 'c99' instead of # 'c++11'. '-std=c11', # ...and the same thing goes for the magic -x option which specifies the # language that the files to be compiled are written in. This is mostly # relevant for c++ headers. # For a C project, you would set this to 'c' instead of 'c++'. '-x', 'c', ] if compilation_database_folder: database = ycm_core.CompilationDatabase(compilation_database_folder) else: database = None def DirectoryOfThisScript(): return os.path.dirname(os.path.abspath(__file__)) def MakeRelativePathsInFlagsAbsolute(flags, working_directory): if not working_directory: return flags new_flags = [] make_next_absolute = False path_flags = ['-isystem', '-I', '-iquote', '--sysroot='] for flag in flags: new_flag = flag if make_next_absolute: make_next_absolute = False if not flag.startswith('/'): new_flag = os.path.join(working_directory, flag) for path_flag in path_flags: if flag == path_flag: make_next_absolute = True break if flag.startswith(path_flag): path = flag[len(path_flag):] new_flag = path_flag + os.path.join(working_directory, path) break if new_flag: new_flags.append(new_flag) return new_flags def FlagsForFile(filename): if database: # Bear in mind that compilation_info.compiler_flags_ does NOT return a # python list, but a "list-like" StringVec object compilation_info = database.GetCompilationInfoForFile(filename) final_flags = PrepareClangFlags( MakeRelativePathsInFlagsAbsolute( compilation_info.compiler_flags_, compilation_info.compiler_working_dir_), filename) else: relative_to = DirectoryOfThisScript() final_flags = MakeRelativePathsInFlagsAbsolute(flags, relative_to) return { 'flags': final_flags, 'do_cache': True } rtpengine-mr13.5.1.3/daemon/Makefile000066400000000000000000000066141512121055300172010ustar00rootroot00000000000000TARGET= rtpengine export top_srcdir = .. include ../lib/deps.Makefile with_iptables_option ?= yes with_transcoding ?= yes ifeq ($(origin CFLAGS),undefined) CFLAGS:= -g -Wall -Wextra -Wno-sign-compare -Wno-unused-parameter -Wstrict-prototypes -Werror=return-type \ -Wshadow else CFLAGS:= $(CFLAGS) endif CFLAGS+= -pthread CFLAGS+= -std=c11 CFLAGS+= -I. -I../kernel-module/ -I../lib/ -I../include/ CFLAGS+= -Iprivate CFLAGS+= -D_GNU_SOURCE CFLAGS+= $(CFLAGS_GLIB) CFLAGS+= $(CFLAGS_GTHREAD) CFLAGS+= $(CFLAGS_LIBZ) CFLAGS+= $(CFLAGS_OPENSSL) CFLAGS+= $(CFLAGS_LIBEVENT) CFLAGS+= $(CFLAGS_LIBPCRE) CFLAGS+= $(CFLAGS_LIBCURL) CFLAGS+= $(CFLAGS_JSON_GLIB) CFLAGS+= $(CFLAGS_LIBWEBSOCKETS) CFLAGS+= $(CFLAGS_LIBNFTNL) CFLAGS+= $(CFLAGS_LIBMNL) ifeq ($(with_iptables_option),yes) CFLAGS+= $(CFLAGS_LIBIPTC) CFLAGS+= -DWITH_IPTABLES_OPTION endif ifeq ($(with_transcoding),yes) CFLAGS+= $(CFLAGS_LIBAVCODEC) CFLAGS+= $(CFLAGS_LIBAVFORMAT) CFLAGS+= $(CFLAGS_LIBAVUTIL) CFLAGS+= $(CFLAGS_LIBSWRESAMPLE) CFLAGS+= $(CFLAGS_LIBAVFILTER) CFLAGS+= $(CFLAGS_SPANDSP) CFLAGS+= $(CFLAGS_OPUS) CFLAGS+= -DWITH_TRANSCODING CFLAGS+= $(CFLAGS_MYSQL) else CFLAGS+= -DWITHOUT_CODECLIB endif ifeq ($(without_nftables),yes) CFLAGS+= -DWITHOUT_NFTABLES endif ### compile time options: #CFLAGS+= -DSRTCP_KEY_DERIVATION_RFC_COMPLIANCE #CFLAGS+= -DSTRICT_SDES_KEY_LIFETIME LDLIBS:= -lm -ldl LDLIBS+= $(LDLIBS_GLIB) LDLIBS+= $(LDLIBS_GTHREAD) LDLIBS+= $(LDLIBS_LIBZ) LDLIBS+= $(LDLIBS_LIBPCRE) LDLIBS+= $(LDLIBS_LIBCURL) LDLIBS+= $(LDLIBS_LIBCRYPTO) LDLIBS+= $(LDLIBS_OPENSSL) LDLIBS+= $(LDLIBS_LIBEVENT) LDLIBS+= $(LDLIBS_LIBPCAP) LDLIBS+= $(LDLIBS_LIBHIREDIS) LDLIBS+= $(LDLIBS_JSON_GLIB) LDLIBS+= $(LDLIBS_LIBWEBSOCKETS) LDLIBS+= $(LDLIBS_LIBNFTNL) LDLIBS+= $(LDLIBS_LIBMNL) ifeq ($(with_iptables_option),yes) LDLIBS+= $(LDLIBS_LIBIPTC) endif ifeq ($(with_transcoding),yes) LDLIBS+= $(LDLIBS_LIBAVCODEC) LDLIBS+= $(LDLIBS_LIBAVFORMAT) LDLIBS+= $(LDLIBS_LIBAVUTIL) LDLIBS+= $(LDLIBS_LIBSWRESAMPLE) LDLIBS+= $(LDLIBS_LIBAVFILTER) LDLIBS+= $(LDLIBS_SPANDSP) LDLIBS+= $(LDLIBS_OPUS) LDLIBS+= $(LDLIBS_MYSQL) endif ifeq ($(with_transcoding),yes) CFLAGS+= $(CFLAGS_BCG729) LDLIBS+= $(LDLIBS_BCG729) CFLAGS+= $(CFLAGS_CODEC_CHAIN) LDLIBS+= $(LDLIBS_CODEC_CHAIN) endif CFLAGS+= $(CFLAGS_MQTT) LDLIBS+= $(LDLIBS_MQTT) SRCS= main.c kernel.c helpers.c control_tcp.c call.c control_udp.c redis.c \ cookie_cache.c udp_listener.c control_ng_flags_parser.c control_ng.strhash.c sdp.strhash.c stun.c rtcp.c \ crypto.c rtp.c call_interfaces.strhash.c dtls.c log.c cli.strhash.c graphite.c ice.c \ media_socket.c homer.c recording.c statistics.c cdr.c ssrc.c iptables.c tcp_listener.c \ codec.c load.c dtmf.c timerthread.c media_player.c jitter_buffer.c t38.c websocket.c \ mqtt.c janus.strhash.c audio_player.c arena.c ng_client.c ifneq ($(without_nftables),yes) SRCS+= nftables.c endif LIBSRCS= loglib.c auxlib.c rtplib.c str.c socket.c streambuf.c ssllib.c dtmflib.c mix_buffer.c poller.c \ bufferpool.c bencode.c ifeq ($(with_transcoding),yes) LIBSRCS+= codeclib.strhash.c resample.c LIBASM= mvr2s_x64_avx2.S mvr2s_x64_avx512.S mix_in_x64_avx2.S mix_in_x64_avx512bw.S mix_in_x64_sse2.S endif ifneq ($(have_liburing),yes) LIBSRCS+= uring.c endif MDS= rtpengine.ronn MANS= $(MDS:.ronn=.8) include ../lib/common.Makefile install: $(TARGET) $(MANS) install -m 0755 -D $(TARGET) $(DESTDIR)/usr/bin/$(TARGET) install -m 0644 -D $(TARGET).8 $(DESTDIR)/usr/share/man/man8/$(TARGET).8 rtpengine-mr13.5.1.3/daemon/arena.c000066400000000000000000000000731512121055300167640ustar00rootroot00000000000000#include "arena.h" __thread memory_arena_t *memory_arena; rtpengine-mr13.5.1.3/daemon/audio_player.c000066400000000000000000000120121512121055300203470ustar00rootroot00000000000000#ifdef WITH_TRANSCODING #include "audio_player.h" #include "call.h" #include "media_player.h" #include "mix_buffer.h" #include "codec.h" struct audio_player { struct media_player *mp; struct mix_buffer mb; int64_t last_run; unsigned int ptime_us; unsigned int ptime; // in samples unsigned long long pts; }; // call is locked in R and mp is locked static bool audio_player_run(struct media_player *mp) { if (!mp || !mp->media) return false; struct audio_player *ap = mp->media->audio_player; if (!ap || !ap->ptime_us) return false; ap->last_run = rtpe_now; // equals mp->next_run unsigned int size; void *buf = mix_buffer_read_fast(&ap->mb, ap->ptime, &size); if (!buf) { if (!size) { // error or not active: just reschedule mp->next_run += ap->ptime_us; timerthread_obj_schedule_abs(&mp->tt_obj, mp->next_run); return false; } buf = g_alloca(size); mix_buffer_read_slow(&ap->mb, buf, ap->ptime); } media_player_add_packet(mp, buf, size, ap->ptime_us, ap->pts); ap->pts += ap->ptime; return false; } // call locked in W bool audio_player_setup(struct call_media *m, const rtp_payload_type *dst_pt, unsigned int size_ms, unsigned int delay_ms, str_case_value_ht codec_set) { if (!dst_pt) return false; unsigned int bufsize_ms = size_ms; if (!bufsize_ms) bufsize_ms = rtpe_config.audio_buffer_length; if (!bufsize_ms) return false; unsigned int clockrate = fraction_mult(dst_pt->clock_rate, &dst_pt->codec_def->default_clockrate_fact); unsigned int ptime_ms = m->ptime; if (!ptime_ms) ptime_ms = 20; unsigned int ptime_us = ptime_ms * 1000; unsigned int ptime_smp = ptime_ms * clockrate / 1000; // in samples // TODO: shortcut this to avoid the detour of avframe -> avpacket -> avframe (all in s16) rtp_payload_type src_pt = { .payload_type = -1, .encoding = STR_CONST("X-L16"), // XXX support flp .channels = dst_pt->channels, .clock_rate = clockrate, .ptime = ptime_ms, }; struct audio_player *ap; struct media_player *mp = NULL; // check if objects exists and parameters are still the same if ((ap = m->audio_player) && (mp = ap->mp)) { if (!media_player_pt_match(mp, &src_pt, dst_pt)) { /* do reset below */ } if (ap->ptime != ptime_smp || ap->ptime_us != ptime_us) { /* do reset below */ } else // everything matched return true; ilogs(transcoding, LOG_DEBUG, "Resetting audio player for new parameters"); } else ilogs(transcoding, LOG_DEBUG, "Creating new audio player"); // create ap and mp objects, or reset them if needed if (ap) { mix_buffer_destroy(&ap->mb); ZERO(ap->mb); } else ap = m->audio_player = g_new0(__typeof(*m->audio_player), 1); if (mp) media_player_stop(mp); else { media_player_new(&mp, m->monologue, NULL, NULL); ap->mp = mp; } if (!mp) goto error; // set everything up src_pt.codec_def = codec_find_by_av(AV_CODEC_ID_PCM_S16LE), // XXX shortcut this? mp->run_func = audio_player_run; ap->ptime_us = ptime_us; ap->ptime = ptime_smp; if (media_player_setup(mp, &src_pt, dst_pt, codec_set)) goto error; bufsize_ms = MAX(bufsize_ms, ptime_ms * 2); // make sure the buf size is at least 2 frames mix_buffer_init_active(&ap->mb, AV_SAMPLE_FMT_S16, clockrate, dst_pt->channels, bufsize_ms, delay_ms, false); return true; error: audio_player_free(m); return false; } void audio_player_activate(struct call_media *m) { if (!m) return; struct audio_player *ap = m->audio_player; if (!ap) return; mix_buffer_activate(&ap->mb); } // call locked in W void audio_player_start(struct call_media *m) { struct audio_player *ap; if (!m || !(ap = m->audio_player)) return; struct media_player *mp = ap->mp; if (!mp) return; media_player_set_media(mp, m); if (mp->next_run) // already running? return; ilogs(transcoding, LOG_DEBUG, "Starting audio player"); ap->last_run = rtpe_now; mp->next_run = rtpe_now; mp->next_run += ap->ptime_us; timerthread_obj_schedule_abs(&mp->tt_obj, mp->next_run); } void audio_player_add_frame(struct audio_player *ap, uint32_t ssrc, AVFrame *frame) { bool ret = mix_buffer_write(&ap->mb, ssrc, frame->extended_data[0], frame->nb_samples); if (!ret) ilogs(transcoding, LOG_WARN | LOG_FLAG_LIMIT, "Failed to add samples to mix buffer"); av_frame_free(&frame); } void audio_player_stop(struct call_media *m) { struct audio_player *ap = m->audio_player; if (!ap) return; ilogs(transcoding, LOG_DEBUG, "Stopping audio player"); media_player_stop(ap->mp); media_player_put(&ap->mp); } bool audio_player_is_active(struct call_media *m) { if (!m->audio_player) return false; if (!m->audio_player->mp) return false; if (!m->audio_player->mp->next_run) return false; return true; } bool audio_player_pt_match(struct call_media *m, const rtp_payload_type *pt) { return rtp_payload_type_eq_exact(&m->audio_player->mp->coder.handler->dest_pt, pt); } void audio_player_free(struct call_media *m) { struct audio_player *ap = m->audio_player; if (!ap) return; mix_buffer_destroy(&ap->mb); media_player_put(&ap->mp); g_free(ap); m->audio_player = NULL; } #endif rtpengine-mr13.5.1.3/daemon/call.c000066400000000000000000005172271512121055300166270ustar00rootroot00000000000000#include "call.h" #include #include #include #include #include #include #include #include #include #include #include #include "poller.h" #include "helpers.h" #include "log.h" #include "kernel.h" #include "control_tcp.h" #include "streambuf.h" #include "redis.h" #include "str.h" #include "stun.h" #include "rtcp.h" #include "rtp.h" #include "call_interfaces.h" #include "ice.h" #include "log_funcs.h" #include "rtplib.h" #include "cdr.h" #include "ssrc.h" #include "main.h" #include "graphite.h" #include "codec.h" #include "media_player.h" #include "jitter_buffer.h" #include "mqtt.h" #include "janus.h" #include "audio_player.h" #include "bufferpool.h" #include "xt_RTPENGINE.h" struct iterator_helper { uint64_t count; GSList *del_timeout; GSList *del_scheduled; uint64_t transcoded_media; uint64_t user_streams; uint64_t kernel_streams; uint64_t user_kernel_streams; }; struct xmlrpc_helper { enum xmlrpc_format fmt; GQueue strings; }; rwlock_t rtpe_callhash_lock = RWLOCK_STATIC_INIT; rtpe_calls_ht rtpe_callhash; struct call_iterator_list rtpe_call_iterators[NUM_CALL_ITERATORS]; __thread call_t *call_memory_arena; static struct mqtt_timer *global_mqtt_timer; unsigned int call_socket_cpu_affinity = 0; /** * locally needed static declarations */ static int64_t add_ongoing_calls_dur_in_interval(int64_t interval_start, int64_t interval_duration); static void __call_free(call_t *p); static void __call_cleanup(call_t *c); static void __monologue_stop(struct call_monologue *ml); static void media_stop(struct call_media *m); __attribute__((nonnull(1, 2, 4))) static struct media_subscription *__subscribe_medias_both_ways(struct call_media * a, struct call_media * b, bool is_offer, medias_q *); static void call_stream_crypto_reset(struct packet_stream *ps); /* called with call->master_lock held in R */ static int call_timer_delete_monologues(call_t *c) { struct call_monologue *ml; int ret = 0; int64_t min_deleted = 0; bool update = false; /* we need a write lock here */ rwlock_unlock_r(&c->master_lock); rwlock_lock_w(&c->master_lock); for (__auto_type i = c->monologues.head; i; i = i->next) { ml = i->data; if (!ml->deleted_us) continue; if (ml->deleted_us > rtpe_now) { if (!min_deleted || ml->deleted_us < min_deleted) min_deleted = ml->deleted_us; continue; } monologue_destroy(ml); update = true; } c->ml_deleted_us = min_deleted; rwlock_unlock_w(&c->master_lock); if (update) redis_update_onekey(c, rtpe_redis_write); rwlock_lock_r(&c->master_lock); // coverity[missing_unlock : FALSE] return ret; } void call_make_own_foreign(call_t *c, bool foreign) { statistics_update_foreignown_dec(c); bf_set_clear(&c->call_flags, CALL_FLAG_FOREIGN, foreign); statistics_update_foreignown_inc(c); } /* called with hashlock held */ static void call_timer_iterator(call_t *c, struct iterator_helper *hlp) { int64_t check; bool good = false; bool do_update = false; bool has_srtp = false; struct packet_stream *ps; int tmp_t_reason = UNKNOWN; enum call_stream_state css; int64_t timestamp; hlp->count++; rwlock_lock_r(&c->master_lock); log_info_call(c); // final timeout applicable to all calls (own and foreign) int64_t final_timeout = atomic_get_na(&rtpe_config.final_timeout_us); if (final_timeout && rtpe_now >= (c->created + final_timeout)) { ilog(LOG_INFO, "Closing call due to final timeout"); tmp_t_reason = FINAL_TIMEOUT; for (__auto_type it = c->monologues.head; it; it = it->next) { __auto_type ml = it->data; ml->terminated = rtpe_now; ml->term_reason = tmp_t_reason; } goto delete; } // other timeouts not applicable to foreign calls if (IS_FOREIGN_CALL(c)) { goto out; } if (c->deleted_us && rtpe_now >= c->deleted_us && c->last_signal_us <= c->deleted_us) goto delete; if (c->ml_deleted_us && rtpe_now >= c->ml_deleted_us) { if (call_timer_delete_monologues(c)) goto delete; } // conference: call can be created without participants added if (!c->streams.head) goto out; // ignore media timeout if call was recently taken over if (CALL_ISSET(c, FOREIGN_MEDIA) && rtpe_now - c->last_signal_us <= atomic_get_na(&rtpe_config.timeout_us)) goto out; ice_fragments_cleanup(c->sdp_fragments, false); for (__auto_type it = c->streams.head; it; it = it->next) { ps = it->data; timestamp = packet_stream_last_packet(ps); if (!ps->media) continue; g_autoptr(stream_fd) sfd = NULL; { LOCK(&ps->lock); if (ps->selected_sfd) sfd = obj_get(ps->selected_sfd); } if (!sfd) goto no_sfd; /* valid stream */ css = call_stream_state_machine(ps); if (css == CSS_ICE) timestamp = atomic64_get_na(&ps->media->ice_agent->last_activity); if (PS_ISSET(ps, RTP)) { if (rtpe_now - atomic64_get_na(&ps->stats_in->last_packet_us) < 2000000LL) { // kernel activity if (rtpe_now - atomic64_get_na(&ps->last_packet_us) < 2000000LL) hlp->user_kernel_streams++; // user activity else hlp->kernel_streams++; } else if (rtpe_now - atomic64_get_na(&ps->last_packet_us) < 2000000LL) hlp->user_streams++; // user activity } bool active_media = (rtpe_now - packet_stream_last_packet(ps) < 1000000LL); if (active_media) CALL_CLEAR(sfd->call, FOREIGN_MEDIA); no_sfd: if (good) continue; check = atomic_get_na(&rtpe_config.timeout_us); tmp_t_reason = TIMEOUT; if (!MEDIA_ISSET(ps->media, RECV) || !sfd) { check = atomic_get_na(&rtpe_config.silent_timeout_us); tmp_t_reason = SILENT_TIMEOUT; } else if (!PS_ISSET(ps, FILLED)) { check = atomic_get_na(&rtpe_config.offer_timeout_us); tmp_t_reason = OFFER_TIMEOUT; } if (timestamp > rtpe_now || rtpe_now - timestamp < check) good = true; } for (__auto_type it = c->medias.head; it; it = it->next) { struct call_media *media = it->data; if (media->protocol && media->protocol->srtp) has_srtp = true; if (rtpe_config.measure_rtp) ssrc_collect_metrics(media); if (MEDIA_ISSET(media, TRANSCODING)) hlp->transcoded_media++; for (__auto_type l = media->ssrc_hash_in.nq.head; l; l = l->next) { struct ssrc_entry_call *ctx = l->data; if (rtpe_now - atomic64_get_na(&ctx->stats->last_packet_us) < 2000000L) payload_tracker_add(&ctx->tracker, atomic_get_na(&ctx->stats->last_pt)); } for (__auto_type l = media->ssrc_hash_out.nq.head; l; l = l->next) { struct ssrc_entry_call *ctx = l->data; if (rtpe_now - atomic64_get_na(&ctx->stats->last_packet_us) < 2000000L) payload_tracker_add(&ctx->tracker, atomic_get_na(&ctx->stats->last_pt)); } } if (good) { if (IS_FOREIGN_CALL(c)) goto out; // update every 5 minutes if (has_srtp && rtpe_now - atomic64_get_na(&c->last_redis_update_us) > 60*5*1000000LL) do_update = true; goto out; } if (c->ml_deleted_us) goto out; for (__auto_type it = c->monologues.head; it; it = it->next) { __auto_type ml = it->data; ml->terminated = rtpe_now; ml->term_reason = tmp_t_reason; } ilog(LOG_INFO, "Closing call due to timeout"); hlp->del_timeout = g_slist_prepend(hlp->del_timeout, obj_get(c)); goto out; delete: hlp->del_scheduled = g_slist_prepend(hlp->del_scheduled, obj_get(c)); goto out; out: rwlock_unlock_r(&c->master_lock); if (do_update) redis_update_onekey(c, rtpe_redis_write); log_info_pop(); } static size_t cb_curl_write(char *ptr, size_t size, size_t nmemb, void *userdata) { g_string_append_len(userdata, ptr, size * nmemb); return size * nmemb; } void xmlrpc_kill_calls(void *p) { struct xmlrpc_helper *xh = p; unsigned int tries = 0; int els_per_ent = 2; if (xh->fmt == XF_SEMS) els_per_ent = 3; else if (xh->fmt == XF_KAMAILIO) els_per_ent = 4; while (xh->strings.length >= els_per_ent) { const char *url; str *call_id, *tag = NULL, *tag2 = NULL; usleep(10000); url = xh->strings.head->data; call_id = xh->strings.head->next->data; if (xh->fmt == XF_KAMAILIO || xh->fmt == XF_SEMS) { tag = xh->strings.head->next->next->data; if (xh->fmt == XF_KAMAILIO) tag2 = xh->strings.head->next->next->next->data; } if (tag) ilog(LOG_INFO, "Initiating XMLRPC for call (ID " STR_FORMAT_M ", tag " STR_FORMAT_M ")", STR_FMT_M(call_id), STR_FMT_M(tag)); else ilog(LOG_INFO, "Initiating XMLRPC for call (ID " STR_FORMAT_M ")", STR_FMT_M(call_id)); g_autoptr(GString) body = g_string_new(""); g_autoptr(GString) response = g_string_new(""); int ret = CURLE_FAILED_INIT; CURL *curl = curl_easy_init(); if (!curl) goto fault; if ((ret = curl_easy_setopt(curl, CURLOPT_URL, url)) != CURLE_OK) goto fault; if ((ret = curl_easy_setopt(curl, CURLOPT_POST, 1L)) != CURLE_OK) goto fault; if ((ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb_curl_write)) != CURLE_OK) goto fault; if ((ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, response)) != CURLE_OK) goto fault; if ((ret = curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L)) != CURLE_OK) goto fault; if ((ret = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, &(struct curl_slist) {.data = "Content-type: text/xml"})) != CURLE_OK) goto fault; switch (xh->fmt) { case XF_SEMS: g_string_append_printf(body, "" "" "di" "" "sbc" "postControlCmd" "" STR_FORMAT "" "teardown" "" "", STR_FMT(tag)); break; case XF_CALLID: g_string_append_printf(body, "" "" "teardown" "" "" STR_FORMAT "" "" "", STR_FMT(call_id)); break; case XF_KAMAILIO: g_string_append_printf(body, "" "" "dlg.terminate_dlg" "" "" STR_FORMAT "" "" STR_FORMAT "" "" STR_FORMAT "" "" "", STR_FMT(call_id), STR_FMT(tag), STR_FMT(tag2)); break; } if ((ret = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body->str)) != CURLE_OK) goto fault; if ((ret = curl_easy_perform(curl)) != CURLE_OK) goto fault; if (strcasestr(response->str, "")) { if (strcasestr(response->str, "dialog not found")) ; else { ret = CURLE_HTTP_RETURNED_ERROR; goto fault; } } fault: curl_easy_cleanup(curl); if (ret != CURLE_OK) { ilog(LOG_WARNING, "XMLRPC fault occurred: %s", curl_easy_strerror(ret)); tries++; } if (ret == CURLE_OK || tries >= 3) { for (int j = 0; j < els_per_ent; j++) free(g_queue_pop_head(&xh->strings)); tries = 0; } } g_free(xh); } void kill_calls_timer(GSList *list, const char *url) { call_t *ca; struct call_monologue *cm; char *url_prefix = NULL, *url_suffix = NULL; struct xmlrpc_helper *xh = NULL; char url_buf[128]; if (!list) return; /* if url is NULL, it's the scheduled deletions, otherwise it's the timeouts */ if (url) { xh = g_new(__typeof(*xh), 1); url_prefix = NULL; url_suffix = strstr(url, "%%"); if (url_suffix) { url_prefix = strndup(url, url_suffix - url); url_suffix = strdup(url_suffix + 2); } else url_suffix = strdup(url); g_queue_init(&xh->strings); xh->fmt = rtpe_config.fmt; } while (list) { GHashTable *dup_tags = NULL; ca = list->data; log_info_call(ca); if (!url) goto destroy; if (rtpe_config.fmt == XF_KAMAILIO) dup_tags = g_hash_table_new((GHashFunc) str_hash, (GEqualFunc) str_equal); rwlock_lock_r(&ca->master_lock); if (url_prefix) { str cb_addr; if (ca->xmlrpc_callback.len) cb_addr = ca->xmlrpc_callback; else cb_addr = ca->created_from; snprintf(url_buf, sizeof(url_buf), "%s" STR_FORMAT "%s", url_prefix, STR_FMT(&cb_addr), url_suffix); } else snprintf(url_buf, sizeof(url_buf), "%s", url_suffix); switch (rtpe_config.fmt) { case XF_SEMS: for (__auto_type csl = ca->monologues.head; csl; csl = csl->next) { cm = csl->data; if (!cm->tag.s || !cm->tag.len) continue; g_queue_push_tail(&xh->strings, strdup(url_buf)); g_queue_push_tail(&xh->strings, str_dup(&ca->callid)); g_queue_push_tail(&xh->strings, str_dup(&cm->tag)); } break; case XF_CALLID: g_queue_push_tail(&xh->strings, strdup(url_buf)); g_queue_push_tail(&xh->strings, str_dup(&ca->callid)); break; case XF_KAMAILIO: for (__auto_type csl = ca->monologues.head; csl; csl = csl->next) { cm = csl->data; if (!cm->tag.s || !cm->tag.len) continue; for (unsigned int i = 0; i < cm->medias->len; i++) { struct call_media *media = cm->medias->pdata[i]; if (!media) continue; for (__auto_type l = media->media_subscribers.head; l; l = l->next) { struct media_subscription * ms = l->data; struct call_monologue * sub_ml = ms->monologue; if (!sub_ml->tag.s || !sub_ml->tag.len) continue; str *from_tag = g_hash_table_lookup(dup_tags, &sub_ml->tag); if (from_tag && !str_cmp_str(from_tag, &cm->tag)) continue; from_tag = str_dup(&cm->tag); str *to_tag = str_dup(&sub_ml->tag); g_queue_push_tail(&xh->strings, strdup(url_buf)); g_queue_push_tail(&xh->strings, str_dup(&ca->callid)); g_queue_push_tail(&xh->strings, from_tag); g_queue_push_tail(&xh->strings, to_tag); g_hash_table_insert(dup_tags, from_tag, to_tag); } } } break; } rwlock_unlock_r(&ca->master_lock); destroy: call_destroy(ca); obj_release(ca); list = g_slist_delete_link(list, list); log_info_pop(); if (dup_tags) g_hash_table_destroy(dup_tags); } if (xh) thread_create_detach_prio(xmlrpc_kill_calls, xh, rtpe_config.idle_scheduling, rtpe_config.idle_priority, "XMLRPC"); if (url_prefix) free(url_prefix); if (url_suffix) free(url_suffix); } enum thread_looper_action call_timer(void) { struct iterator_helper hlp; ZERO(hlp); ITERATE_CALL_LIST_START(CALL_ITERATOR_TIMER, c); call_timer_iterator(c, &hlp); ITERATE_CALL_LIST_NEXT_END(c); /* stats derived while iterating calls */ RTPE_GAUGE_SET(transcoded_media, hlp.transcoded_media); /* TODO: move out from here? */ RTPE_GAUGE_SET(userspace_streams, hlp.user_streams); RTPE_GAUGE_SET(kernel_only_streams, hlp.kernel_streams); RTPE_GAUGE_SET(kernel_user_streams, hlp.user_kernel_streams); kill_calls_timer(hlp.del_scheduled, NULL); kill_calls_timer(hlp.del_timeout, rtpe_config.b2b_url); /* add thread scope (local) sockets to the global list, in order to release them later */ append_thread_lpr_to_glob_lpr(); return TLA_CONTINUE; } int call_init(void) { rtpe_callhash = rtpe_calls_ht_new(); if (!t_hash_table_is_set(rtpe_callhash)) return -1; for (int i = 0; i < NUM_CALL_ITERATORS; i++) mutex_init(&rtpe_call_iterators[i].lock); if (mqtt_publish_scope() != MPS_NONE) mqtt_timer_start(&global_mqtt_timer, NULL, NULL); return 0; } static void __call_iterator_remove(call_t *c) { for (unsigned int i = 0; i < NUM_CALL_ITERATORS; i++) { call_t *prev_call, *next_call; while (1) { mutex_lock(&rtpe_call_iterators[i].lock); // lock this entry mutex_lock(&c->iterator[i].next_lock); mutex_lock(&c->iterator[i].prev_lock); // try lock adjacent entries prev_call = c->iterator[i].link.prev ? c->iterator[i].link.prev->data : NULL; next_call = c->iterator[i].link.next ? c->iterator[i].link.next->data : NULL; if (prev_call) { if (mutex_trylock(&prev_call->iterator[i].next_lock)) { mutex_unlock(&c->iterator[i].next_lock); mutex_unlock(&c->iterator[i].prev_lock); mutex_unlock(&rtpe_call_iterators[i].lock); continue; // try again } } if (next_call) { if (mutex_trylock(&next_call->iterator[i].prev_lock)) { if (prev_call) mutex_unlock(&prev_call->iterator[i].next_lock); mutex_unlock(&c->iterator[i].next_lock); mutex_unlock(&c->iterator[i].prev_lock); mutex_unlock(&rtpe_call_iterators[i].lock); continue; // try again } } break; // we can remove now } obj_release(c->iterator[i].link.data); rtpe_call_iterators[i].first = t_list_remove_link(rtpe_call_iterators[i].first, &c->iterator[i].link); ZERO(c->iterator[i].link); if (prev_call) mutex_unlock(&prev_call->iterator[i].next_lock); if (next_call) mutex_unlock(&next_call->iterator[i].prev_lock); mutex_unlock(&c->iterator[i].next_lock); mutex_unlock(&c->iterator[i].prev_lock); mutex_unlock(&rtpe_call_iterators[i].lock); } } void call_free(void) { mqtt_timer_stop(&global_mqtt_timer); rtpe_calls_ht_iter iter; t_hash_table_iter_init(&iter, rtpe_callhash); call_t *c; while (t_hash_table_iter_next(&iter, NULL, &c)) { __call_iterator_remove(c); __call_cleanup(c); obj_release(c); } t_hash_table_destroy(rtpe_callhash); } struct call_media *call_media_new(call_t *call) { struct call_media *med; med = uid_alloc(&call->medias); med->call = call; codec_store_init(&med->codecs, med); codec_store_init(&med->offered_codecs, med); med->media_subscribers_ht = subscription_ht_new(); med->media_subscriptions_ht = subscription_ht_new(); mutex_init(&med->dtmf_lock); med->sdp_attr_print = sdp_insert_media_attributes; RESET_BANDWIDTH(med->sdp_media_bandwidth, -1); ssrc_hash_call_init(&med->ssrc_hash_in); ssrc_hash_call_init(&med->ssrc_hash_out); return med; } __attribute__((nonnull(1, 2, 4))) static struct call_media *call_get_media(struct call_monologue *ml, const str *type, enum media_type type_id, const str *media_id, bool trickle_ice, unsigned int want_index, str_ht tracker) { struct call_media *med; call_t *call; if (media_id->len && (!t_hash_table_is_set(tracker) || !t_hash_table_lookup(tracker, media_id))) { if (t_hash_table_is_set(tracker)) t_hash_table_insert(tracker, (str *) media_id, (str *) media_id); // in this case, the media sections can be out of order and the media ID // string is used to determine which media section to operate on. med = t_hash_table_lookup(ml->media_ids, media_id); if (med) { if (med->type_id == type_id) return med; ilogs(ice, LOG_WARN, "Ignoring media ID '" STR_FORMAT "' as media type doesn't match. " "Was media ID changed?", STR_FMT(media_id)); } if (trickle_ice) ilogs(ice, LOG_ERR, "Received trickle ICE SDP fragment with unknown media ID '" STR_FORMAT "'", STR_FMT(media_id)); } assert(want_index > 0); unsigned int arr_index = want_index - 1; // check if we have an existing media struct. resize array if needed if (arr_index >= ml->medias->len) t_ptr_array_set_size(ml->medias, want_index); if (ml->medias->pdata[arr_index]) { __C_DBG("found existing call_media for stream #%u", want_index); return ml->medias->pdata[arr_index]; } __C_DBG("allocating new call_media for stream #%u", want_index); call = ml->call; med = call_media_new(call); med->monologue = ml; med->index = want_index; med->type = call_str_cpy(type); med->type_id = type_id; ml->medias->pdata[arr_index] = med; return med; } __attribute__((nonnull(1, 2, 3))) static struct call_media *__get_media(struct call_monologue *ml, const struct stream_params *sp, const sdp_ng_flags *flags, unsigned int index, str_ht tracker) { if (index == 0) index = sp->index; return call_get_media(ml, &sp->type, sp->type_id, &sp->media_id, !!flags->trickle_ice, index, tracker); } static int __media_want_interfaces(struct call_media *media) { unsigned int want_interfaces = media->logical_intf->list.length; if (rtpe_config.save_interface_ports || !MEDIA_ISSET(media, ICE)) want_interfaces = 1; return want_interfaces; } static void __endpoint_map_truncate(struct endpoint_map *em, unsigned int num_intfs) { while (em->intf_sfds.length > num_intfs) { struct sfd_intf_list *il = t_queue_pop_tail(&em->intf_sfds); free_sfd_intf_list(il); } } static struct endpoint_map *__hunt_endpoint_map(struct call_media *media, unsigned int num_ports, const struct endpoint *ep, const sdp_ng_flags *flags, bool always_reuse, unsigned int want_interfaces) { for (__auto_type l = media->endpoint_maps.tail; l; l = l->prev) { struct endpoint_map *em = l->data; if (em->logical_intf != media->logical_intf) continue; // any of our sockets shut down? for (__auto_type k = em->intf_sfds.head; k; k = k->next) { struct sfd_intf_list *il = k->data; for (__auto_type j = il->list.head; j; j = j->next) { stream_fd *sfd = j->data; if (sfd->socket.fd == -1) return NULL; } } if ((em->wildcard || always_reuse) && em->num_ports >= num_ports && em->intf_sfds.length >= want_interfaces) { __C_DBG("found a wildcard endpoint map%s", ep ? " and filling it in" : ""); if (ep) { em->endpoint = *ep; em->wildcard = 0; } __endpoint_map_truncate(em, want_interfaces); return em; } if (!ep) /* creating wildcard map */ break; if (is_addr_unspecified(&ep->address) || is_addr_unspecified(&em->endpoint.address)) { /* handle zero endpoint address: only compare ports */ if (ep->port != em->endpoint.port) continue; } else if (memcmp(&em->endpoint, ep, sizeof(*ep))) continue; if (em->num_ports >= num_ports && em->intf_sfds.length >= want_interfaces) { if (is_addr_unspecified(&em->endpoint.address)) em->endpoint.address = ep->address; __endpoint_map_truncate(em, want_interfaces); return em; } /* endpoint matches, but not enough ports. flush existing ports * and allocate a new set. */ __C_DBG("endpoint matches, doesn't have enough ports"); t_queue_clear_full(&em->intf_sfds, free_sfd_intf_list); return em; } return NULL; } static struct endpoint_map *__latch_endpoint_map(struct call_media *media) { // simply look for the endpoint map matching the current port if (!media->streams.length) return NULL; struct packet_stream *first_ps = media->streams.head->data; if (!first_ps->sfds.length) return NULL; stream_fd *matcher = first_ps->sfds.head->data; for (__auto_type l = media->endpoint_maps.tail; l; l = l->prev) { struct endpoint_map *em = l->data; if (!em->intf_sfds.length) continue; struct sfd_intf_list *em_il = em->intf_sfds.head->data; if (!em_il->list.length) continue; stream_fd *first = em_il->list.head->data; if (first == matcher) return em; } return NULL; } static struct endpoint_map *__get_endpoint_map(struct call_media *media, unsigned int num_ports, const struct endpoint *ep, const sdp_ng_flags *flags, bool always_reuse) { stream_fd *sfd; socket_intf_list_q intf_sockets = TYPED_GQUEUE_INIT; unsigned int want_interfaces = __media_want_interfaces(media); bool port_latching = false; if (flags && flags->port_latching) port_latching = true; else if (MEDIA_ISSET(media, ICE) && (!flags || !flags->no_port_latching)) port_latching = true; else if (!MEDIA_ISSET(media, RECV) && (!flags || !flags->no_port_latching)) port_latching = true; struct endpoint_map *em = NULL; if (port_latching) em = __latch_endpoint_map(media); if (!em) em = __hunt_endpoint_map(media, num_ports, ep, flags, always_reuse, want_interfaces); if (em) { if (em->intf_sfds.length) return em; // fall through } else { __C_DBG("allocating new %sendpoint map", ep ? "" : "wildcard "); em = uid_alloc(&media->call->endpoint_maps); if (ep) em->endpoint = *ep; else em->wildcard = 1; em->logical_intf = media->logical_intf; t_queue_init(&em->intf_sfds); t_queue_push_tail(&media->endpoint_maps, em); } em->num_ports = num_ports; if (num_ports > 16) return NULL; if (!get_consecutive_ports(&intf_sockets, num_ports, want_interfaces, media)) return NULL; __C_DBG("allocating stream_fds for %u ports", num_ports); MEDIA_CLEAR(media, PUBLIC); struct socket_intf_list *il; while ((il = t_queue_pop_head(&intf_sockets))) { if (il->list.length != num_ports) goto next_il; struct sfd_intf_list *em_il = g_new0(__typeof(*em_il), 1); em_il->local_intf = il->local_intf; t_queue_push_tail(&em->intf_sfds, em_il); struct socket_port_link *spl; while ((spl = t_queue_pop_head(&il->list))) { set_tos(&spl->socket, media->call->tos); if (media->call->cpu_affinity >= 0) { if (socket_cpu_affinity(&spl->socket, media->call->cpu_affinity)) ilog(LOG_ERR | LOG_FLAG_LIMIT, "Failed to set socket CPU " "affinity: %s", strerror(errno)); } sfd = stream_fd_new(spl, media->call, il->local_intf); t_queue_push_tail(&em_il->list, sfd); // not referenced g_free(spl); } next_il: free_socket_intf_list(il); } return em; } static void __assign_stream_fds(struct call_media *media, sfd_intf_list_q *intf_sfds) { int reset_ice = 0; for (__auto_type k = media->streams.head; k; k = k->next) { struct packet_stream *ps = k->data; // use opaque pointer to detect changes void *old_selected_sfd = ps->selected_sfd; t_queue_clear(&ps->sfds); bool sfd_found = false; stream_fd *intf_sfd = NULL; for (__auto_type l = intf_sfds->head; l; l = l->next) { struct sfd_intf_list *il = l->data; stream_fd *sfd = t_queue_peek_nth(&il->list, ps->component - 1); if (!sfd) sfd = ps->selected_sfd; if (!sfd) { // create a dummy sfd. needed to hold RTCP crypto context when // RTCP-mux is in use struct socket_port_link spl = {0}; dummy_socket(&spl.socket, &il->local_intf->spec->local_address.addr); sfd = stream_fd_new(&spl, media->call, il->local_intf); } sfd->stream = ps; t_queue_push_tail(&ps->sfds, sfd); if (ps->selected_sfd == sfd) sfd_found = true; if (ps->selected_sfd && sfd->local_intf == ps->selected_sfd->local_intf) intf_sfd = sfd; } if (!ps->selected_sfd || !sfd_found) { if (intf_sfd) ps->selected_sfd = intf_sfd; else ps->selected_sfd = t_queue_peek_nth(&ps->sfds, 0); } if (old_selected_sfd && ps->selected_sfd && old_selected_sfd != ps->selected_sfd) reset_ice = 1; } if (reset_ice && media->ice_agent) ice_restart(media->ice_agent); } static int __wildcard_endpoint_map(struct call_media *media, unsigned int num_ports) { struct endpoint_map *em; em = __get_endpoint_map(media, num_ports, NULL, NULL, false); if (!em) return -1; __assign_stream_fds(media, &em->intf_sfds); return 0; } static void __rtp_stats_free(struct rtp_stats *p) { bufferpool_unref(p); } TYPED_GHASHTABLE_IMPL(rtp_stats_ht, g_direct_hash, g_direct_equal, NULL, __rtp_stats_free) struct packet_stream *__packet_stream_new(call_t *call) { struct packet_stream *stream; stream = uid_alloc(&call->streams); mutex_init(&stream->lock); stream->call = call; atomic64_set_na(&stream->last_packet_us, rtpe_now); stream->rtp_stats = rtp_stats_ht_new(); recording_init_stream(stream); stream->send_timer = send_timer_new(stream); stream->stats_in = bufferpool_alloc0(shm_bufferpool, sizeof(*stream->stats_in)); stream->stats_out = bufferpool_alloc0(shm_bufferpool, sizeof(*stream->stats_out)); if (rtpe_config.jb_length && !CALL_ISSET(call, DISABLE_JB)) stream->jb = jitter_buffer_new(call); return stream; } static int __num_media_streams(struct call_media *media, unsigned int num_ports) { struct packet_stream *stream; call_t *call = media->call; int ret = 0; // we need at least two, one for RTP and one for RTCP as they hold the crypto context if (num_ports < 2) num_ports = 2; __C_DBG("allocating %i new packet_streams", num_ports - media->streams.length); while (media->streams.length < num_ports) { stream = __packet_stream_new(call); stream->media = media; t_queue_push_tail(&media->streams, stream); stream->component = media->streams.length; ret++; } t_queue_truncate(&media->streams, num_ports); return ret; } __attribute__((nonnull(1, 2, 4))) static void __fill_stream(struct packet_stream *ps, const struct endpoint *epp, unsigned int port_off, const struct stream_params *sp, const sdp_ng_flags *flags) { struct endpoint ep; struct call_media *media = ps->media; atomic64_set_na(&ps->last_packet_us, rtpe_now); ep = *epp; ep.port += port_off; /* if the endpoint hasn't changed, we do nothing */ if (PS_ISSET(ps, FILLED) && !memcmp(&ps->advertised_endpoint, &ep, sizeof(ep))) return; ps->advertised_endpoint = ep; ps->learned_endpoint = ep; /* ignore endpoint changes if we're ICE-enabled and ICE data hasn't changed */ if (PS_ISSET(ps, FILLED) && MEDIA_ISSET(media, ICE) && media->ice_agent && !ice_ufrag_cmp(media->ice_agent, &sp->ice_ufrag)) return; if (!MEDIA_ISSET(media, ICE)) { if (PS_ISSET(ps, FILLED) && ps->selected_sfd && ep.address.family != ps->selected_sfd->socket.family) { if (ep.address.family && !is_trickle_ice_address(&ep)) ilog(LOG_WARN, "Ignoring updated remote endpoint %s%s%s as the local " "socket is %s", FMT_M(endpoint_print_buf(&ep)), ps->selected_sfd->socket.family->name); return; } ps->endpoint = ep; if (PS_ISSET(ps, FILLED) && !MEDIA_ISSET(media, DTLS)) { /* we reset crypto params whenever the endpoint changes */ call_stream_crypto_reset(ps); dtls_shutdown(ps); } } else { // ICE if (!PS_ISSET(ps, FILLED)) ps->endpoint = ep; } /* endpont-learning setup */ if (flags) ps->el_flags = flags->el_option; if (ps->selected_sfd) ilog(LOG_DEBUG, "set FILLED flag for stream, local %s remote %s%s%s", endpoint_print_buf(&ps->selected_sfd->socket.local), FMT_M(endpoint_print_buf(&ps->endpoint))); else ilog(LOG_DEBUG, "set FILLED flag for stream, remote %s%s%s", FMT_M(endpoint_print_buf(&ps->endpoint))); PS_SET(ps, FILLED); if (flags && flags->pierce_nat) PS_SET(ps, PIERCE_NAT); if (flags && flags->nat_wait) PS_SET(ps, NAT_WAIT); } static void call_stream_crypto_reset(struct packet_stream *ps) { ilog(LOG_DEBUG, "Resetting crypto context"); crypto_reset(&ps->crypto); struct call_media *media = ps->media; if (PS_ISSET(ps, RTP)) { mutex_lock(&media->ssrc_hash_in.lock); for (GList *l = media->ssrc_hash_in.nq.head; l; l = l->next) { struct ssrc_entry_call *se = l->data; atomic_set_na(&se->stats->ext_seq, 0); } mutex_unlock(&media->ssrc_hash_in.lock); mutex_lock(&media->ssrc_hash_out.lock); for (GList *l = media->ssrc_hash_in.nq.head; l; l = l->next) { struct ssrc_entry_call *se = l->data; atomic_set_na(&se->stats->ext_seq, 0); } mutex_unlock(&media->ssrc_hash_out.lock); } } /* called with call locked in R or W, but ps not locked */ enum call_stream_state call_stream_state_machine(struct packet_stream *ps) { struct call_media *media = ps->media; if (!ps->selected_sfd || !ps->sfds.length) return CSS_SHUTDOWN; if (MEDIA_ISSET(media, PASSTHRU)) return CSS_RUNNING; enum call_stream_state ret = CSS_RUNNING; if (MEDIA_ISSET(media, ICE) && !ice_has_finished(media)) { if (!MEDIA_ISSET(media, DTLS)) return CSS_ICE; /* handled by ICE timer */ if (!ice_is_usable(media)) return CSS_ICE; /* handled by ICE timer */ // special case: ICE was able to communicate and DTLS is in use. // we can now start DTLS if necessary. ret = CSS_ICE; } if (MEDIA_ISSET(media, DTLS)) { mutex_lock(&ps->lock); struct dtls_connection *d = dtls_ptr(ps->selected_sfd); if (d && d->init && !d->connected) { int dret = dtls(ps->selected_sfd, NULL, NULL); mutex_unlock(&ps->lock); if (dret == 1) call_media_unkernelize(media, "DTLS connected"); return CSS_DTLS; } mutex_unlock(&ps->lock); } if (PS_ISSET(ps, PIERCE_NAT) && PS_ISSET(ps, FILLED) && !PS_ISSET(ps, CONFIRMED)) { for (__auto_type l = ps->sfds.head; l; l = l->next) { static const str fake_rtp = STR_CONST("\x80\x7f\xff\xff\x00\x00\x00\x00" "\x00\x00\x00\x00"); stream_fd *sfd = l->data; if (sfd->socket.fd == -1 || ps->endpoint.address.family == NULL) continue; socket_sendto(&sfd->socket, fake_rtp.s, fake_rtp.len, &ps->endpoint); atomic64_inc_na(&ps->stats_out->packets); atomic64_add_na(&ps->stats_out->bytes, fake_rtp.len); } ret = CSS_PIERCE_NAT; } return ret; } void call_media_state_machine(struct call_media *m) { for (__auto_type l = m->streams.head; l; l = l->next) call_stream_state_machine(l->data); } bool __init_stream(struct packet_stream *ps) { struct call_media *media = ps->media; call_t *call = ps->call; int dtls_active = -1; g_autoptr(char) paramsbuf = NULL; struct dtls_connection *dtls_conn = NULL; if (MEDIA_ISSET(media, DTLS)) { dtls_conn = dtls_ptr(ps->selected_sfd); if (dtls_conn) dtls_active = dtls_is_active(dtls_conn); } else dtls_shutdown(ps); if (MEDIA_ISSET(media, SDES) && dtls_active == -1) { for (__auto_type l = ps->sfds.head; l; l = l->next) { stream_fd *sfd = l->data; struct crypto_params_sdes *cps = media->sdes_in.head ? media->sdes_in.head->data : NULL; crypto_init(&sfd->crypto, cps ? &cps->params : NULL); ilogs(crypto, LOG_DEBUG, "[%s] Initialized incoming SRTP with SDES crypto params: %s%s%s", endpoint_print_buf(&sfd->socket.local), FMT_M(crypto_params_sdes_dump(cps, ¶msbuf))); } struct crypto_params_sdes *cps = media->sdes_out.head ? media->sdes_out.head->data : NULL; crypto_init(&ps->crypto, cps ? &cps->params : NULL); ilogs(crypto, LOG_DEBUG, "[%i] Initialized outgoing SRTP with SDES crypto params: %s%s%s", ps->component, FMT_M(crypto_params_sdes_dump(cps, ¶msbuf))); } if (MEDIA_ISSET(media, DTLS) && !PS_ISSET(ps, FALLBACK_RTCP)) { // we try to retain our role if possible, but must handle a role switch if ((dtls_active && !MEDIA_ISSET(media, SETUP_ACTIVE)) || (!dtls_active && !MEDIA_ISSET(media, SETUP_PASSIVE))) dtls_active = -1; if (dtls_active == -1) dtls_active = (PS_ISSET(ps, FILLED) && MEDIA_ISSET(media, SETUP_ACTIVE)); dtls_connection_init(&ps->ice_dtls, ps, dtls_active, call->dtls_cert); for (__auto_type l = ps->sfds.head; l; l = l->next) { stream_fd *sfd = l->data; dtls_connection_init(&sfd->dtls, ps, dtls_active, call->dtls_cert); } if (!PS_ISSET(ps, FINGERPRINT_VERIFIED) && media->fingerprint.hash_func && media->fingerprint.digest_len && ps->dtls_cert) { if (dtls_verify_cert(ps)) return false; } call_stream_state_machine(ps); } return true; } static void rtp_stats_add_pt(rtp_stats_ht dst, const struct rtp_payload_type *pt) { struct rtp_stats *rs = t_hash_table_lookup(dst, GINT_TO_POINTER(pt->payload_type)); if (rs) return; rs = bufferpool_alloc0(shm_bufferpool, sizeof(*rs)); rs->payload_type = pt->payload_type; rs->clock_rate = pt->clock_rate; t_hash_table_insert(dst, GINT_TO_POINTER(rs->payload_type), rs); } void __rtp_stats_update(rtp_stats_ht dst, struct codec_store *cs) { rtp_payload_type *pt; codecs_ht src = cs->codecs; /* "src" is a call_media->codecs table, while "dst" is a * packet_stream->rtp_stats table */ codecs_ht_iter iter; t_hash_table_iter_init(&iter, src); while (t_hash_table_iter_next(&iter, NULL, &pt)) rtp_stats_add_pt(dst, pt); /* we leave previously added but now removed payload types in place */ } void free_sink_handler(struct sink_handler *sh) { g_free(sh); } /** * A transfer of flags from the subscription to the sink handlers (sink_handler) is done * using the __streams_set_sinks() through __add_sink_handler(). */ void __add_sink_handler(sink_handler_q *q, struct packet_stream *sink, const struct sink_attrs *attrs) { struct sink_handler *sh = g_new0(__typeof(*sh), 1); sh->sink = sink; sh->kernel_output_idx = -1; if (attrs) sh->attrs = *attrs; t_queue_push_tail(q, sh); } // called once before calling __streams_set_sinks once for each sink static void __reset_streams(struct call_media *media) { for (__auto_type l = media->streams.head; l; l = l->next) { struct packet_stream *ps = l->data; t_queue_clear_full(&ps->rtp_sinks, free_sink_handler); t_queue_clear_full(&ps->rtcp_sinks, free_sink_handler); t_queue_clear_full(&ps->rtp_mirrors, free_sink_handler); } } // sets stream flags, sets endpoint addresses if available, // initialises SRTP, starts off the state machine __attribute__((nonnull(1))) static bool __init_streams(struct call_media *A, const struct stream_params *sp, const sdp_ng_flags *flags) { unsigned int port_off = 0; __C_DBG("Stream set flags media %u", A->index); for (__auto_type l = A->streams.head; l; l = l->next) { __auto_type a = l->data; /* RTP */ PS_SET(a, RTP); /* XXX technically not correct, could be udptl too */ __rtp_stats_update(a->rtp_stats, &A->codecs); if (sp) { __fill_stream(a, &sp->rtp_endpoint, port_off, sp, flags); bf_copy_same(&a->ps_flags, &sp->sp_flags, SHARED_FLAG_STRICT_SOURCE | SHARED_FLAG_MEDIA_HANDOVER); } bf_copy_same(&a->ps_flags, &A->media_flags, SHARED_FLAG_ICE); if (!__init_stream(a)) return false; /* RTCP */ if (!MEDIA_ISSET(A, RTCP_MUX)) PS_CLEAR(a, RTCP); else { PS_SET(a, RTCP); PS_CLEAR(a, IMPLICIT_RTCP); } __auto_type ax = a; /* if muxing, this is the fallback RTCP port. it also contains the RTCP * crypto context */ l = l->next; assert(l != NULL); a = l->data; PS_CLEAR(a, RTP); PS_SET(a, RTCP); a->rtcp_sibling = NULL; bf_copy(&a->ps_flags, PS_FLAG_FALLBACK_RTCP, &ax->ps_flags, PS_FLAG_RTCP); ax->rtcp_sibling = a; if (sp) { if (!SP_ISSET(sp, IMPLICIT_RTCP)) { __fill_stream(a, &sp->rtcp_endpoint, port_off, sp, flags); PS_CLEAR(a, IMPLICIT_RTCP); } else { __fill_stream(a, &sp->rtp_endpoint, port_off + 1, sp, flags); PS_SET(a, IMPLICIT_RTCP); } bf_copy_same(&a->ps_flags, &sp->sp_flags, SHARED_FLAG_STRICT_SOURCE | SHARED_FLAG_MEDIA_HANDOVER); } bf_copy_same(&a->ps_flags, &A->media_flags, SHARED_FLAG_ICE); PS_CLEAR(a, ZERO_ADDR); if (!__init_stream(a)) return false; recording_setup_stream(ax); // RTP recording_setup_stream(a); // RTCP port_off += 2; } return true; } /** Called once on media A for each sink media B. * Sets up sink pointers. * flags can be NULL */ __attribute__((nonnull(1, 2, 4))) static bool __streams_set_sinks(struct call_media *A, struct call_media *B, const sdp_ng_flags *flags, const struct sink_attrs *attrs) { __auto_type la = A->streams.head; __auto_type lb = B->streams.head; __C_DBG("Sink init media %u -> %u", A->index, B->index); while (la) { if (!lb) break; // nothing left to do __auto_type a_rtp = la->data; __auto_type b_rtp = lb->data; /* RTP */ // reflect media - pretend reflection also for blackhole, as otherwise // we get SSRC flip-flops on the opposite side // XXX still necessary for blackhole? if (attrs->egress && b_rtp) __add_sink_handler(&a_rtp->rtp_mirrors, b_rtp, attrs); else if (MEDIA_ISSET(A, ECHO) || MEDIA_ISSET(A, BLACKHOLE)) __add_sink_handler(&a_rtp->rtp_sinks, a_rtp, attrs); else if (b_rtp && MEDIA_ISSET(B, SEND)) __add_sink_handler(&a_rtp->rtp_sinks, b_rtp, attrs); PS_CLEAR(b_rtp, ZERO_ADDR); if (is_addr_unspecified(&a_rtp->advertised_endpoint.address) && !(is_trickle_ice_address(&a_rtp->advertised_endpoint) && MEDIA_ISSET(A, TRICKLE_ICE)) && !(flags && flags->replace_zero_address)) PS_SET(b_rtp, ZERO_ADDR); /* RTCP */ lb = lb->next; assert(lb != NULL); __auto_type b_rtcp = lb->data; /* if muxing, this is the fallback RTCP port. it also contains the RTCP * crypto context */ la = la->next; assert(la != NULL); __auto_type a_rtcp = la->data; if (attrs->egress) goto no_rtcp; if (MEDIA_ISSET(A, ECHO) || MEDIA_ISSET(A, BLACKHOLE)) { if (MEDIA_ISSET(A, RTCP_MUX)) { __add_sink_handler(&a_rtp->rtcp_sinks, a_rtp, attrs); __add_sink_handler(&a_rtcp->rtcp_sinks, a_rtp, attrs); } else { __add_sink_handler(&a_rtp->rtcp_sinks, a_rtcp, attrs); __add_sink_handler(&a_rtcp->rtcp_sinks, a_rtcp, attrs); } } else if (MEDIA_ISSET(B, RTCP_MUX)) { __add_sink_handler(&a_rtp->rtcp_sinks, b_rtp, attrs); __add_sink_handler(&a_rtcp->rtcp_sinks, b_rtp, attrs); } else if (b_rtcp) { __add_sink_handler(&a_rtp->rtcp_sinks, b_rtcp, attrs); __add_sink_handler(&a_rtcp->rtcp_sinks, b_rtcp, attrs); } no_rtcp: la = la->next; lb = lb->next; } return true; } __attribute__((nonnull(1, 2, 3))) static void __ice_offer(const sdp_ng_flags *flags, struct call_media *this, struct call_media *other, bool ice_restart) { // the default is to pass through the offering client's choice if (!MEDIA_ISSET(this, INITIALIZED)) bf_copy_same(&this->media_flags, &other->media_flags, MEDIA_FLAG_ICE); // unless instructed not to if (flags->ice_option == ICE_REMOVE) MEDIA_CLEAR(this, ICE); else if (flags->ice_option != ICE_DEFAULT) MEDIA_SET(this, ICE); if (flags->ice_reject) MEDIA_CLEAR(other, ICE); if (flags->passthrough_on) { ilog(LOG_DEBUG, "enabling passthrough mode"); MEDIA_SET(this, PASSTHRU); MEDIA_SET(other, PASSTHRU); return; } if (flags->passthrough_off) { ilog(LOG_DEBUG, "disabling passthrough mode"); MEDIA_CLEAR(this, PASSTHRU); MEDIA_CLEAR(other, PASSTHRU); return; } if (flags->ice_option != ICE_FORCE && flags->ice_option != ICE_DEFAULT) { /* special case: if doing ICE on both sides and ice_force is not set, we cannot * be sure that media will pass through us, so we have to disable certain features */ if (MEDIA_ISSET(this, ICE) && MEDIA_ISSET(other, ICE)) { ilog(LOG_DEBUG, "enabling passthrough mode"); MEDIA_SET(this, PASSTHRU); MEDIA_SET(other, PASSTHRU); return; } // if this is an answer, may see our ICE offer being rejected. if the original offer // wasn't forcing ICE, then we're only acting as a passthrough and so we must disable // ICE on the remote side as well. we can use the presence of an ICE agent as a test // to see whether ICE was originally forced or not. if (flags->opmode == OP_ANSWER && !MEDIA_ISSET(other, ICE) && !this->ice_agent) { MEDIA_CLEAR(this, ICE); return; } } if (flags->opmode == OP_OFFER) { switch (flags->ice_lite_option) { case ICE_LITE_OFF: MEDIA_CLEAR(this, ICE_LITE_SELF); MEDIA_CLEAR(other, ICE_LITE_SELF); break; case ICE_LITE_FWD: MEDIA_SET(this, ICE_LITE_SELF); MEDIA_CLEAR(other, ICE_LITE_SELF); break; case ICE_LITE_BKW: MEDIA_CLEAR(this, ICE_LITE_SELF); MEDIA_SET(other, ICE_LITE_SELF); break; case ICE_LITE_BOTH: MEDIA_SET(this, ICE_LITE_SELF); MEDIA_SET(other, ICE_LITE_SELF); break; default: break; } if (flags->trickle_ice) MEDIA_SET(this, TRICKLE_ICE); } else if (flags->opmode == OP_SUBSCRIBE_REQ) { // leave source media (`other`) alone switch (flags->ice_lite_option) { case ICE_LITE_OFF: case ICE_LITE_BKW: MEDIA_CLEAR(this, ICE_LITE_SELF); break; case ICE_LITE_FWD: case ICE_LITE_BOTH: MEDIA_SET(this, ICE_LITE_SELF); break; default: break; } if (flags->trickle_ice) MEDIA_SET(this, TRICKLE_ICE); } /* determine roles (even if we don't actually do ICE) */ /* this = receiver, other = sender */ /* ICE_CONTROLLING is from our POV, the other ICE flags are from peer's POV */ if (MEDIA_ISSET(this, ICE_LITE_PEER) && !MEDIA_ISSET(this, ICE_LITE_SELF)) MEDIA_SET(this, ICE_CONTROLLING); else if (!MEDIA_ISSET(this, INITIALIZED) || ice_restart) { if (MEDIA_ISSET(this, ICE_LITE_SELF)) MEDIA_CLEAR(this, ICE_CONTROLLING); else if (flags->opmode == OP_OFFER || flags->opmode == OP_SUBSCRIBE_REQ) MEDIA_SET(this, ICE_CONTROLLING); else MEDIA_CLEAR(this, ICE_CONTROLLING); } if (flags->opmode == OP_OFFER) { /* roles are reversed for the other side */ if (MEDIA_ISSET(other, ICE_LITE_PEER) && !MEDIA_ISSET(other, ICE_LITE_SELF)) MEDIA_SET(other, ICE_CONTROLLING); else if (!MEDIA_ISSET(other, INITIALIZED) || ice_restart) { if (MEDIA_ISSET(other, ICE_LITE_SELF)) MEDIA_CLEAR(other, ICE_CONTROLLING); else if (flags->opmode == OP_OFFER) MEDIA_CLEAR(other, ICE_CONTROLLING); else MEDIA_SET(other, ICE_CONTROLLING); } } } static void __sdes_flags(struct crypto_params_sdes *cps, const sdp_ng_flags *flags) { if (!cps) return; if (flags->sdes_unencrypted_srtp && flags->opmode == OP_OFFER) cps->params.session_params.unencrypted_srtp = 1; else if (flags->sdes_encrypted_srtp) cps->params.session_params.unencrypted_srtp = 0; if (flags->sdes_unencrypted_srtcp && flags->opmode == OP_OFFER) cps->params.session_params.unencrypted_srtcp = 1; else if (flags->sdes_encrypted_srtcp) cps->params.session_params.unencrypted_srtcp = 0; if (flags->sdes_unauthenticated_srtp && flags->opmode == OP_OFFER) cps->params.session_params.unauthenticated_srtp = 1; else if (flags->sdes_authenticated_srtp) cps->params.session_params.unauthenticated_srtp = 0; } static bool reorder_sdes_preferences(sdes_q *sdes_in, const str_q *offered_order) { if (!sdes_in || !sdes_in->length || !offered_order || !offered_order->length) return false; // nothing to do ilog(LOG_DEBUG, "The crypto suites for the offerer may be re-ordered"); bool ret = false; sdes_list *insert_pos = sdes_in->head; // first preffered suite goes first in the list for (str_list *l = offered_order->head; l; l = l->next) { str * cs_name = l->data; // find matching suites in `sdes_in` after the current insert position and // move them up __auto_type elem = t_list_find_custom(insert_pos->next, cs_name, crypto_params_sdes_cmp); if (!elem) continue; // found a match: remove from list at current position and insert at // the insert position, then advance insert position __auto_type cps_found = elem->data; ilog(LOG_DEBUG, "Reordering suites for offerer, prioritising: %s (cps tag: %d)", cps_found->params.crypto_suite->name, cps_found->tag); t_queue_delete_link(sdes_in, elem); t_queue_insert_before(sdes_in, insert_pos, cps_found); insert_pos = insert_pos->next; ret = true; } return ret; } /** * Only generates SDES parameters for outgoing SDP, which is our media "out" direction. * `this` is the receiver of the message. * `other` is the sender and can be NULL. */ __attribute__((nonnull(1, 2))) static void __generate_crypto(const sdp_ng_flags *flags, struct call_media *this, struct call_media *other) { /* SDES options, which will be present in the outgoing offer */ sdes_q *cpq = &this->sdes_out; /* SDES options coming to us for processing */ sdes_q *cpq_in = &this->sdes_in; sdes_q *offered_cpq = other ? &other->sdes_in : NULL; /* requested order of crypto suites - generated offer */ const str_q *cpq_order = &flags->sdes_order; /* preferred crypto suites for the offerer - generated answer */ const str_q *offered_order = &flags->sdes_offerer_pref; bool is_offer = (flags->opmode == OP_OFFER || flags->opmode == OP_SUBSCRIBE_REQ); if (!this->protocol || !this->protocol->srtp || MEDIA_ISSET(this, PASSTHRU)) { crypto_params_sdes_queue_clear(cpq); // reorder received SDES suites towards offerer based on preference reorder_sdes_preferences(offered_cpq, offered_order); /* clear crypto for the this leg b/c we are in passthrough mode */ MEDIA_CLEAR(this, DTLS); MEDIA_CLEAR(this, SDES); MEDIA_CLEAR(this, SETUP_PASSIVE); MEDIA_CLEAR(this, SETUP_ACTIVE); if (other && (MEDIA_ISSET(this, PASSTHRU) || !other->protocol)) { /* clear crypto for the other leg as well b/c passthrough only * works if it is done for both legs */ MEDIA_CLEAR(other, DTLS); MEDIA_CLEAR(other, SDES); MEDIA_CLEAR(other, SETUP_PASSIVE); MEDIA_CLEAR(other, SETUP_ACTIVE); } return; } if (is_offer) { /* we always must offer actpass */ MEDIA_SET(this, SETUP_PASSIVE); MEDIA_SET(this, SETUP_ACTIVE); } else { if (flags->dtls_passive && MEDIA_ISSET(this, SETUP_PASSIVE)) MEDIA_CLEAR(this, SETUP_ACTIVE); /* if we can be active, we will, otherwise we'll be passive */ if (MEDIA_ISSET(this, SETUP_ACTIVE)) MEDIA_CLEAR(this, SETUP_PASSIVE); } if (is_offer) { // if neither is enabled yet... if (!MEDIA_ISSET2(this, DTLS, SDES)) { /* we offer both DTLS and SDES by default */ /* unless this is overridden by flags */ if (!flags->dtls_off) MEDIA_SET(this, DTLS); if (!flags->sdes_off) MEDIA_SET(this, SDES); else goto skip_sdes; } } else { /* if both SDES and DTLS are supported, we may use the flags to select one * over the other */ if (MEDIA_ARESET2(this, DTLS, SDES) && flags->dtls_off) { MEDIA_CLEAR(this, DTLS); this->fingerprint.hash_func = NULL; } /* flags->sdes_off is ignored as we prefer DTLS by default */ /* if we're talking to someone understanding DTLS, then skip the SDES stuff */ if (MEDIA_ISSET(this, DTLS)) { MEDIA_CLEAR(this, SDES); goto skip_sdes; } } /* SDES parameters below */ /* OP_OFFER */ if (is_offer) { /* generate full set of params * re-create the entire list - steal for later flushing */ sdes_q cpq_orig = *cpq; /* re-initialize it, in order to fill it out later, taking into account * all the provided SDES flags and parameters */ t_queue_init(cpq); /* if we were offered some crypto suites, copy those first into our offer */ unsigned int c_tag = 1; /* tag for next crypto suite generated by us */ unsigned long types_offered = 0; /* make sure our bit field is large enough */ assert(num_crypto_suites <= sizeof(types_offered) * 8); /* always consider by default that offerer doesn't need re-ordering */ MEDIA_CLEAR(other, REORDER_FORCED); /* add offered crypto parameters */ for (__auto_type l = offered_cpq ? offered_cpq->head : NULL; l; l = l->next) { struct crypto_params_sdes *offered_cps = l->data; if (!flags->sdes_nonew && crypto_params_sdes_check_limitations(flags->sdes_only, flags->sdes_no, offered_cps->params.crypto_suite)) { ilogs(crypto, LOG_DEBUG, "Not offering crypto suite '%s'", offered_cps->params.crypto_suite->name); continue; } struct crypto_params_sdes *cps = g_new0(__typeof(*cps), 1); t_queue_push_tail(cpq, cps); cps->tag = offered_cps->tag; /* our own offered tags will be higher than the ones we received */ if (cps->tag >= c_tag) c_tag = cps->tag + 1; crypto_params_copy(&cps->params, &offered_cps->params, 1); /* we use a bit field to keep track of which types we've seen here */ types_offered |= 1 << cps->params.crypto_suite->idx; __sdes_flags(cps, flags); } /* if we had any suites added before, re-add those that aren't there yet */ struct crypto_params_sdes *cps_orig; while ((cps_orig = t_queue_pop_head(&cpq_orig))) { if ((types_offered & (1 << cps_orig->params.crypto_suite->idx))) { crypto_params_sdes_free(cps_orig); continue; } /* make sure our tag is higher than what we've seen */ if (cps_orig->tag < c_tag) cps_orig->tag = c_tag; if (cps_orig->tag >= c_tag) c_tag = cps_orig->tag + 1; t_queue_push_tail(cpq, cps_orig); types_offered |= 1 << cps_orig->params.crypto_suite->idx; } /* don't add any new crypto suites into the outgoing offer, if `SDES-nonew` is set */ if (!flags->sdes_nonew) { /* generate crypto suite offers for any types that we haven't seen above. * IMPORTANT: for re-invites, this always creates new crypto keys for suites * that weren't accepted before, instead of re-using the same keys (and * suites) that were previously offered but not accepted */ for (unsigned int i = 0; i < num_crypto_suites; i++) { if ((types_offered & (1 << i))) continue; if (crypto_params_sdes_check_limitations(flags->sdes_only, flags->sdes_no, &crypto_suites[i])) { ilogs(crypto, LOG_DEBUG, "Not offering crypto suite '%s'", crypto_suites[i].name); continue; } struct crypto_params_sdes *cps = g_new0(__typeof(*cps), 1); t_queue_push_tail(cpq, cps); cps->tag = c_tag++; cps->params.crypto_suite = &crypto_suites[i]; random_string((unsigned char *) cps->params.master_key, cps->params.crypto_suite->master_key_len); random_string((unsigned char *) cps->params.master_salt, cps->params.crypto_suite->master_salt_len); /* mki = mki_len = 0 */ __sdes_flags(cps, flags); } } /* order the crypto suites list before to send out, if needed */ if (cpq_order && cpq_order->head) { ilog(LOG_DEBUG, "The crypto suites in the outbound SDP will be re-ordered."); sdes_q cpq_orig_list = *cpq; t_queue_init(cpq); /* re-initialize sdes_out */ /* first add those mentioned in the order list, * but only, if they were previously generated/added to the sdes_out */ for (auto_iter(l, cpq_order->head); l; l = l->next) { str * cs_name = l->data; struct crypto_params_sdes * cps_order; __auto_type elem = t_queue_find_custom(&cpq_orig_list, cs_name, crypto_params_sdes_cmp); if (!elem) continue; cps_order = elem->data; ilog(LOG_DEBUG, "New suites order, adding: %s (cps tag: %d)", cps_order->params.crypto_suite->name, cps_order->tag); t_queue_push_tail(cpq, cps_order); t_queue_delete_link(&cpq_orig_list, elem); } /* now add the rest */ while ((cps_orig = t_queue_pop_head(&cpq_orig_list))) { ilog(LOG_DEBUG, "New suites order, adding: %s (cps tag: %d)", cps_orig->params.crypto_suite->name, cps_orig->tag); t_queue_push_tail(cpq, cps_orig); } } /* set preferences list of crypto suites for the offerer, if given */ if (reorder_sdes_preferences(offered_cpq, offered_order)) { /* affects a proper handling of crypto suites ordering, * when sending processed answer to the media session originator */ MEDIA_SET(other, REORDER_FORCED); } } /* OP_ANSWER */ else { /* we pick the first supported crypto suite */ struct crypto_params_sdes *cps = cpq->head ? cpq->head->data : NULL; struct crypto_params_sdes *cps_in = cpq_in->head ? cpq_in->head->data : NULL; struct crypto_params_sdes *offered_cps = (offered_cpq && offered_cpq->head) ? offered_cpq->head->data : NULL; if (flags->sdes_static && cps) { /* reverse logic: instead of looking for a matching crypto suite to put in * our answer, we want to leave what we already had. however, this is only * valid if the currently present crypto suite matches the offer */ for (__auto_type l = cpq_in->head; l; l = l->next) { struct crypto_params_sdes *check_cps = l->data; if (check_cps->params.crypto_suite == cps->params.crypto_suite && check_cps->tag == cps->tag) { ilogs(crypto, LOG_DEBUG, "Found matching existing crypto suite %u:%s", check_cps->tag, check_cps->params.crypto_suite->name); goto cps_match; } } } /* don't try to match, if the offerer requested some suite preferences */ if (offered_cps && !MEDIA_ISSET(this, REORDER_FORCED) ) { ilogs(crypto, LOG_DEBUG, "Looking for matching crypto suite to offered %u:%s", offered_cps->tag, offered_cps->params.crypto_suite->name); /* check if we can do SRTP<>SRTP passthrough. the crypto suite that was accepted * must have been present in what was offered to us */ for (__auto_type l = cpq_in->head; l; l = l->next) { struct crypto_params_sdes *check_cps = l->data; if (check_cps->params.crypto_suite == offered_cps->params.crypto_suite) { ilogs(crypto, LOG_DEBUG, "Found matching crypto suite %u:%s", check_cps->tag, check_cps->params.crypto_suite->name); cps_in = check_cps; break; } } } cps_match: if (cps_in && (!cps || cps->params.crypto_suite != cps_in->params.crypto_suite)) { crypto_params_sdes_queue_clear(cpq); cps = g_new0(__typeof(*cps), 1); t_queue_push_tail(cpq, cps); cps->tag = cps_in->tag; cps->params.crypto_suite = cps_in->params.crypto_suite; if (offered_cps && offered_cps->params.crypto_suite == cps->params.crypto_suite) { // SRTP<>SRTP passthrough cps->params.session_params = cps_in->params.session_params; // XXX verify crypto_params_copy(&cps->params, &offered_cps->params, 1); ilogs(crypto, LOG_DEBUG, "Copied crypto params from %i:%s for SRTP passthrough", cps_in->tag, cps_in->params.crypto_suite->name); } else { random_string((unsigned char *) cps->params.master_key, cps->params.crypto_suite->master_key_len); random_string((unsigned char *) cps->params.master_salt, cps->params.crypto_suite->master_salt_len); /* mki = mki_len = 0 */ cps->params.session_params = cps_in->params.session_params; ilogs(crypto, LOG_DEBUG, "Creating new SRTP crypto params for %i:%s", cps->tag, cps->params.crypto_suite->name); } // flush out crypto suites we ended up not using - leave only one if (!t_queue_remove(cpq_in, cps_in)) ilogs(crypto, LOG_ERR, "BUG: incoming crypto suite not found in queue"); crypto_params_sdes_queue_clear(cpq_in); t_queue_push_tail(cpq_in, cps_in); __sdes_flags(cps, flags); __sdes_flags(cps_in, flags); } } skip_sdes: if (is_offer) { if (MEDIA_ISSET(this, DTLS) && !this->fp_hash_func && flags->dtls_fingerprint.len) this->fp_hash_func = dtls_find_hash_func(&flags->dtls_fingerprint); } } /** * Only accepts or declines proposed crypto suites. Does not generate. * * For an answer, uses the incoming received list of SDES crypto suites to prune * the list of (generated) outgoing crypto suites to contain only the one that was * accepted. */ static void __sdes_accept(struct call_media *media, const sdp_ng_flags *flags) { if (!media->sdes_in.length) return; /* if 'flags->sdes_nonew' is set, don't prune anything, just pass all coming. * 'flags->sdes_nonew' takes precedence over 'sdes_only' and 'sdes_no'. */ if (flags && (t_hash_table_is_set(flags->sdes_only) || t_hash_table_is_set(flags->sdes_no)) && !flags->sdes_nonew) { __auto_type l = media->sdes_in.tail; while (l) { struct crypto_params_sdes *offered_cps = l->data; if (!crypto_params_sdes_check_limitations(flags->sdes_only, flags->sdes_no, offered_cps->params.crypto_suite)) { l = l->prev; continue; } /* stop the iteration intentionally, if only one suite is left * this helps with a case, when the offerer left with no suites, * which can be allowed, but we need to still have at least something */ if (media->sdes_in.length == 1) break; ilogs(crypto, LOG_DEBUG, "Dropping offered crypto suite '%s' from offer due to %s", offered_cps->params.crypto_suite->name, t_hash_table_is_set(flags->sdes_only) ? "not being in SDES-only" : "SDES-no"); __auto_type prev = l->prev; t_queue_delete_link(&media->sdes_in, l); crypto_params_sdes_free(offered_cps); l = prev; } } if (media->sdes_in.head == NULL) return; /* now prune those suites, which weren't accepted */ /* currently incoming suites */ struct crypto_params_sdes *cps_in = media->sdes_in.head->data; /* outgoing suites */ __auto_type l = media->sdes_out.head; while (l) { struct crypto_params_sdes *cps_out = l->data; if (cps_out->params.crypto_suite != cps_in->params.crypto_suite) goto del_next; if (cps_out->tag != cps_in->tag) goto del_next; /* this one's good */ l = l->next; continue; del_next: /* mismatch, prune this one out */ crypto_params_sdes_free(cps_out); __auto_type next = l->next; t_queue_delete_link(&media->sdes_out, l); l = next; } } static void __disable_streams(struct call_media *media, unsigned int num_ports) { struct packet_stream *ps; __num_media_streams(media, num_ports); for (__auto_type l = media->streams.head; l; l = l->next) { ps = l->data; t_queue_clear(&ps->sfds); ps->selected_sfd = NULL; } } static void __rtcp_mux_set(const sdp_ng_flags *flags, struct call_media *media) { if (flags->rtcp_mux_offer || flags->rtcp_mux_require) MEDIA_SET(media, RTCP_MUX); else if (flags->rtcp_mux_demux) MEDIA_CLEAR(media, RTCP_MUX); } __attribute__((nonnull(1, 2, 3))) static void __rtcp_mux_logic(sdp_ng_flags *flags, struct call_media *media, struct call_media *other_media) { if (flags->opmode == OP_ANSWER) { /* default is to go with the client's choice, unless we were instructed not * to do that in the offer (see below) */ if (!MEDIA_ISSET(other_media, RTCP_MUX_OVERRIDE)) bf_copy_same(&media->media_flags, &other_media->media_flags, MEDIA_FLAG_RTCP_MUX); return; } if (flags->opmode != OP_OFFER) return; /* default is to pass through the client's choice, unless our peer is already * talking rtcp-mux, then we stick to that */ if (!MEDIA_ISSET(media, RTCP_MUX)) bf_copy_same(&media->media_flags, &other_media->media_flags, MEDIA_FLAG_RTCP_MUX); else { // mux already in use - unless we were instructed to do something else, // keep using it and don't offer a fallback choice: this is needed as the // fallback port might already be closed flags->rtcp_mux_require = 1; } /* in our offer, we can override the client's choice */ __rtcp_mux_set(flags, media); /* we can also control what's going to happen in the answer. it * depends on what was offered, but by default we go with the other * client's choice */ MEDIA_CLEAR(media, RTCP_MUX_OVERRIDE); if (MEDIA_ISSET(other_media, RTCP_MUX)) { if (!MEDIA_ISSET(media, RTCP_MUX)) { /* rtcp-mux was offered, but we don't offer it ourselves. * the answer will not accept rtcp-mux (wasn't offered). * the default is to accept the offer, unless we want to * explicitly reject it. */ MEDIA_SET(media, RTCP_MUX_OVERRIDE); if (flags->rtcp_mux_reject) MEDIA_CLEAR(other_media, RTCP_MUX); } else { /* rtcp-mux was offered and we offer it too. default is * to go with the other client's choice, unless we want to * either explicitly accept it (possibly demux) or reject * it (possible reverse demux). */ if (flags->rtcp_mux_accept) MEDIA_SET(media, RTCP_MUX_OVERRIDE); else if (flags->rtcp_mux_reject) { MEDIA_SET(media, RTCP_MUX_OVERRIDE); MEDIA_CLEAR(other_media, RTCP_MUX); } } } else { /* rtcp-mux was not offered. we may offer it, but since it wasn't * offered to us, we must not accept it. */ MEDIA_SET(media, RTCP_MUX_OVERRIDE); } } static void __dtls_restart(struct call_media *m) { struct packet_stream *ps; for (__auto_type l = m->streams.head; l; l = l->next) { ps = l->data; PS_CLEAR(ps, FINGERPRINT_VERIFIED); dtls_shutdown(ps); __init_stream(ps); } } static void __fingerprint_changed(struct call_media *m) { if (!m->fingerprint.hash_func || !m->fingerprint.digest_len) return; ilogs(crypto, LOG_INFO, "DTLS fingerprint changed, restarting DTLS"); __dtls_restart(m); } static void __set_all_tos(call_t *c) { for (__auto_type l = c->stream_fds.head; l; l = l->next) { stream_fd *sfd = l->data; if (sfd->socket.fd == -1) continue; set_tos(&sfd->socket, c->tos); } } static void __tos_change(call_t *call, const sdp_ng_flags *flags) { unsigned char new_tos; /* Handle TOS= parameter. Negative value = no change, not present or too large = * revert to default, otherwise set specified value. We only do it in an offer, but * then for both directions. */ if (flags && (flags->opmode != OP_OFFER || flags->tos < 0)) return; if (!flags || flags->tos > 255) new_tos = rtpe_config.default_tos; else new_tos = flags->tos; if (new_tos == call->tos) return; call->tos = new_tos; __set_all_tos(call); } static void __init_interface(struct call_media *media, const str *ifname, int num_ports) { if (!media->logical_intf) media->logical_intf = media->monologue->logical_intf; if (!media->desired_family) media->desired_family = media->monologue->desired_family; if (!media->logical_intf) goto get; if (media->logical_intf->preferred_family != media->desired_family) goto get; if (!ifname || !ifname->s) return; if (!str_cmp_str(&media->logical_intf->name, ifname)) return; if (t_hash_table_lookup(media->logical_intf->rr_specs, ifname)) return; get: media->logical_intf = get_logical_interface(ifname, media->desired_family, num_ports); if (G_UNLIKELY(!media->logical_intf)) { /* legacy support */ if (!str_cmp(ifname, "internal")) media->desired_family = get_socket_family_enum(SF_IP4); else if (!str_cmp(ifname, "external")) media->desired_family = get_socket_family_enum(SF_IP6); else ilog(LOG_WARNING, "Interface '"STR_FORMAT"' not found, using default", STR_FMT(ifname)); media->logical_intf = get_logical_interface(NULL, media->desired_family, num_ports); if (!media->logical_intf) { ilog(LOG_WARNING, "Requested address family (%s) not supported", media->desired_family->name); media->logical_intf = get_logical_interface(NULL, NULL, 0); } } media->monologue->logical_intf = media->logical_intf; media->monologue->desired_family = media->desired_family; } // process received a=setup and related attributes __attribute__((nonnull(1, 2, 3))) static void __dtls_logic(const sdp_ng_flags *flags, struct call_media *other_media, struct stream_params *sp) { uint64_t tmp; /* active and passive are from our POV */ tmp = atomic64_get_na(&other_media->media_flags); bf_copy(&other_media->media_flags, MEDIA_FLAG_SETUP_PASSIVE, &sp->sp_flags, SP_FLAG_SETUP_ACTIVE); bf_copy(&other_media->media_flags, MEDIA_FLAG_SETUP_ACTIVE, &sp->sp_flags, SP_FLAG_SETUP_PASSIVE); /* Allow overriding preference of DTLS over SDES */ if ((flags->opmode == OP_OFFER || flags->opmode == OP_PUBLISH) && flags->sdes_prefer && MEDIA_ISSET(other_media, SDES)) { MEDIA_CLEAR(other_media, DTLS); MEDIA_CLEAR(other_media, SETUP_ACTIVE); MEDIA_CLEAR(other_media, SETUP_PASSIVE); } /* Special case: if this is an offer and actpass is being offered (as it should), * we would normally choose to be active. However, if this is a reinvite and we * were passive previously, we should retain this role. */ if ((flags->opmode == OP_OFFER || flags->opmode == OP_PUBLISH) && MEDIA_ARESET2(other_media, SETUP_ACTIVE, SETUP_PASSIVE) && (tmp & (MEDIA_FLAG_SETUP_ACTIVE | MEDIA_FLAG_SETUP_PASSIVE)) == MEDIA_FLAG_SETUP_PASSIVE) MEDIA_CLEAR(other_media, SETUP_ACTIVE); /* if passive mode is requested, honour it if we can */ if (flags->dtls_reverse_passive && MEDIA_ISSET(other_media, SETUP_PASSIVE)) MEDIA_CLEAR(other_media, SETUP_ACTIVE); // restart DTLS? if (memcmp(&other_media->fingerprint, &sp->fingerprint, sizeof(sp->fingerprint))) { __fingerprint_changed(other_media); other_media->fingerprint = sp->fingerprint; } else if (other_media->tls_id.len && (sp->tls_id.len == 0 || str_cmp_str(&other_media->tls_id, &sp->tls_id))) { // previously seen tls-id and new tls-id is different or not present ilogs(crypto, LOG_INFO, "TLS-ID changed, restarting DTLS"); __dtls_restart(other_media); } else if (ice_is_restart(other_media->ice_agent, sp) && !other_media->tls_id.len && !sp->tls_id.len) { ilogs(crypto, LOG_INFO, "ICE restart without TLS-ID, restarting DTLS"); __dtls_restart(other_media); } other_media->tls_id = call_str_cpy(&sp->tls_id); MEDIA_CLEAR(other_media, DTLS); if (MEDIA_ISSET2(other_media, SETUP_PASSIVE, SETUP_ACTIVE) && other_media->fingerprint.hash_func) MEDIA_SET(other_media, DTLS); } static void __ice_start(struct call_media *media) { if (MEDIA_ISSET(media, PASSTHRU)) { ice_shutdown(&media->ice_agent); return; } if (!MEDIA_ISSET(media, ICE)) /* don't init new ICE agent but leave it running if there is one */ return; ice_agent_init(&media->ice_agent, media); } __attribute__((nonnull(1, 2))) static void __endpoint_loop_protect(struct stream_params *sp, struct call_media *media) { struct intf_address intf_addr; /* check if the advertised endpoint is one of our own addresses. this can * happen by mistake, or it's expected when ICE is in use and passthrough * mode is enabled (in particular when using ICE=force-relay). we still * accept such an endpoint, but flag it for potential loop, which we will * check for later. * */ intf_addr.type = socktype_udp; // if (other_media->protocol && other_media->protocol->tcp) // intf_addr.type = socktype_tcp; intf_addr.addr = sp->rtp_endpoint.address; if (!intf_addr.addr.family) // dummy/empty address return; if (!is_local_endpoint(&intf_addr, sp->rtp_endpoint.port)) return; ilog(LOG_DEBUG, "Detected local endpoint advertised by remote client, " "enabling loop checking"); MEDIA_SET(media, LOOP_CHECK); } static void generate_mid(struct call_media *media, unsigned int idx) { char buf[64]; snprintf(buf, sizeof(buf), "%u", idx); media->media_id = call_str_cpy_c(buf); } __attribute__((nonnull(2, 3, 4))) static void __update_media_id(struct call_media *media, struct call_media *other_media, struct stream_params *sp, const sdp_ng_flags *flags) { struct call_monologue *ml = media ? media->monologue : NULL; struct call_monologue *other_ml = other_media->monologue; if (flags->opmode == OP_OFFER || flags->opmode == OP_PUBLISH || flags->opmode == OP_SUBSCRIBE_REQ || IS_OP_OTHER(flags->opmode)) { if (!other_media->media_id.s) { // incoming side: we copy what we received if (sp->media_id.s) other_media->media_id = call_str_cpy(&sp->media_id); if (other_media->media_id.s) t_hash_table_insert(other_ml->media_ids, &other_media->media_id, other_media); } else { // RFC 5888 allows changing the media ID in a re-invite // (section 9.1), so handle this here. if (sp->media_id.s) { if (str_cmp_str(&other_media->media_id, &sp->media_id)) { // mismatch - update t_hash_table_remove(other_ml->media_ids, &other_media->media_id); other_media->media_id = call_str_cpy(&sp->media_id); t_hash_table_insert(other_ml->media_ids, &other_media->media_id, other_media); } } else { // we already have a media ID, but re-invite offer did not specify // one. we keep what we already have. ; } } if (media && !media->media_id.s) { // outgoing side: we copy from the other side if (other_media->media_id.s) media->media_id = call_str_cpy(&other_media->media_id); else if (flags->generate_mid) { // or generate one generate_mid(media, other_media->index); } if (media->media_id.s) t_hash_table_insert(ml->media_ids, &media->media_id, media); } else { // we already have a media ID. keep what we have and ignore what's // happening on the other side. ; } } else if (flags->opmode == OP_ANSWER) { // in normal cases, if the answer contains a media ID, it must match // the media ID previously sent in the offer, as the order of the media // sections must remain intact (RFC 5888 section 9.1). check this. if (sp->media_id.s) { if (!other_media->media_id.s) ilog(LOG_INFO, "Received answer SDP with media ID ('" STR_FORMAT "') when no media ID was offered", STR_FMT(&sp->media_id)); else if (str_cmp_str(&other_media->media_id, &sp->media_id)) ilog(LOG_WARN, "Received answer SDP with mismatched media ID ('" STR_FORMAT "') when the offered media ID was '" STR_FORMAT "'", STR_FMT(&sp->media_id), STR_FMT(&other_media->media_id)); } } } static void __t38_reset(struct call_media *media, struct call_media *other_media) { ilog(LOG_DEBUG, "Stopping T.38 gateway and resetting %s/" STR_FORMAT " to %s/" STR_FORMAT, media->protocol->name, STR_FMT(&media->format_str), other_media->protocol->name, STR_FMT(&other_media->format_str)); media->protocol = other_media->protocol; media->type_id = other_media->type_id; media->type = call_str_cpy(&other_media->type); media->format_str = call_str_cpy(&other_media->format_str); } __attribute__((nonnull(2, 3, 4))) static void __update_media_protocol(struct call_media *media, struct call_media *other_media, struct stream_params *sp, sdp_ng_flags *flags) { // is the media type still the same? if (str_cmp_str(&other_media->type, &sp->type)) { ilog(LOG_DEBUG, "Updating media type from '" STR_FORMAT "' to '" STR_FORMAT "'", STR_FMT(&other_media->type), STR_FMT(&sp->type)); other_media->type = call_str_cpy(&sp->type); other_media->type_id = codec_get_type(&other_media->type); if (media) { media->type = call_str_cpy(&sp->type); media->type_id = other_media->type_id; } } /* deduct protocol from stream parameters received */ other_media->protocol_str = call_str_cpy(&sp->protocol_str); if (other_media->protocol != sp->protocol) { other_media->protocol = sp->protocol; /* If the endpoint changes the protocol, we reset the other side's * protocol as well. this lets us remember our previous overrides, * but also lets endpoints re-negotiate. * Answers are a special case: handle OSRTP answer/accept, but otherwise * answer with the same protocol that was offered, unless we're instructed * not to. */ if (media) { if (flags->opmode == OP_ANSWER) { // OSRTP? if (other_media->protocol && other_media->protocol->rtp && !other_media->protocol->srtp && media->protocol && media->protocol->osrtp) { // accept it? if (flags->osrtp_accept_rfc) ; else media->protocol = NULL; // reject } // pass through any other protocol change? else if (!flags->protocol_accept) { if (media->protocol && sp->protocol && !media->protocol->osrtp && sp->protocol->osrtp) { ilog(LOG_WARNING, "Ignore OSRTP answer since this was not offered"); other_media->protocol = media->protocol; } } else media->protocol = NULL; } else media->protocol = NULL; } } /* default is to leave the protocol unchanged */ if (media && !media->protocol) media->protocol = other_media->protocol; if (media && !media->protocol_str.s) media->protocol_str = call_str_cpy(&other_media->protocol_str); // handler overrides requested by the user /* allow override of outgoing protocol even if we know it already */ /* but only if this is an RTP-based protocol */ if (media && flags->transport_protocol && proto_is_rtp(other_media->protocol)) media->protocol = flags->transport_protocol; // OSRTP offer requested? if (media && media->protocol && media->protocol->rtp && !media->protocol->srtp && media->protocol->osrtp_proto && flags->osrtp_offer && flags->opmode == OP_OFFER) { media->protocol = &transport_protocols[media->protocol->osrtp_proto]; } // T.38 decoder? if (media && other_media->type_id == MT_IMAGE && proto_is(other_media->protocol, PROTO_UDPTL) && flags->t38_decode) { media->protocol = flags->transport_protocol; if (!media->protocol) media->protocol = &transport_protocols[PROTO_RTP_AVP]; media->type_id = MT_AUDIO; media->type = call_str_cpy_c("audio"); return; } // T.38 encoder? if (media && other_media->type_id == MT_AUDIO && proto_is_rtp(other_media->protocol) && flags->t38_force) { media->protocol = &transport_protocols[PROTO_UDPTL]; media->type_id = MT_IMAGE; media->type = call_str_cpy_c("image"); media->format_str = call_str_cpy_c("t38"); return; } // previous T.38 gateway but now stopping? if (media && flags->t38_stop) { if (other_media->type_id == MT_AUDIO && proto_is_rtp(other_media->protocol) && media->type_id == MT_IMAGE && proto_is(media->protocol, PROTO_UDPTL)) __t38_reset(media, other_media); else if (media->type_id == MT_AUDIO && proto_is_rtp(media->protocol) && other_media->type_id == MT_IMAGE && proto_is(other_media->protocol, PROTO_UDPTL)) __t38_reset(media, other_media); // drop through for protocol override } } __attribute__((nonnull(1, 2, 3, 4))) static void codecs_offer(struct call_media *media, struct call_media *other_media, struct stream_params *sp, sdp_ng_flags *flags) { ilogs(codec, LOG_DEBUG, "Updating codecs for offerer " STR_FORMAT " #%u", STR_FMT(&other_media->monologue->tag), other_media->index); if (flags->reuse_codec) codec_store_populate_reuse(&other_media->codecs, &sp->codecs, .codec_set = flags->codec_set); else codec_store_populate(&other_media->codecs, &sp->codecs, .codec_set = flags->codec_set, .allow_asymmetric = !!flags->allow_asymmetric_codecs); codec_store_strip(&other_media->codecs, &flags->codec_ignore, flags->codec_except); codec_store_check_empty(&other_media->codecs, &sp->codecs, flags); codec_store_accept(&other_media->codecs, &flags->codec_accept, NULL); codec_store_accept(&other_media->codecs, &flags->codec_consume, &sp->codecs); codec_store_track(&other_media->codecs, &flags->codec_mask); // we don't update the answerer side if the offer is not RTP but is going // to RTP (i.e. T.38 transcoding) - instead we leave the existing codec list // intact bool update_answerer = true; if (proto_is_rtp(media->protocol) && !proto_is_rtp(other_media->protocol)) update_answerer = false; if (update_answerer) { // update/create answer/receiver side ilogs(codec, LOG_DEBUG, "Updating offer codecs for answerer " STR_FORMAT " #%u", STR_FMT(&media->monologue->tag), media->index); if ((flags->static_codecs) && media->codecs.codec_prefs.length) ilogs(codec, LOG_DEBUG, "Leaving answerer codecs alone"); else if (flags->reuse_codec) codec_store_populate_reuse(&media->codecs, &sp->codecs, .merge_cs = &sp->codecs); else codec_store_populate(&media->codecs, &sp->codecs, .allow_asymmetric = !!(flags->allow_asymmetric_codecs), .merge_cs = &sp->codecs); } codec_store_strip(&media->codecs, &flags->codec_strip, flags->codec_except); codec_store_strip(&media->codecs, &flags->codec_consume, flags->codec_except); codec_store_strip(&media->codecs, &flags->codec_mask, flags->codec_except); codec_store_offer(&media->codecs, &flags->codec_offer, &sp->codecs); codec_store_transcode(&media->codecs, &flags->codec_transcode, &sp->codecs); codec_store_check_empty(&media->codecs, &sp->codecs, flags); codec_store_synthesise(&media->codecs, &other_media->codecs); // update supp codecs based on actions so far codec_tracker_update(&media->codecs, &sp->codecs); // set up handlers codec_handlers_update(media, other_media, .flags = flags, .sp = sp, .allow_asymmetric = !!(flags->allow_asymmetric_codecs)); // updating the handlers may have removed some codecs, so run update the supp codecs again codec_tracker_update(&media->codecs, &sp->codecs); // finally set up handlers again based on final results codec_handlers_update(media, other_media, .flags = flags, .sp = sp, .allow_asymmetric = !!(flags->allow_asymmetric_codecs), .reset_transcoding = true); // keep a copy of the final list of what was offered codec_store_copy(&other_media->offered_codecs, &other_media->codecs); } __attribute__((nonnull(1, 2, 3, 4))) static void codecs_answer(struct call_media *media, struct call_media *other_media, struct stream_params *sp, sdp_ng_flags *flags) { ilogs(codec, LOG_DEBUG, "Updating codecs for answerer " STR_FORMAT " #%u", STR_FMT(&other_media->monologue->tag), other_media->index); bool codec_answer_only = true; // don't do codec answer for a rejected media section if (other_media->streams.length == 0) codec_answer_only = false; else if (sp->rtp_endpoint.port == 0) codec_answer_only = false; if (flags->reuse_codec) codec_store_populate_reuse(&other_media->codecs, &sp->codecs, .codec_set = flags->codec_set, .answer_only = codec_answer_only); else codec_store_populate(&other_media->codecs, &sp->codecs, .codec_set = flags->codec_set, .answer_only = codec_answer_only, .allow_asymmetric = !!flags->allow_asymmetric_codecs); codec_store_strip(&other_media->codecs, &flags->codec_strip, flags->codec_except); codec_store_offer(&other_media->codecs, &flags->codec_offer, &sp->codecs); codec_store_check_empty(&other_media->codecs, &sp->codecs, flags); // restore list of originally offered codecs codec_store_copy(&media->codecs, &media->offered_codecs); // update callee side codec handlers again (second pass after the offer) as we // might need to update some handlers, e.g. when supplemental codecs have been // rejected codec_handlers_update(other_media, media, .allow_asymmetric = !!flags->allow_asymmetric_codecs); // finally set up our caller side codecs ilogs(codec, LOG_DEBUG, "Codec answer for " STR_FORMAT " #%u", STR_FMT(&other_media->monologue->tag), other_media->index); codec_store_answer(&media->codecs, &other_media->codecs, flags, .allow_asymmetric = !!flags->allow_asymmetric_codecs); // set up handlers codec_handlers_update(media, other_media, .flags = flags, .sp = sp, .allow_asymmetric = !!flags->allow_asymmetric_codecs); // updating the handlers may have removed some codecs, so run update the supp codecs again codec_tracker_update(&media->codecs, NULL); codec_tracker_update(&other_media->codecs, NULL); // finally set up handlers again based on final results codec_handlers_update(media, other_media, .flags = flags, .sp = sp, .allow_asymmetric = !!flags->allow_asymmetric_codecs, .reset_transcoding = true); codec_handlers_update(other_media, media, .allow_asymmetric = !!flags->allow_asymmetric_codecs, .reset_transcoding = true); // activate audio player if needed (not done by codec_handlers_update without `flags`) audio_player_activate(media); } void codecs_offer_answer(struct call_media *media, struct call_media *other_media, struct stream_params *sp, sdp_ng_flags *flags) { if (flags->opmode != OP_ANSWER) codecs_offer(media, other_media, sp, flags); else codecs_answer(media, other_media, sp, flags); } /* called with call->master_lock held in W */ __attribute__((nonnull(1))) static void __update_init_subscribers(struct call_media *media, struct stream_params *sp, sdp_ng_flags *flags, enum ng_opmode opmode, unsigned int iter) { if (media->update_iter == iter) return; media->update_iter = iter; recording_setup_media(media); /* should be set on media directly? Currently absent */ if (flags && flags->block_short) ML_SET(media->monologue, BLOCK_SHORT); __ice_start(media); if (!__init_streams(media, sp, flags)) ilog(LOG_WARN, "Error setting stream flags"); /* update all subscribers */ __reset_streams(media); for (__auto_type l = media->media_subscribers.head; l; l = l->next) { struct media_subscription * ms = l->data; struct call_media * sub_media = ms->media; if (!__streams_set_sinks(media, sub_media, flags, &ms->attrs)) ilog(LOG_WARN, "Error initialising streams"); __update_init_subscribers(sub_media, NULL, NULL, opmode, iter); } for (__auto_type l = media->media_subscriptions.head; l; l = l->next) { struct media_subscription * ms = l->data; struct call_media *sub_media = ms->media; __update_init_subscribers(sub_media, NULL, NULL, opmode, iter); } /* we are now ready to fire up ICE if so desired and requested */ ice_update(media->ice_agent, sp, opmode == OP_OFFER); /* sp == NULL: update in case rtcp-mux changed */ if (sp) { // take over and store received ICE candidates ice_candidates_free(&media->ice_candidates); media->ice_candidates = sp->ice_candidates; t_queue_init(&sp->ice_candidates); } recording_setup_media(media); t38_gateway_start(media->t38_gateway, flags ? flags->codec_set : str_case_value_ht_null()); audio_player_start(media); if (mqtt_publish_scope() == MPS_MEDIA) mqtt_timer_start(&media->mqtt_timer, media->call, media); } __attribute__((nonnull(1))) static void update_init_subscribers(struct call_media *media, struct stream_params *sp, sdp_ng_flags *flags, enum ng_opmode opmode) { __update_init_subscribers(media, sp, flags, opmode, ++media->call->update_iter); } /* called with call->master_lock held in W */ void update_init_monologue_subscribers(struct call_monologue *ml, enum ng_opmode opmode) { unsigned int update_iter = ++ml->call->update_iter; for (unsigned int i = 0; i < ml->medias->len; i++) { struct call_media *media = ml->medias->pdata[i]; if (!media) continue; __update_init_subscribers(media, NULL, NULL, opmode, update_iter); } } /* called with call->master_lock held in W */ static void __update_init_medias(const medias_q *medias, enum ng_opmode opmode) { if (!medias->length) return; unsigned int update_iter = ++medias->head->data->call->update_iter; for (auto_iter(l, medias->head); l; l = l->next) __update_init_subscribers(l->data, NULL, NULL, opmode, update_iter); } /* called with call->master_lock held in W */ static void __medias_unconfirm(medias_q *medias, const char *reason) { for (auto_iter(l, medias->head); l; l = l->next) __media_unconfirm(l->data, reason); } __attribute__((nonnull(1, 3))) static void __call_monologue_init_from_flags(struct call_monologue *ml, struct call_monologue *other_ml, sdp_ng_flags *flags) { call_t *call = ml->call; call->last_signal_us = rtpe_now; call->deleted_us = 0; call->media_rec_slots = (flags->media_rec_slots > 0 && call->media_rec_slots == 0) ? flags->media_rec_slots : call->media_rec_slots; // consume session attributes t_queue_clear_full(&ml->generic_attributes, sdp_attr_free); t_queue_clear_full(&ml->all_attributes, sdp_attr_free); ml->generic_attributes = flags->generic_attributes; t_queue_init(&flags->generic_attributes); ml->all_attributes = flags->all_attributes; t_queue_init(&flags->all_attributes); /* set moh flags for future processing */ if (flags->moh_sendrecv) ML_SET(ml, MOH_SENDRECV); if (flags->moh_zero_connection) ML_SET(ml, MOH_ZEROCONN); if (flags->moh_blob.len) ml->moh_blob = call_str_cpy(&flags->moh_blob); if (flags->moh_file.len) ml->moh_file = call_str_cpy(&flags->moh_file); if (flags->moh_db_id > 0) /* only set when defined by flags, must be kept then for future offer/answer exchanges */ ml->moh_db_id = flags->moh_db_id; /* consume sdp session parts */ { /* for cases with origin replacements, keep the very first used origin */ if (other_ml && !other_ml->session_last_sdp_orig && flags->session_sdp_orig.parsed) other_ml->session_last_sdp_orig = sdp_orig_dup(&flags->session_sdp_orig); /* origin (name, version etc.) */ if (flags->session_sdp_orig.parsed) { sdp_orig_free(ml->session_sdp_orig); ml->session_sdp_orig = sdp_orig_dup(&flags->session_sdp_orig); } /* sdp session name */ if (flags->session_sdp_name.len && (!ml->sdp_session_name.len || /* if not set yet */ (ml->sdp_session_name.len && !flags->replace_sess_name))) /* replace_sess_name = do not replace if possible*/ { ml->sdp_session_name = call_str_cpy(&flags->session_sdp_name); } ml->sdp_session_timing = call_str_cpy(&flags->session_timing); /* sdp bandwidth per session level * 0 value is supported (e.g. b=RR:0 and b=RS:0), to be able to disable rtcp */ ml->sdp_session_bandwidth.as = flags->session_bandwidth.as; ml->sdp_session_bandwidth.rr = flags->session_bandwidth.rr; ml->sdp_session_bandwidth.rs = flags->session_bandwidth.rs; ml->sdp_session_bandwidth.ct = flags->session_bandwidth.ct; ml->sdp_session_bandwidth.tias = flags->session_bandwidth.tias; ml->sdp_session_group = call_str_cpy(&flags->session_group); ml->sdp_session_uri = call_str_cpy(&flags->session_uri); ml->sdp_session_email = call_str_cpy(&flags->session_email); ml->sdp_session_phone = call_str_cpy(&flags->session_phone); ml->sdp_session_information = call_str_cpy(&flags->session_information); } // reset offer ipv4/ipv6/mixed media stats if (flags->opmode == OP_OFFER) { statistics_update_ip46_inc_dec(call, CMC_DECREMENT); CALL_CLEAR(call, IPV4_OFFER); CALL_CLEAR(call, IPV6_OFFER); // reset answer ipv4/ipv6/mixed media stats } else if (flags->opmode == OP_ANSWER) { statistics_update_ip46_inc_dec(call, CMC_DECREMENT); CALL_CLEAR(call, IPV4_ANSWER); CALL_CLEAR(call, IPV6_ANSWER); } __tos_change(call, flags); if (flags->label.s) { ml->label = call_str_cpy(&flags->label); t_hash_table_replace(call->labels, &ml->label, ml); } if (flags->recording_vsc) { #define SET_VSC(x,t) \ if (flags->vsc_ ## x ## _rec.len) \ dtmf_trigger_set(ml, DTMF_TRIGGER_ ## t ## _REC, &flags->vsc_ ## x ## _rec, false); \ else \ dtmf_trigger_set(ml, DTMF_TRIGGER_ ## t ## _REC, &rtpe_config.vsc_ ## x ## _rec, false); SET_VSC(start, START) SET_VSC(stop, STOP) SET_VSC(pause, PAUSE) SET_VSC(start_stop, START_STOP) SET_VSC(pause_resume, PAUSE_RESUME) SET_VSC(start_pause_resume, START_PAUSE_RESUME) #undef SET_VSC } #ifdef WITH_TRANSCODING if (flags->recording_announcement) { media_player_opts_t opts = MPO( .repeat = flags->repeat_times, .duration_spent = flags->repeat_duration, .start_pos = flags->start_pos, .block_egress = !!flags->block_egress, .codec_set = flags->codec_set, .file = flags->file, .blob = flags->blob, .db_id = flags->db_id, ); media_player_new(&ml->rec_player, ml, NULL, &opts); if (!media_player_add(ml->rec_player, opts)) ilog(LOG_WARN, "Failed to add media player for recording announcement"); } #endif } __attribute__((nonnull(2, 3))) static void __update_media_label(struct call_media *media, struct call_media *other_media, sdp_ng_flags *flags) { if (!media) return; if (flags->siprec && flags->opmode == OP_SUBSCRIBE_REQ) { if (!media->label.len) { char buf[64]; snprintf(buf, sizeof(buf), "%u", other_media->unique_id); media->label = call_str_cpy_c(buf); } // put same label on both sides if (!other_media->label.len) other_media->label = media->label; } } // `media` can be NULL __attribute__((nonnull(1, 3, 4))) static void __media_init_from_flags(struct call_media *other_media, struct call_media *media, struct stream_params *sp, sdp_ng_flags *flags) { if (flags->opmode == OP_OFFER && flags->reset) { if (media) MEDIA_CLEAR(media, INITIALIZED); MEDIA_CLEAR(other_media, INITIALIZED); if (media && media->ice_agent) ice_restart(media->ice_agent); if (other_media->ice_agent) ice_restart(other_media->ice_agent); } if (flags->generate_rtcp) { if (media) MEDIA_SET(media, RTCP_GEN); MEDIA_SET(other_media, RTCP_GEN); } else if (flags->generate_rtcp_off) { if (media) MEDIA_CLEAR(media, RTCP_GEN); MEDIA_CLEAR(other_media, RTCP_GEN); } switch (flags->media_echo) { case MEO_FWD: if (media) { MEDIA_SET(media, ECHO); MEDIA_CLEAR(media, BLACKHOLE); } MEDIA_SET(other_media, BLACKHOLE); MEDIA_CLEAR(other_media, ECHO); break; case MEO_BKW: if (media) { MEDIA_SET(media, BLACKHOLE); MEDIA_CLEAR(media, ECHO); } MEDIA_SET(other_media, ECHO); MEDIA_CLEAR(other_media, BLACKHOLE); break; case MEO_BOTH: if (media) { MEDIA_SET(media, ECHO); MEDIA_CLEAR(media, BLACKHOLE); } MEDIA_SET(other_media, ECHO); MEDIA_CLEAR(other_media, BLACKHOLE); break; case MEO_BLACKHOLE: if (media) { MEDIA_SET(media, BLACKHOLE); MEDIA_CLEAR(media, ECHO); } MEDIA_SET(other_media, BLACKHOLE); MEDIA_CLEAR(other_media, ECHO); case MEO_DEFAULT: break; } __update_media_label(media, other_media, flags); __update_media_protocol(media, other_media, sp, flags); __update_media_id(media, other_media, sp, flags); __endpoint_loop_protect(sp, other_media); if (sp->rtp_endpoint.port) { /* copy parameters advertised by the sender of this message */ bf_copy_same(&other_media->media_flags, &sp->sp_flags, SHARED_FLAG_RTCP_MUX | SHARED_FLAG_ASYMMETRIC | SHARED_FLAG_UNIDIRECTIONAL | SHARED_FLAG_ICE | SHARED_FLAG_TRICKLE_ICE | SHARED_FLAG_ICE_LITE_PEER | SHARED_FLAG_END_OF_CANDIDATES | SHARED_FLAG_RTCP_FB | SHARED_FLAG_LEGACY_OSRTP | SHARED_FLAG_LEGACY_OSRTP_REV); // duplicate the entire queue of offered crypto params crypto_params_sdes_queue_clear(&other_media->sdes_in); crypto_params_sdes_queue_copy(&other_media->sdes_in, &sp->sdes_params); if (other_media->sdes_in.length) { MEDIA_SET(other_media, SDES); __sdes_accept(other_media, flags); } } if (flags->opmode == OP_OFFER || flags->opmode == OP_ANSWER || flags->opmode == OP_PUBLISH) { /* moved as plain text attributes, required later by sdp_create() * extmap * other (unknown type) */ t_queue_clear_full(&other_media->generic_attributes, sdp_attr_free); t_queue_clear_full(&other_media->all_attributes, sdp_attr_free); other_media->generic_attributes = sp->generic_attributes; t_queue_init(&sp->generic_attributes); other_media->all_attributes = sp->all_attributes; t_queue_init(&sp->all_attributes); } // codec and RTP payload types handling if (sp->ptime > 0) { if (media && !MEDIA_ISSET(media, PTIME_OVERRIDE)) media->ptime = sp->ptime; if (!MEDIA_ISSET(other_media, PTIME_OVERRIDE)) other_media->ptime = sp->ptime; } if (media && sp->maxptime > 0) { media->maxptime = sp->maxptime; } if (media && flags->ptime > 0) { media->ptime = flags->ptime; MEDIA_SET(media, PTIME_OVERRIDE); MEDIA_SET(other_media, PTIME_OVERRIDE); } if (flags->rev_ptime > 0) { other_media->ptime = flags->rev_ptime; if (media) MEDIA_SET(media, PTIME_OVERRIDE); MEDIA_SET(other_media, PTIME_OVERRIDE); } if (str_cmp_str(&other_media->format_str, &sp->format_str)) other_media->format_str = call_str_cpy(&sp->format_str); if (media && str_cmp_str(&media->format_str, &sp->format_str)) { // update opposite side format string only if protocols match if (media->protocol == other_media->protocol) media->format_str = call_str_cpy(&sp->format_str); } /* deduct address family from stream parameters received */ if (!other_media->desired_family || !MEDIA_ISSET(other_media, ICE)) other_media->desired_family = sp->rtp_endpoint.address.family; /* for outgoing SDP, use "direction"/DF or default to what was offered */ if (media && (!media->desired_family || !MEDIA_ISSET(media, ICE))) { if (!media->desired_family) media->desired_family = other_media->desired_family; if (flags->address_family) media->desired_family = flags->address_family; } if (flags->opmode == OP_OFFER) { ilog(LOG_DEBUG, "setting other slot to %u, setting slot to %u", flags->media_rec_slot_offer, flags->media_rec_slot_answer); other_media->media_rec_slot = flags->media_rec_slot_offer; if (media) media->media_rec_slot = flags->media_rec_slot_answer; } /* bandwidth */ other_media->sdp_media_bandwidth = sp->media_session_bandiwdth; other_media->sdp_information = call_str_cpy(&sp->sdp_information); if (flags->recrypt) { MEDIA_SET(other_media, RECRYPT); if (media) MEDIA_SET(media, RECRYPT); } } unsigned int proto_num_ports(unsigned int sp_ports, struct call_media *media, sdp_ng_flags *flags, bool allow_offer_split) { if (sp_ports == 0) return 2; if (sp_ports != 2) return sp_ports; if (!proto_is_rtp(media->protocol)) return sp_ports; if (!MEDIA_ISSET(media, RTCP_MUX)) return sp_ports; if (!flags) return sp_ports; if (flags->opmode == OP_ANSWER || flags->opmode == OP_PUBLISH) return sp_ports / 2; if (flags->opmode == OP_OFFER) { if (allow_offer_split) return sp_ports / 2; return sp_ports; } return sp_ports; } static int __sub_is_transcoding(const struct media_subscription *ms, gconstpointer dummy) { return ms->attrs.transcoding ? 0 : 1; } /** * Set transcoding flag if any media flows are transcoding, otherwise unset it. */ static void media_update_transcoding_flag(struct call_media *media) { if (!media) return; MEDIA_CLEAR(media, TRANSCODING); if (t_queue_find_custom(&media->media_subscribers, NULL, __sub_is_transcoding)) MEDIA_SET(media, TRANSCODING); } /** * For handling sdp media level manipulations (media sessions remove). * This function just adds a fictitious media for this side, pretending it had 0 port. */ static struct call_media * monologue_add_zero_media(struct call_monologue *sender_ml, struct stream_params *sp, unsigned int *num_ports_other, sdp_ng_flags *flags, str_ht tracker) { struct call_media *sender_media = NULL; sp->rtp_endpoint.port = 0; /* pretend it was a zero stream */ sender_media = __get_media(sender_ml, sp, flags, 0, tracker); sender_media->media_sdp_id = sp->media_sdp_id; __media_init_from_flags(sender_media, NULL, sp, flags); *num_ports_other = proto_num_ports(sp->num_ports, sender_media, flags, (flags->rtcp_mux_demux || flags->rtcp_mux_accept) ? true : false); __disable_streams(sender_media, *num_ports_other); __init_interface(sender_media, &sp->direction[0], *num_ports_other); return sender_media; } /* called with call->master_lock held in W */ int monologue_offer_answer(struct call_monologue *monologues[2], sdp_streams_q *streams, sdp_ng_flags *flags) { struct call_media *receiver_media, *sender_media = NULL; struct endpoint_map *em; struct call_monologue *sender_ml = monologues[0]; struct call_monologue *receiver_ml = monologues[1]; unsigned int num_ports_this, num_ports_other; bool is_offer = (flags->opmode == OP_OFFER); unsigned int medias_offset = 0; /* media indexes offset for case with media manipulations */ /* we must have a complete dialogue, even though the to-tag (monologue->tag) * may not be known yet */ if (!sender_ml) { ilog(LOG_ERROR, "Incomplete dialogue association"); return -1; } __call_monologue_init_from_flags(sender_ml, receiver_ml, flags); if (flags->exclude_recording) { ML_SET(receiver_ml, NO_RECORDING); ML_SET(sender_ml, NO_RECORDING); } __C_DBG("this="STR_FORMAT" other="STR_FORMAT, STR_FMT(&receiver_ml->tag), STR_FMT(&sender_ml->tag)); if (flags->opmode == OP_OFFER) ML_CLEAR(receiver_ml, FINAL_RESPONSE); else if (flags->opmode == OP_ANSWER && flags->message_type == SIP_REPLY && flags->code >= 200) ML_SET(sender_ml, FINAL_RESPONSE); else ML_CLEAR(sender_ml, FINAL_RESPONSE); g_auto(str_ht) mid_tracker_sender = str_ht_new(); g_auto(str_ht) mid_tracker_receiver = str_ht_new(); for (__auto_type sp_iter = streams->head; sp_iter; sp_iter = sp_iter->next) { struct stream_params *sp = sp_iter->data; __C_DBG("processing media stream #%u", sp->index); assert(sp->index > 0); /** * for an offer, a sequence in which sender_media->media_subscriptions.head medias are gotten by index, matters. * This affects later the sequencing of medias, e.g. for subscribe requests. */ /* handling of media sessions level manipulations (media sessions remove) */ if (is_offer && flags->sdp_media_remove[sp->type_id]) { sender_media = monologue_add_zero_media(sender_ml, sp, &num_ports_other, flags, mid_tracker_sender); medias_offset++; if (sender_media->logical_intf == NULL) goto error_intf; ilog(LOG_DEBUG, "Media type '"STR_FORMAT"' is to be removed by SDP manipulations.", STR_FMT(&sp->type)); continue; } /* sender's side, get by index */ sender_media = __get_media(sender_ml, sp, flags, 0, mid_tracker_sender); sender_media->media_sdp_id = sp->media_sdp_id; /* receiver's side, try media subscriptions lookup, fall back to index-based lookup */ receiver_media = NULL; for (auto_iter(l, sender_media->media_subscriptions.head); l && !receiver_media; l = l->next) { __auto_type ms = l->data; __auto_type r_media = ms->media; if (r_media->monologue != receiver_ml) continue; /* check type, it must match */ if (str_cmp_str(&r_media->type, &sender_media->type)) continue; /* check a=mid, it must match if present */ if (sender_media->media_id.len && r_media->media_id.len && str_cmp_str(&sender_media->media_id, &r_media->media_id)) continue; /* found it */ receiver_media = r_media; } if (!receiver_media) { ilog(LOG_DEBUG, "No matching media (index: %d) using subscription, just use an index.", sp->index); receiver_media = __get_media(receiver_ml, sp, flags, sp->index - medias_offset, mid_tracker_receiver); } receiver_media->media_sdp_id = sp->media_sdp_id; /* SDP parameters in "sp" are advertised by sender side. * Parameters sent to receiver side may be overridden by * what's in "flags". If this is an answer, or if we have talked to * receiver's side before, then the structs will be populated with * details already. */ /* if medias still not subscribed to each other, do it now */ g_auto(medias_q) old_medias = TYPED_GQUEUE_INIT; __auto_type ms = __subscribe_medias_both_ways(sender_media, receiver_media, is_offer, &old_medias); ms->attrs.transcoding = false; __media_init_from_flags(sender_media, receiver_media, sp, flags); codecs_offer_answer(receiver_media, sender_media, sp, flags); /* send and recv are from our POV */ bf_copy_same(&receiver_media->media_flags, &sp->sp_flags, SP_FLAG_SEND | SP_FLAG_RECV); bf_copy(&sender_media->media_flags, MEDIA_FLAG_RECV, &sp->sp_flags, SP_FLAG_SEND); bf_copy(&sender_media->media_flags, MEDIA_FLAG_SEND, &sp->sp_flags, SP_FLAG_RECV); if (sp->rtp_endpoint.port) { /* DTLS stuff */ __dtls_logic(flags, sender_media, sp); /* control rtcp-mux */ __rtcp_mux_logic(flags, receiver_media, sender_media); /* SDES and DTLS */ __generate_crypto(flags, receiver_media, sender_media); /* set `a=setup:` for the message media type */ if (sender_media->type_id == MT_MESSAGE) { /* not from our POV, but from POV of media sent further to destination */ bf_copy(&receiver_media->media_flags, MEDIA_FLAG_SETUP_ACTIVE, &sp->sp_flags, SP_FLAG_SETUP_ACTIVE); bf_copy(&receiver_media->media_flags, MEDIA_FLAG_SETUP_PASSIVE, &sp->sp_flags, SP_FLAG_SETUP_PASSIVE); } } if (receiver_media->desired_family->af == AF_INET) { if (flags->opmode == OP_OFFER) { CALL_SET(receiver_media->call, IPV4_OFFER); } else if (flags->opmode == OP_ANSWER) { CALL_SET(receiver_media->call, IPV4_ANSWER); } } else if (receiver_media->desired_family->af == AF_INET6) { if (flags->opmode == OP_OFFER) { CALL_SET(receiver_media->call, IPV6_OFFER); } else if (flags->opmode == OP_ANSWER) { CALL_SET(receiver_media->call, IPV6_ANSWER); } } num_ports_this = proto_num_ports(sp->num_ports, receiver_media, flags, flags->rtcp_mux_require ? true : false); num_ports_other = proto_num_ports(sp->num_ports, sender_media, flags, (flags->rtcp_mux_demux || flags->rtcp_mux_accept) ? true : false); /* local interface selection */ __init_interface(receiver_media, &sp->direction[1], num_ports_this); __init_interface(sender_media, &sp->direction[0], num_ports_other); if (receiver_media->logical_intf == NULL || sender_media->logical_intf == NULL) { goto error_intf; } /* ICE stuff - must come after interface and address family selection */ __ice_offer(flags, receiver_media, sender_media, ice_is_restart(sender_media->ice_agent, sp)); /* we now know what's being advertised by the other side */ MEDIA_SET(sender_media, INITIALIZED); if (!sp->rtp_endpoint.port) { /* Zero port: stream has been rejected. * RFC 3264, chapter 6: * If a stream is rejected, the offerer and answerer MUST NOT * generate media (or RTCP packets) for that stream. */ __disable_streams(receiver_media, num_ports_this); __disable_streams(sender_media, num_ports_other); continue; } if (is_addr_unspecified(&sp->rtp_endpoint.address) && !MEDIA_ISSET(sender_media, TRICKLE_ICE)) { /* Zero endpoint address, equivalent to setting the media stream * to sendonly or inactive */ MEDIA_CLEAR(receiver_media, RECV); MEDIA_CLEAR(sender_media, SEND); } /* get that many ports for each side, and one packet stream for each port, then * assign the ports to the streams */ em = __get_endpoint_map(receiver_media, num_ports_this, &sp->rtp_endpoint, flags, false); if (!em) { goto error_ports; } if (flags->disable_jb && receiver_media->call) CALL_SET(receiver_media->call, DISABLE_JB); __num_media_streams(receiver_media, num_ports_this); __assign_stream_fds(receiver_media, &em->intf_sfds); if (__num_media_streams(sender_media, num_ports_other)) { /* new streams created on OTHER side. normally only happens in * initial offer. create a wildcard endpoint_map to be filled in * when the answer comes. */ if (__wildcard_endpoint_map(sender_media, num_ports_other)) goto error_ports; } update_init_subscribers(sender_media, sp, flags, flags->opmode); __update_init_medias(&old_medias, flags->opmode); media_update_transcoding_flag(receiver_media); media_update_transcoding_flag(sender_media); } // set ipv4/ipv6/mixed media stats if (flags->opmode == OP_OFFER || flags->opmode == OP_ANSWER) { statistics_update_ip46_inc_dec(receiver_ml->call, CMC_INCREMENT); } return 0; error_ports: ilog(LOG_ERR, "Error allocating media ports"); return ERROR_NO_FREE_PORTS; error_intf: ilog(LOG_ERR, "Error finding logical interface with free ports"); return ERROR_NO_FREE_LOGS; } void media_subscriptions_clear(subscription_q *q) { t_queue_clear_full(q, media_subscription_free); } static void __unsubscribe_media_link(struct call_media * which, subscription_list * which_cm_link) { struct media_subscription * ms = which_cm_link->data; struct media_subscription * rev_ms = ms->link->data; struct call_media * from = ms->media; ilog(LOG_DEBUG, "Unsubscribing media with monologue tag '" STR_FORMAT_M "' (index: %d) " "from media with monologue tag '" STR_FORMAT_M "' (index: %d)", STR_FMT_M(&which->monologue->tag), which->index, STR_FMT_M(&from->monologue->tag), from->index); t_queue_delete_link(&from->media_subscribers, ms->link); t_queue_delete_link(&which->media_subscriptions, which_cm_link); t_hash_table_remove(which->media_subscriptions_ht, ms->media); t_hash_table_remove(from->media_subscribers_ht, rev_ms->media); g_free(ms); g_free(rev_ms); } /** * Unsubscribe one particular media subscriber from this call media. */ bool __unsubscribe_media(struct call_media * which, struct call_media * from) { if (!t_hash_table_is_set(which->media_subscriptions_ht) || !t_hash_table_is_set(from->media_subscribers_ht)) return true; // can happen during shutdown subscription_list * l = t_hash_table_lookup(which->media_subscriptions_ht, from); if (!l) { ilog(LOG_DEBUG, "Media with monologue tag '" STR_FORMAT_M "' (index: %d) " "is not subscribed to media with monologue tag '" STR_FORMAT_M "' " "(index: %d). Cannot remove this media subscriber.", STR_FMT_M(&which->monologue->tag), which->index, STR_FMT_M(&from->monologue->tag), from->index); return false; } __unsubscribe_media_link(which, l); return true; } /** * Deletes all offer/answer media subscriptions. */ __attribute__((nonnull(1, 2))) static void __unsubscribe_all_offer_answer_medias(struct call_media * cm, medias_q *medias) { for (__auto_type l = cm->media_subscribers.head; l; ) { struct media_subscription * ms = l->data; if (!ms->attrs.offer_answer) { l = l->next; continue; } __auto_type next = l->next; struct call_media * other_cm = ms->media; t_queue_push_tail(medias, other_cm); __unsubscribe_media(other_cm, cm); __unsubscribe_media(cm, other_cm); l = next; } } static void __unsubscribe_medias_from_all(struct call_monologue *ml) { for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type subcription = media->media_subscriptions.head; subcription; ) { __auto_type next = subcription->next; __unsubscribe_media_link(media, subcription); subcription = next; } } } /** * Check whether this monologue medias are subscribed to a single other monologue medias. */ struct call_monologue * ml_medias_subscribed_to_single_ml(struct call_monologue *ml) { /* detect monologues multiplicity */ struct call_monologue * return_ml = NULL; for (unsigned int i = 0; i < ml->medias->len; i++) { struct call_media *media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type l = media->media_subscriptions.head; l; l = l->next) { struct media_subscription * ms = l->data; if (!return_ml) return_ml = ms->monologue; else if (ms->monologue != return_ml) return NULL; } } return return_ml; } struct media_subscription *__add_media_subscription(struct call_media * which, struct call_media * to, const struct sink_attrs *attrs) { subscription_list *ret; if ((ret = t_hash_table_lookup(which->media_subscriptions_ht, to))) { ilog(LOG_DEBUG, "Media with monologue tag '" STR_FORMAT_M "' (index: %d) is already subscribed" " to media with monologue tag '" STR_FORMAT_M "' (index: %d)", STR_FMT_M(&which->monologue->tag), which->index, STR_FMT_M(&to->monologue->tag), to->index); return ret->data; } ilog(LOG_DEBUG, "Subscribing media with monologue tag '" STR_FORMAT_M "' (index: %d) " "to media with monologue tag '" STR_FORMAT_M "' (index: %d)", STR_FMT_M(&which->monologue->tag), which->index, STR_FMT_M(&to->monologue->tag), to->index); struct media_subscription *which_ms = g_new0(__typeof(*which_ms), 1); struct media_subscription *to_rev_ms = g_new0(__typeof(*to_rev_ms), 1); which_ms->media = to; to_rev_ms->media = which; which_ms->monologue = to->monologue; to_rev_ms->monologue = which->monologue; /* preserve attributes if they were present previously */ if (attrs) { which_ms->attrs = * attrs; to_rev_ms->attrs = * attrs; } /* keep offer-answer subscriptions first in the list */ if (!attrs || !attrs->offer_answer) { t_queue_push_tail(&which->media_subscriptions, which_ms); t_queue_push_tail(&to->media_subscribers, to_rev_ms); which_ms->link = to->media_subscribers.tail; to_rev_ms->link = which->media_subscriptions.tail; } else { t_queue_push_head(&which->media_subscriptions, which_ms); t_queue_push_head(&to->media_subscribers, to_rev_ms); which_ms->link = to->media_subscribers.head; to_rev_ms->link = which->media_subscriptions.head; } t_hash_table_insert(which->media_subscriptions_ht, to, to_rev_ms->link); t_hash_table_insert(to->media_subscribers_ht, which, which_ms->link); return to_rev_ms; } /** * Subscribe medias to each other. * Returns B's subscription to A, i.e. the same as * call_get_media_subscription(B->media_subscribers_ht, A) would return. */ static struct media_subscription *__subscribe_medias_both_ways(struct call_media * a, struct call_media * b, bool is_offer, medias_q *medias) { /* retrieve previous subscriptions to retain attributes */ struct media_subscription *a_ms = call_get_media_subscription(a->media_subscriptions_ht, b); struct media_subscription *b_ms = call_get_media_subscription(b->media_subscriptions_ht, a); /* copy out attributes */ struct sink_attrs a_attrs = {0,}; struct sink_attrs b_attrs = {0,}; if (a_ms) a_attrs = a_ms->attrs; if (b_ms) b_attrs = b_ms->attrs; /* override/reset some attributes */ a_attrs.offer_answer = b_attrs.offer_answer = true; a_attrs.egress = b_attrs.egress = false; a_attrs.rtcp_only = b_attrs.rtcp_only = false; /* Release existing subscriptions both ways. * But leave those for SDP offer, if there are any, * because can be a branched offer. */ if (!is_offer) __unsubscribe_all_offer_answer_medias(a, medias); __unsubscribe_all_offer_answer_medias(b, medias); /* (re)create, preserving existing attributes if there have been any */ __add_media_subscription(b, a, &b_attrs); return __add_media_subscription(a, b, &a_attrs); } /** * Retrieve exsisting media subscriptions for a call monologue. * Checks if given media is in subscriptions/subscribers HT of opposite media. */ struct media_subscription *call_get_media_subscription(subscription_ht ht, struct call_media * cm) { subscription_list *l = t_hash_table_lookup(ht, cm); if (!l) return NULL; return l->data; } /** * Retrieve top most media subscription of given media. */ struct media_subscription *call_media_get_top_ms(struct call_media * cm) { if (cm->media_subscriptions.head) return cm->media_subscriptions.head->data; return NULL; } /** * Retrieve top most media subscription of top media for a given call monologue. * It's useful for offer/answer model cases, * where most of cases single-to-single subscription model is used. */ struct media_subscription *call_ml_get_top_ms(struct call_monologue *ml) { for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media) continue; __auto_type subcription = media->media_subscriptions.head; if (subcription) return subcription->data; } return NULL; } /** * Checks if any present audio medias are sendonly/inactive. * Should only be used when medias are already initialized with flags. */ bool call_ml_sendonly_inactive(struct call_monologue *ml) { for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media || media->type_id != MT_AUDIO) continue; /* sendonly media for rtpengine means: receive from this media, but don't send to it * sendonly: !MEDIA_ISSET(media, SEND) && MEDIA_ISSET(media, RECV) * inactive: !MEDIA_ISSET(media, SEND) && !MEDIA_ISSET(media, RECV) */ if (!MEDIA_ISSET(media, SEND)) { if (!MEDIA_ISSET(media, RECV)) ilog(LOG_DEBUG, "Coming SDP offer puts on hold using inactive type."); else ilog(LOG_DEBUG, "Coming SDP offer puts on hold using sendonly type."); return true; } } return false; } /* called with call->master_lock held in W */ __attribute__((nonnull(1, 2, 3))) int monologue_publish(struct call_monologue *ml, sdp_streams_q *streams, sdp_ng_flags *flags) { __call_monologue_init_from_flags(ml, NULL, flags); if (flags->exclude_recording) ML_SET(ml, NO_RECORDING); g_auto(str_ht) mid_tracker = str_ht_new(); for (__auto_type l = streams->head; l; l = l->next) { struct stream_params *sp = l->data; struct call_media *media = __get_media(ml, sp, flags, 0, mid_tracker); __media_init_from_flags(media, NULL, sp, flags); codec_store_populate(&media->codecs, &sp->codecs, .allow_asymmetric = !!flags->allow_asymmetric_codecs); if (codec_store_accept_one(&media->codecs, &flags->codec_accept, !!flags->accept_any)) return -1; // the most we can do is receive bf_copy(&media->media_flags, MEDIA_FLAG_RECV, &sp->sp_flags, SP_FLAG_SEND); if (sp->rtp_endpoint.port) { __dtls_logic(flags, media, sp); __generate_crypto(flags, media, NULL); } unsigned int num_ports = proto_num_ports(sp->num_ports, media, flags, true); /* local interface selection */ __init_interface(media, &flags->interface, num_ports); if (media->logical_intf == NULL) return -1; // XXX return error code /* ICE stuff - must come after interface and address family selection */ __ice_offer(flags, media, media, ice_is_restart(media->ice_agent, sp)); MEDIA_SET(media, INITIALIZED); if (!sp->rtp_endpoint.port) { /* Zero port: stream has been rejected. * RFC 3264, chapter 6: * If a stream is rejected, the offerer and answerer MUST NOT * generate media (or RTCP packets) for that stream. */ __disable_streams(media, num_ports); continue; } struct endpoint_map *em = __get_endpoint_map(media, num_ports, NULL, flags, true); if (!em) return -1; // XXX error - no ports __num_media_streams(media, num_ports); __assign_stream_fds(media, &em->intf_sfds); // XXX this should be covered by __update_init_subscribers ? if (!__init_streams(media, sp, flags)) return -1; __ice_start(media); ice_update(media->ice_agent, sp, false); } return 0; } /* called with call->master_lock held in W */ __attribute__((nonnull(1, 2, 3, 4))) static int monologue_subscribe_request1(struct call_monologue *src_ml, struct call_monologue *dst_ml, sdp_ng_flags *flags, unsigned int *index) { unsigned int idx_diff = 0, rev_idx_diff = 0; g_auto(str_ht) mid_tracker_dst = str_ht_new(); g_auto(str_ht) mid_tracker_src = str_ht_new(); for (__auto_type l = src_ml->last_in_sdp_streams.head; l; l = l->next) { struct stream_params *sp = l->data; struct call_media *dst_media = __get_media(dst_ml, sp, flags, (*index)++, mid_tracker_dst); struct call_media *src_media = __get_media(src_ml, sp, flags, 0, mid_tracker_src); /* subscribe dst_ml (subscriber) to src_ml, don't forget to carry the egress flag, if required */ __add_media_subscription(dst_media, src_media, &(struct sink_attrs) { .egress = !!flags->egress }); /* mirroring, so vice-versa: src_media gets subscribed to dst_media (subscriber) */ if (flags->rtcp_mirror) __add_media_subscription(src_media, dst_media, &(struct sink_attrs) { .egress = !!flags->egress, .rtcp_only = true }); // track media index difference if one ml is subscribed to multiple other mls if (idx_diff == 0 && dst_media->index > src_media->index) idx_diff = dst_media->index - src_media->index; if (rev_idx_diff == 0 && src_media->index > dst_media->index) rev_idx_diff = src_media->index - dst_media->index; __media_init_from_flags(src_media, dst_media, sp, flags); codec_store_populate(&dst_media->codecs, &src_media->codecs, .allow_asymmetric = !!flags->allow_asymmetric_codecs); codec_store_strip(&dst_media->codecs, &flags->codec_strip, flags->codec_except); codec_store_strip(&dst_media->codecs, &flags->codec_consume, flags->codec_except); codec_store_strip(&dst_media->codecs, &flags->codec_mask, flags->codec_except); codec_store_offer(&dst_media->codecs, &flags->codec_offer, &sp->codecs); codec_store_transcode(&dst_media->codecs, &flags->codec_transcode, &sp->codecs); codec_store_synthesise(&dst_media->codecs, &src_media->codecs); codec_handlers_update(dst_media, src_media, .flags = flags, .sp = sp, .allow_asymmetric = !!flags->allow_asymmetric_codecs); if (!flags->inactive) bf_copy(&dst_media->media_flags, MEDIA_FLAG_SEND, &src_media->media_flags, SP_FLAG_RECV); else MEDIA_CLEAR(dst_media, SEND); MEDIA_CLEAR(dst_media, RECV); __rtcp_mux_set(flags, dst_media); __generate_crypto(flags, dst_media, src_media); unsigned int num_ports = proto_num_ports(sp->num_ports, dst_media, flags, false); // interface selection __init_interface(dst_media, &flags->interface, num_ports); if (dst_media->logical_intf == NULL) return -1; // XXX return error code __ice_offer(flags, dst_media, src_media, ice_is_restart(src_media->ice_agent, sp)); struct endpoint_map *em = __get_endpoint_map(dst_media, num_ports, NULL, flags, true); if (!em) return -1; // XXX error - no ports __num_media_streams(dst_media, num_ports); __assign_stream_fds(dst_media, &em->intf_sfds); if (!__init_streams(dst_media, NULL, flags)) return -1; update_init_subscribers(src_media, NULL, NULL, flags->opmode); } return 0; } /* called with call->master_lock held in W */ __attribute__((nonnull(1, 2, 3))) int monologue_subscribe_request(const subscription_q *srms, struct call_monologue *dst_ml, sdp_ng_flags *flags) { unsigned int index = 1; /* running counter for output/dst medias */ __unsubscribe_medias_from_all(dst_ml); __call_monologue_init_from_flags(dst_ml, NULL, flags); g_auto(GQueue) mls = G_QUEUE_INIT; /* to avoid duplications */ for (auto_iter(sl, srms->head); sl; sl = sl->next) { struct media_subscription *ms = sl->data; struct call_monologue *src_ml = ms->monologue; if (!src_ml) continue; if (!g_queue_find(&mls, src_ml)) { int ret = monologue_subscribe_request1(src_ml, dst_ml, flags, &index); g_queue_push_tail(&mls, src_ml); if (ret) return -1; } /* update last used origin: copy from source to the dest monologue */ if (src_ml && src_ml->session_last_sdp_orig && !dst_ml->session_last_sdp_orig) dst_ml->session_last_sdp_orig = sdp_orig_dup(src_ml->session_last_sdp_orig); } return 0; } /* called with call->master_lock held in W */ __attribute__((nonnull(1, 2, 3))) int monologue_subscribe_answer(struct call_monologue *dst_ml, sdp_ng_flags *flags, sdp_streams_q *streams) { struct media_subscription *rev_ms = NULL; g_auto(str_ht) mid_tracker = str_ht_new(); for (__auto_type l = streams->head; l; l = l->next) { struct stream_params * sp = l->data; struct call_media * dst_media = __get_media(dst_ml, sp, flags, 0, mid_tracker); if (!dst_media) continue; /* set src_media based on subscription (assuming it is one-to-one) * TODO: this should probably be reworked to support one-to-multi subscriptions. */ __auto_type src_ml_media_it = dst_media->media_subscriptions.head; struct media_subscription * ms = src_ml_media_it->data; struct call_media * src_media = ms->media; rev_ms = call_get_media_subscription(src_media->media_subscribers_ht, dst_media); if (rev_ms) rev_ms->attrs.transcoding = false; __media_init_from_flags(dst_media, NULL, sp, flags); if (flags->allow_transcoding) { codec_store_populate(&dst_media->codecs, &sp->codecs, .codec_set = flags->codec_set, .answer_only = true, .allow_asymmetric = !!flags->allow_asymmetric_codecs); codec_store_strip(&dst_media->codecs, &flags->codec_strip, flags->codec_except); codec_store_offer(&dst_media->codecs, &flags->codec_offer, &sp->codecs); } else { codec_store_populate(&dst_media->codecs, &sp->codecs, .answer_only = true, .allow_asymmetric = !!flags->allow_asymmetric_codecs); if (!codec_store_is_full_answer(&src_media->codecs, &dst_media->codecs)) return -1; } codec_handlers_update(src_media, dst_media, .flags = flags, .allow_asymmetric = !!flags->allow_asymmetric_codecs); codec_handlers_update(dst_media, src_media, .flags = flags, .sp = sp, .allow_asymmetric = !!flags->allow_asymmetric_codecs, .reset_transcoding = true); __dtls_logic(flags, dst_media, sp); if (!__init_streams(dst_media, sp, flags)) return -1; MEDIA_CLEAR(dst_media, RECV); bf_copy(&dst_media->media_flags, MEDIA_FLAG_SEND, &sp->sp_flags, SP_FLAG_RECV); /* TODO: check answer SDP parameters */ MEDIA_SET(dst_media, INITIALIZED); update_init_subscribers(dst_media, sp, flags, flags->opmode); __media_unconfirm(dst_media, "subscribe answer event"); } /* TODO: move inside the cycle above, to reduce iterations amount */ g_auto(GQueue) mls = G_QUEUE_INIT; /* to avoid duplications */ for (int i = 0; i < dst_ml->medias->len; i++) { struct call_media * dst_media = dst_ml->medias->pdata[i]; if (!dst_media) continue; /* TODO: probably we should take care about subscribers as well? */ for (__auto_type sub = dst_media->media_subscriptions.head; sub; sub = sub->next) { struct media_subscription * ms = sub->data; if (!g_queue_find(&mls, ms->monologue)) { media_update_transcoding_flag(ms->media); update_init_subscribers(ms->media, NULL, NULL, flags->opmode); __media_unconfirm(ms->media, "subscribe answer event"); g_queue_push_tail(&mls, ms->monologue); } } } return 0; } /* called with call->master_lock held in W */ __attribute__((nonnull(1, 2))) int monologue_unsubscribe(struct call_monologue *dst_ml, sdp_ng_flags *flags) { for (unsigned int i = 0; i < dst_ml->medias->len; i++) { struct call_media *media = dst_ml->medias->pdata[i]; if (!media) continue; __media_unconfirm(media, "media unsubscribe"); /* TODO: should we care about subscribers as well? */ for (__auto_type l = media->media_subscriptions.head; l; ) { __auto_type next = l->next; struct media_subscription * ms = l->data; struct call_media * src_media = ms->media; __media_unconfirm(src_media, "media unsubscribe"); __unsubscribe_media_link(media, l); update_init_subscribers(src_media, NULL, NULL, flags->opmode); l = next; } update_init_subscribers(media, NULL, NULL, flags->opmode); } return 0; } __attribute__((nonnull(1, 2, 3))) void dialogue_connect(struct call_monologue *src_ml, struct call_monologue *dst_ml, sdp_ng_flags *flags) { // for each source media, find a usable destination media for (unsigned int i = 0; i < src_ml->medias->len; i++) { __auto_type src_media = src_ml->medias->pdata[i]; if (!src_media) continue; struct call_media *dst_media = NULL; // try a=mid first if there is one if (src_media->media_id.len) { dst_media = t_hash_table_lookup(dst_ml->media_ids, &src_media->media_id); // type must still match if (str_cmp_str(&dst_media->type, &src_media->type)) dst_media = NULL; } // otherwise try by index if (!dst_media) { for (unsigned int j = 0; j < dst_ml->medias->len; j++) { unsigned int dx = (j + i) % dst_ml->medias->len; dst_media = dst_ml->medias->pdata[dx]; if (!dst_media) continue; // if type matches, we can connect if (!str_cmp_str(&dst_media->type, &src_media->type)) break; dst_media = NULL; } } // anything found? if (!dst_media) { ilog(LOG_WARN, "Unable to find usable media (type '" STR_FORMAT "') to connect call", STR_FMT(&src_media->type)); continue; } __media_unconfirm(src_media, "connect"); __media_unconfirm(dst_media, "connect"); g_auto(medias_q) medias = TYPED_GQUEUE_INIT; __subscribe_medias_both_ways(src_media, dst_media, false, &medias); __medias_unconfirm(&medias, "connect"); codec_handlers_update(src_media, dst_media, .allow_asymmetric = !!flags->allow_asymmetric_codecs); codec_handlers_update(dst_media, src_media, .allow_asymmetric = !!flags->allow_asymmetric_codecs); update_init_subscribers(src_media, NULL, NULL, flags->opmode); __update_init_medias(&medias, flags->opmode); } } static int __rtp_stats_sort(const struct rtp_stats *a, const struct rtp_stats *b) { /* descending order */ if (atomic64_get(&a->packets) > atomic64_get(&b->packets)) return -1; if (atomic64_get(&a->packets) < atomic64_get(&b->packets)) return 1; return 0; } const rtp_payload_type *__rtp_stats_codec(struct call_media *m) { struct packet_stream *ps; const rtp_payload_type *rtp_pt = NULL; /* we only use the primary packet stream for the time being */ if (!m->streams.head) return NULL; ps = m->streams.head->data; rtp_stats_ht_iter iter; t_hash_table_iter_init(&iter, ps->rtp_stats); struct rtp_stats *rs, *top = NULL; while (t_hash_table_iter_next(&iter, NULL, &rs)) { if (!top || __rtp_stats_sort(rs, top) < 0) top = rs; } if (!top) return NULL; /* payload type with the most packets */ if (atomic64_get(&top->packets) == 0) goto out; rtp_pt = get_rtp_payload_type(top->payload_type, &m->codecs); out: return rtp_pt; /* may be NULL */ } void add_total_calls_duration_in_interval(int64_t interval_tv) { int64_t ongoing_calls_dur = add_ongoing_calls_dur_in_interval( rtpe_latest_graphite_interval_start, interval_tv); RTPE_STATS_ADD(total_calls_duration_intv, ongoing_calls_dur); } static int64_t add_ongoing_calls_dur_in_interval(int64_t interval_start, int64_t interval_duration) { int64_t call_duration, res = 0; struct call_monologue *ml; ITERATE_CALL_LIST_START(CALL_ITERATOR_GRAPHITE, call); if (!call->monologues.head || IS_FOREIGN_CALL(call)) goto next; ml = call->monologues.head->data; if (interval_start > ml->started) { res += interval_duration; } else { call_duration = rtpe_now - ml->started; res += call_duration; } next: ; ITERATE_CALL_LIST_NEXT_END(call); return res; } static void __call_cleanup(call_t *c) { for (__auto_type l = c->streams.head; l; l = l->next) { struct packet_stream *ps = l->data; send_timer_put(&ps->send_timer); jb_put(&ps->jb); __unkernelize(ps, "final call cleanup"); dtls_shutdown(ps); ps->selected_sfd = NULL; t_queue_clear(&ps->sfds); crypto_cleanup(&ps->crypto); mutex_destroy(&ps->lock); t_queue_clear_full(&ps->rtp_sinks, free_sink_handler); t_queue_clear_full(&ps->rtcp_sinks, free_sink_handler); t_queue_clear_full(&ps->rtp_mirrors, free_sink_handler); } for (__auto_type l = c->medias.head; l; l = l->next) { struct call_media *md = l->data; ice_shutdown(&md->ice_agent); media_stop(md); t38_gateway_put(&md->t38_gateway); audio_player_free(md); mutex_destroy(&md->dtmf_lock); } for (__auto_type l = c->monologues.head; l; l = l->next) { struct call_monologue *ml = l->data; __monologue_stop(ml); media_player_put(&ml->player); media_player_put(&ml->rec_player); if (ml->tone_freqs) g_array_free(ml->tone_freqs, true); obj_release_o(ml->janus_session); } while (c->stream_fds.head) { stream_fd *sfd = t_queue_pop_head(&c->stream_fds); stream_fd_release(sfd); obj_release(sfd); } recording_finish(c, false); rwlock_destroy(&c->master_lock); } // rtpe_callhash_lock must be held // returns true if call ID was removed static bool __remove_call_id_from_hash(str *callid, call_t *c) { call_t *call_ht = NULL; t_hash_table_steal_extended(rtpe_callhash, callid, NULL, &call_ht); if (!call_ht) return false; if (call_ht == c) return true; t_hash_table_insert(rtpe_callhash, &call_ht->callid, call_ht); return false; } /* called lock-free, but must hold a reference to the call */ void call_destroy(call_t *c) { struct packet_stream *ps=0; struct call_monologue *ml; struct call_media *md; GList *k; const rtp_payload_type *rtp_pt; if (!c) { return; } rwlock_lock_w(&rtpe_callhash_lock); bool removed = __remove_call_id_from_hash(&c->callid, c); for (auto_iter(l, c->callid_aliases.head); l; l = l->next) { __auto_type alias = l->data; if (__remove_call_id_from_hash(alias, c)) obj_put(c); } rwlock_unlock_w(&rtpe_callhash_lock); // if call not found in callhash => previously deleted if (!removed) return; RTPE_GAUGE_DEC(total_sessions); obj_put(c); statistics_update_ip46_inc_dec(c, CMC_DECREMENT); statistics_update_foreignown_dec(c); if (c->redis_hosted_db >= 0) redis_delete(c, rtpe_redis_write); __call_iterator_remove(c); rwlock_lock_w(&c->master_lock); /* at this point, no more packet streams can be added */ mqtt_timer_stop(&c->mqtt_timer); if (!IS_OWN_CALL(c)) goto no_stats_output; ///// stats output ilog(LOG_INFO, "Final packet stats:"); for (__auto_type l = c->monologues.head; l; l = l->next) { ml = l->data; // stats output only - no cleanups ilog(LOG_INFO, "--- Tag '" STR_FORMAT_M "'%s" STR_FORMAT "%s, created " "%u:%02u ago for branch '" STR_FORMAT_M "'", STR_FMT_M(&ml->tag), ml->label.s ? " (label '" : "", STR_FMT(ml->label.s ? &ml->label : &STR_EMPTY), ml->label.s ? "')" : "", (unsigned int) ((rtpe_now - ml->created_us) / 1000000LL) / 60, (unsigned int) ((rtpe_now - ml->created_us) / 1000000LL) % 60, STR_FMT_M(&ml->viabranch)); for (__auto_type alias = ml->tag_aliases.head; alias; alias = alias->next) ilog(LOG_INFO, "--- Alias: '" STR_FORMAT "'", STR_FMT(alias->data)); for (unsigned int m = 0; m < ml->medias->len; m++) { md = ml->medias->pdata[m]; if (!md) continue; for (__auto_type ll = md->media_subscriptions.head; ll; ll = ll->next) { struct media_subscription * ms = ll->data; ilog(LOG_INFO, "--- subscribed to media with monologue tag '" STR_FORMAT_M "' (index: %d)", STR_FMT_M(&ms->monologue->tag), ms->media->index); } for (__auto_type ll = md->media_subscribers.head; ll; ll = ll->next) { struct media_subscription * ms = ll->data; ilog(LOG_INFO, "--- subscription for media with monologue tag '" STR_FORMAT_M "' (index: %d)", STR_FMT_M(&ms->monologue->tag), ms->media->index); } // stats output only - no cleanups #define MLL_PREFIX "------ Media #%u ("STR_FORMAT" over %s) using " /* media log line prefix */ #define MLL_COMMON /* common args */ \ md->index, \ STR_FMT(&md->type), \ md->protocol ? md->protocol->name : "(unknown)" if (proto_is_rtp(md->protocol)) { rtp_pt = __rtp_stats_codec(md); if (!rtp_pt) ilog(LOG_INFO, MLL_PREFIX "unknown codec", MLL_COMMON); else ilog(LOG_INFO, MLL_PREFIX STR_FORMAT, MLL_COMMON, STR_FMT(&rtp_pt->encoding_with_params)); } else { ilog(LOG_INFO, MLL_PREFIX STR_FORMAT, MLL_COMMON, STR_FMT(&md->format_str)); } for (__auto_type o = md->streams.head; o; o = o->next) { ps = o->data; // stats output only - no cleanups if (PS_ISSET(ps, FALLBACK_RTCP)) continue; char *addr = sockaddr_print_buf(&ps->endpoint.address); endpoint_t *local_endpoint = packet_stream_local_addr(ps); char *local_addr = sockaddr_print_buf(&local_endpoint->address); struct ssrc_entry_call *se = call_get_first_ssrc(&ps->media->ssrc_hash_in); ilog(LOG_INFO, "--------- Port %15s:%-5u <> %s%15s:%-5u%s%s, SSRC %s%" PRIx32 "%s, in " "%" PRIu64 " p, %" PRIu64 " b, %" PRIu64 " e, %" PRIu64 " ts, " "out %" PRIu64 " p, %" PRIu64 " b, %" PRIu64 " e", local_addr, (unsigned int) local_endpoint->port, FMT_M(addr, ps->endpoint.port), (!PS_ISSET(ps, RTP) && PS_ISSET(ps, RTCP)) ? " (RTCP)" : "", FMT_M(se ? se->h.ssrc : 0), atomic64_get_na(&ps->stats_in->packets), atomic64_get_na(&ps->stats_in->bytes), atomic64_get_na(&ps->stats_in->errors), (rtpe_now - packet_stream_last_packet(ps)) / 1000000L, atomic64_get_na(&ps->stats_out->packets), atomic64_get_na(&ps->stats_out->bytes), atomic64_get_na(&ps->stats_out->errors)); } for (k = md->ssrc_hash_in.nq.head; k; k = k->next) { struct ssrc_entry_call *se = k->data; // stats output only - no cleanups if (!se->stats_blocks.length || !se->lowest_mos || !se->highest_mos) continue; int mos_samples = (se->stats_blocks.length - se->no_mos_count); if (mos_samples < 1) mos_samples = 1; ilog(LOG_INFO, "--- SSRC %s%" PRIx32 "%s", FMT_M(se->h.ssrc)); ilog(LOG_INFO, "------ Average MOS %" PRIu64 ".%" PRIu64 ", " "lowest MOS %" PRIu64 ".%" PRIu64 " (at %" PRId64 ":%02" PRId64 "), " "highest MOS %" PRIu64 ".%" PRIu64 " (at %" PRId64 ":%02" PRId64 ") lost:%u", se->average_mos.mos / mos_samples / 10, se->average_mos.mos / mos_samples % 10, se->lowest_mos->mos / 10, se->lowest_mos->mos % 10, ((se->lowest_mos->reported - c->created) / 1000000L) / 60, ((se->lowest_mos->reported - c->created) / 1000000L) % 60, se->highest_mos->mos / 10, se->highest_mos->mos % 10, ((se->highest_mos->reported - c->created) / 1000000L) / 60, ((se->highest_mos->reported - c->created) / 1000000L) % 60, (unsigned int) se->packets_lost); ilog(LOG_INFO, "------ respective (avg/min/max) jitter %" PRIu64 "/%" PRIu64 "/%" PRIu64 " ms, " "RTT-e2e %" PRIu64 ".%" PRIu64 "/%" PRIu64 ".%" PRIu64 "/%" PRIu64 ".%" PRIu64 " ms, " "RTT-dsct %" PRIu32 ".%" PRIu32 "/%" PRIu32 ".%" PRIu32 "/%" PRIu32 ".%" PRIu32 " ms, " "packet loss %" PRIu64 "/%" PRIu64 "/%" PRIu64 "%%", se->average_mos.jitter / mos_samples, se->lowest_mos->jitter, se->highest_mos->jitter, se->average_mos.rtt / mos_samples / 1000, (se->average_mos.rtt / mos_samples / 100) % 10, se->lowest_mos->rtt / 1000, (se->lowest_mos->rtt / 100) % 10, se->highest_mos->rtt / 1000, (se->highest_mos->rtt / 100) % 10, se->average_mos.rtt_leg / mos_samples / 1000, (se->average_mos.rtt_leg / mos_samples / 100) % 10, se->lowest_mos->rtt_leg / 1000, (se->lowest_mos->rtt_leg / 100) % 10, se->highest_mos->rtt_leg / 1000, (se->highest_mos->rtt_leg / 100) % 10, se->average_mos.packetloss / mos_samples, se->lowest_mos->packetloss, se->highest_mos->packetloss); } } } no_stats_output: // cleanups statistics_update_oneway(c); cdr_update_entry(c); __call_cleanup(c); rwlock_unlock_w(&c->master_lock); } int call_stream_address(GString *s, struct packet_stream *ps, enum stream_address_format format, const struct local_intf *ifa, bool keep_unspec) { const struct intf_address *ifa_addr; if (!ifa) { if (ps->selected_sfd) ifa = ps->selected_sfd->local_intf; else ifa = get_any_interface_address(ps->media->logical_intf, ps->media->desired_family); } ifa_addr = &ifa->spec->local_address; if (format == SAF_NG) { g_string_append(s, ifa_addr->addr.family->rfc_name); g_string_append_c(s, ' '); } if (PS_ISSET(ps, ZERO_ADDR) && keep_unspec) g_string_append(s, ifa_addr->addr.family->unspec_string); else sockaddr_print_gstring(s, &ifa->advertised_address.addr); return ifa_addr->addr.family->af; } void media_subscription_free(struct media_subscription *p) { g_free(p); } void call_media_free(struct call_media **mdp) { struct call_media *md = *mdp; crypto_params_sdes_queue_clear(&md->sdes_in); crypto_params_sdes_queue_clear(&md->sdes_out); t_queue_clear(&md->streams); t_queue_clear(&md->endpoint_maps); codec_store_cleanup(&md->codecs); codec_store_cleanup(&md->offered_codecs); t_queue_clear_full(&md->generic_attributes, sdp_attr_free); t_queue_clear_full(&md->all_attributes, sdp_attr_free); t_queue_clear_full(&md->dtmf_recv, dtmf_event_free); t_queue_clear_full(&md->dtmf_send, dtmf_event_free); t_hash_table_destroy_ptr(&md->media_subscribers_ht); t_hash_table_destroy_ptr(&md->media_subscriptions_ht); t_queue_clear_full(&md->media_subscribers, media_subscription_free); t_queue_clear_full(&md->media_subscriptions, media_subscription_free); codec_handlers_free(md); codec_handler_free(&md->t38_handler); t38_gateway_put(&md->t38_gateway); ice_candidates_free(&md->ice_candidates); mutex_destroy(&md->dtmf_lock); ssrc_hash_destroy(&md->ssrc_hash_in); ssrc_hash_destroy(&md->ssrc_hash_out); g_free(md); *mdp = NULL; } void __monologue_free(struct call_monologue *m) { t_ptr_array_free(m->medias, true); g_hash_table_destroy(m->associated_tags); t_hash_table_destroy(m->media_ids); if (m->last_out_sdp) g_string_free(m->last_out_sdp, TRUE); sdp_orig_free(m->session_sdp_orig); sdp_orig_free(m->session_last_sdp_orig); t_queue_clear_full(&m->generic_attributes, sdp_attr_free); t_queue_clear_full(&m->all_attributes, sdp_attr_free); t_queue_clear(&m->tag_aliases); sdp_streams_clear(&m->last_in_sdp_streams); g_free(m); } static void __call_free(call_t *c) { struct call_monologue *m; struct call_media *md; struct packet_stream *ps; struct endpoint_map *em; //ilog(LOG_DEBUG, "freeing main call struct"); obj_release(c->dtls_cert); mqtt_timer_stop(&c->mqtt_timer); while (c->monologues.head) { m = t_queue_pop_head(&c->monologues); __monologue_free(m); } while (c->medias.head) { md = t_queue_pop_head(&c->medias); call_media_free(&md); } while (c->endpoint_maps.head) { em = t_queue_pop_head(&c->endpoint_maps); t_queue_clear_full(&em->intf_sfds, free_sfd_intf_list); g_free(em); } t_hash_table_destroy(c->tags); t_hash_table_destroy(c->viabranches); t_hash_table_destroy(c->labels); t_queue_clear(&c->callid_aliases); while (c->streams.head) { ps = t_queue_pop_head(&c->streams); crypto_cleanup(&ps->crypto); t_queue_clear(&ps->sfds); t_hash_table_destroy(ps->rtp_stats); bufferpool_unref(ps->stats_in); bufferpool_unref(ps->stats_out); g_free(ps); } memory_arena_free(&c->buffer); ice_fragments_cleanup(c->sdp_fragments, true); t_hash_table_destroy(c->sdp_fragments); rwlock_destroy(&c->master_lock); assert(c->stream_fds.head == NULL); } static call_t *call_create(const str *callid) { call_t *c; ilog(LOG_NOTICE, "Creating new call"); c = obj_alloc0(call_t, __call_free); memory_arena_init(&c->buffer); rwlock_init(&c->master_lock); c->tags = tags_ht_new(); c->viabranches = tags_ht_new(); c->labels = labels_ht_new(); call_memory_arena_set(c); c->callid = call_str_cpy(callid); c->created = rtpe_now; c->dtls_cert = dtls_cert(); c->tos = rtpe_config.default_tos; c->poller = rtpe_get_poller(); c->sdp_fragments = fragments_ht_new(); c->redis_hosted_db = -1; if (rtpe_config.cpu_affinity) c->cpu_affinity = call_socket_cpu_affinity++ % rtpe_config.cpu_affinity; else c->cpu_affinity = -1; for (int i = 0; i < NUM_CALL_ITERATORS; i++) { mutex_init(&c->iterator[i].next_lock); mutex_init(&c->iterator[i].prev_lock); } return c; } /* returns call with master_lock held in W */ call_t *call_get_or_create(const str *callid, bool exclusive) { call_t *c; restart: rwlock_lock_r(&rtpe_callhash_lock); c = t_hash_table_lookup(rtpe_callhash, callid); if (!c) { rwlock_unlock_r(&rtpe_callhash_lock); /* completely new call-id, create call */ c = call_create(callid); rwlock_lock_w(&rtpe_callhash_lock); if (t_hash_table_lookup(rtpe_callhash, callid)) { /* preempted */ rwlock_unlock_w(&rtpe_callhash_lock); obj_release(c); goto restart; } t_hash_table_insert(rtpe_callhash, &c->callid, obj_get(c)); RTPE_GAUGE_INC(total_sessions); rwlock_lock_w(&c->master_lock); rwlock_unlock_w(&rtpe_callhash_lock); for (int i = 0; i < NUM_CALL_ITERATORS; i++) { c->iterator[i].link.data = obj_get(c); call_t *first_call; while (1) { // lock the list mutex_lock(&rtpe_call_iterators[i].lock); // if there is a first entry, lock that first_call = NULL; if (rtpe_call_iterators[i].first) { first_call = rtpe_call_iterators[i].first->data; // coverity[lock_order : FALSE] if (mutex_trylock(&first_call->iterator[i].prev_lock)) { mutex_unlock(&rtpe_call_iterators[i].lock); continue; // retry } } // we can insert now break; } rtpe_call_iterators[i].first = t_list_insert_before_link(rtpe_call_iterators[i].first, rtpe_call_iterators[i].first, &c->iterator[i].link); if (first_call) mutex_unlock(&first_call->iterator[i].prev_lock); mutex_unlock(&rtpe_call_iterators[i].lock); } if (mqtt_publish_scope() == MPS_CALL) mqtt_timer_start(&c->mqtt_timer, c, NULL); } else { if (exclusive) c = NULL; else { obj_hold(c); rwlock_lock_w(&c->master_lock); } rwlock_unlock_r(&rtpe_callhash_lock); } if (c) log_info_call(c); return c; } /** returns call with master_lock held in W, or NULL if not found * * The lookup of a call is performed via its call-ID. * A reference to the call object is returned with * the reference-count increased by one. * * Therefore the code must use obj_put() on the call after call_get() * and after it's done operating on the object. */ call_t *call_get(const str *callid) { call_t *ret; rwlock_lock_r(&rtpe_callhash_lock); ret = t_hash_table_lookup(rtpe_callhash, callid); if (!ret) { rwlock_unlock_r(&rtpe_callhash_lock); return NULL; } rwlock_lock_w(&ret->master_lock); obj_hold(ret); rwlock_unlock_r(&rtpe_callhash_lock); log_info_call(ret); return ret; } // special version of call_get() to get two calls while avoiding deadlock call_get2_ret_t call_get2(call_t **ret1, call_t **ret2, const str *callid1, const str *callid2) { call_get2_ret_t ret; while (true) { RWLOCK_R(&rtpe_callhash_lock); *ret1 = t_hash_table_lookup(rtpe_callhash, callid1); if (!*ret1) return CG2_NF1; *ret2 = t_hash_table_lookup(rtpe_callhash, callid2); if (!*ret2) return CG2_NF2; if (*ret1 == *ret2) { *ret2 = NULL; ret = CG2_SAME; rwlock_lock_w(&(*ret1)->master_lock); obj_hold(*ret1); } else { rwlock_lock_w(&(*ret1)->master_lock); if (rwlock_trylock_w(&(*ret2)->master_lock)) { // try again rwlock_unlock_w(&(*ret1)->master_lock); continue; } ret = CG2_OK; obj_hold(*ret1); obj_hold(*ret2); } break; } log_info_call(*ret1); return ret; } static gboolean fragment_move(str *key, fragment_q *q, void *c) { call_t *call = c; t_hash_table_insert(call->sdp_fragments, key, q); return TRUE; } // both calls must be locked and a reference held. call2 will be released and set to NULL upon return bool call_merge(call_t *call, call_t **call2p) { call_t *call2 = *call2p; // chcek for tag collisions: duplicate tags are a failure for (auto_iter(l, call2->monologues.head); l; l = l->next) { if (t_hash_table_lookup(call->tags, &l->data->tag)) return false; } ilog(LOG_DEBUG, "Merging call " STR_FORMAT_M " into " STR_FORMAT_M, STR_FMT_M(&call2->callid), STR_FMT_M(&call->callid)); // move buffers bencode_buffer_merge(&call->buffer, &call2->buffer); // move all contained objects: we have to renumber all unique IDs, and redirect any // `call` pointers unsigned int last_id = call->monologues.head->data->unique_id; while (call2->monologues.head) { __auto_type ml = t_queue_pop_head(&call2->monologues); ml->unique_id = ++last_id; ml->call = call; t_queue_push_tail(&call->monologues, ml); t_hash_table_insert(call->tags, &ml->tag, ml); for (auto_iter(l, ml->tag_aliases.head); l; l = l->next) t_hash_table_insert(call->tags, l->data, ml); if (ml->viabranch.len) t_hash_table_insert(call->viabranches, &ml->viabranch, ml); if (ml->label.len) t_hash_table_insert(call->labels, &ml->label, ml); } last_id = call->medias.head->data->unique_id; while (call2->medias.head) { __auto_type media = t_queue_pop_head(&call2->medias); media->unique_id = ++last_id; media->call = call; t_queue_push_tail(&call->medias, media); } t_hash_table_foreach_remove(call2->sdp_fragments, fragment_move, call); last_id = call->streams.head->data->unique_id; while (call2->streams.head) { __auto_type stream = t_queue_pop_head(&call2->streams); stream->unique_id = ++last_id; stream->call = call; t_queue_push_tail(&call->streams, stream); } last_id = call->stream_fds.head->data->unique_id; while (call2->stream_fds.head) { __auto_type sfd = t_queue_pop_head(&call2->stream_fds); sfd->unique_id = ++last_id; // call objects are held by reference here if (sfd->call) { obj_release(sfd->call); sfd->call = obj_get(call); } t_queue_push_tail(&call->stream_fds, sfd); } last_id = call->endpoint_maps.head->data->unique_id; while (call2->endpoint_maps.head) { __auto_type endpoint_map = t_queue_pop_head(&call2->endpoint_maps); endpoint_map->unique_id = ++last_id; t_queue_push_tail(&call->endpoint_maps, endpoint_map); } // redirect hash table entry for old ID. store old ID in new call str *old_id = call_str_dup(&call2->callid); t_queue_push_tail(&call->callid_aliases, old_id); rwlock_lock_w(&rtpe_callhash_lock); call_t *call_ht = NULL; t_hash_table_steal_extended(rtpe_callhash, &call2->callid, NULL, &call_ht); if (call_ht) { if (call_ht != call2) { // already deleted and replace by a different call t_hash_table_insert(rtpe_callhash, &call_ht->callid, call_ht); call_ht = NULL; } else { // insert a new reference under the old call ID t_hash_table_insert(rtpe_callhash, old_id, obj_get(call)); RTPE_GAUGE_DEC(total_sessions); } } // else: already deleted rwlock_unlock_w(&rtpe_callhash_lock); obj_release(call_ht); __call_iterator_remove(call2); mqtt_timer_stop(&call2->mqtt_timer); __call_cleanup(call2); rwlock_unlock_w(&call2->master_lock); obj_release(call2); *call2p = NULL; return true; } /* returns call with master_lock held in W, or possibly NULL iff opmode == OP_ANSWER */ call_t *call_get_opmode(const str *callid, enum ng_opmode opmode) { if (opmode == OP_OFFER) return call_get_or_create(callid, false); return call_get(callid); } /** * Create a new monologue, without assigning a tag to that. * Allocate all required hash tables for it. * * Also give the non reference-counted ptr to the call it belongs to. * * Must be called with call->master_lock held in W. */ struct call_monologue *__monologue_create(call_t *call) { struct call_monologue *ret; __C_DBG("creating new monologue"); ret = uid_alloc(&call->monologues); ret->call = call; ret->created_us = rtpe_now; ret->associated_tags = g_hash_table_new(g_direct_hash, g_direct_equal); ret->medias = medias_arr_new(); ret->media_ids = media_id_ht_new(); ret->sdp_attr_print = sdp_insert_monologue_attributes; /* explicitely set b=RR/b=RS to -1 so it's not considered as 0 inadvertently */ RESET_BANDWIDTH(ret->sdp_session_bandwidth, -1); ret->started = rtpe_now; return ret; } /** * Assign a new tag to the given monologue. * Additionally, remove older monologue tag from the correlated call tags, * and add a newer one. * * Must be called with call->master_lock held in W. */ void __monologue_tag(struct call_monologue *ml, const str *tag) { call_t *call = ml->call; if (!ml->tag.s) { __C_DBG("tagging monologue with '" STR_FORMAT "'", STR_FMT(tag)); ml->tag = call_str_cpy(tag); t_hash_table_insert(call->tags, &ml->tag, ml); return; } if (!str_cmp_str(&ml->tag, tag)) return; // no change // to-tag has changed, save previous as alias __C_DBG("tagging monologue with '" STR_FORMAT "', saving previous '" STR_FORMAT "' as alias", STR_FMT(tag), STR_FMT(&ml->tag)); // remove old entry first, as `ml->tag` will be changed t_hash_table_remove(call->tags, &ml->tag); // duplicate string and save as alias str *old_tag = call_str_dup(&ml->tag); t_queue_push_tail(&ml->tag_aliases, old_tag); // add duplicated old tag into hash table t_hash_table_insert(call->tags, old_tag, ml); // update tag to new one ml->tag = call_str_cpy(tag); // and add new one to hash table t_hash_table_insert(call->tags, &ml->tag, ml); } void __monologue_viabranch(struct call_monologue *ml, const str *viabranch) { call_t *call = ml->call; if (!viabranch || !viabranch->len) return; __C_DBG("tagging monologue with viabranch '"STR_FORMAT"'", STR_FMT(viabranch)); if (ml->viabranch.s) t_hash_table_remove(call->viabranches, &ml->viabranch); ml->viabranch = call_str_cpy(viabranch); t_hash_table_insert(call->viabranches, &ml->viabranch, ml); } static void __unconfirm_sinks(sink_handler_q *q, const char *reason) { for (__auto_type l = q->head; l; l = l->next) { struct sink_handler *sh = l->data; __stream_unconfirm(sh->sink, reason); } } /** * Unconfirms sinks and streams of all monologue medias. * must be called with call->master_lock held in W */ void __monologue_unconfirm(struct call_monologue *monologue, const char *reason) { if (!monologue) return; for (unsigned int i = 0; i < monologue->medias->len; i++) { struct call_media *media = monologue->medias->pdata[i]; if (!media) continue; __media_unconfirm(media, reason); } } /** * Unconfirms sinks and streams of given media. * must be called with call->master_lock held in W */ void __media_unconfirm(struct call_media *media, const char *reason) { if (!media) return; for (__auto_type m = media->streams.head; m; m = m->next) { struct packet_stream *stream = m->data; __stream_unconfirm(stream, reason); __unconfirm_sinks(&stream->rtp_sinks, reason); __unconfirm_sinks(&stream->rtcp_sinks, reason); } } /** * Unconfirms all monologue medias and its subscribers/subscriptions. */ void dialogue_unconfirm(struct call_monologue *ml, const char *reason) { __monologue_unconfirm(ml, reason); /* TODO: this seems to be doing similar work as `__monologue_unconfirm()` * but works instead on subscriptions additionally. For the future * this should probably be deprecated and `__monologue_unconfirm()` * has to take the work on subscribers/subscriptions as well. */ for (unsigned int i = 0; i < ml->medias->len; i++) { struct call_media *media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type l = media->media_subscriptions.head; l; l = l->next) { struct media_subscription * ms = l->data; __media_unconfirm(ms->media, reason); } for (__auto_type l = media->media_subscribers.head; l; l = l->next) { struct media_subscription * ms = l->data; __media_unconfirm(ms->media, reason); } } } static void __unkernelize_sinks(sink_handler_q *q, const char *reason) { for (__auto_type l = q->head; l; l = l->next) { struct sink_handler *sh = l->data; unkernelize(sh->sink, reason); } } /** * Unkernelizes sinks and streams of given media. * call locked in R */ void call_media_unkernelize(struct call_media *media, const char *reason) { if (!media) return; for (__auto_type m = media->streams.head; m; m = m->next) { struct packet_stream *stream = m->data; unkernelize(stream, reason); __unkernelize_sinks(&stream->rtp_sinks, reason); __unkernelize_sinks(&stream->rtcp_sinks, reason); } } /* must be called with call->master_lock held in W */ static void __tags_unassociate_all(struct call_monologue *a) { GHashTableIter iter; g_hash_table_iter_init(&iter, a->associated_tags); struct call_monologue *b; while (g_hash_table_iter_next(&iter, (void **) &b, NULL)) g_hash_table_remove(b->associated_tags, a); g_hash_table_remove_all(a->associated_tags); } void monologue_destroy(struct call_monologue *monologue) { call_t *call; call = monologue->call; ilog(LOG_DEBUG, "Destroying monologue '" STR_FORMAT "' (" STR_FORMAT ")", STR_FMT(&monologue->tag), STR_FMT0(&monologue->viabranch)); __monologue_unconfirm(monologue, "destroying monologue"); __tags_unassociate_all(monologue); t_hash_table_remove(call->tags, &monologue->tag); if (monologue->viabranch.s) t_hash_table_remove(call->viabranches, &monologue->viabranch); // close sockets for (unsigned int i = 0; i < monologue->medias->len; i++) { struct call_media *m = monologue->medias->pdata[i]; if (!m) continue; for (__auto_type k = m->streams.head; k; k = k->next) { struct packet_stream *ps = k->data; if (ps->selected_sfd && ps->selected_sfd->socket.local.port) ps->last_local_endpoint = ps->selected_sfd->socket.local; ps->selected_sfd = NULL; stream_fd *sfd; while ((sfd = t_queue_pop_head(&ps->sfds))) stream_fd_release(sfd); } } monologue->deleted_us = 0; } /* must be called with call->master_lock held in W */ static void __tags_unassociate(struct call_monologue *a, struct call_monologue *b) { g_hash_table_remove(a->associated_tags, b); g_hash_table_remove(b->associated_tags, a); } /** * Marks the monologue for destruction, or destroys it immediately. * It also iterates through the associated monologues and does the same for them. * * Returns `true`, if we need to update Redis. */ static bool monologue_delete_iter(struct call_monologue *a, int64_t delete_delay_us) { call_t *call = a->call; if (!call) return 0; GList *associated = g_hash_table_get_values(a->associated_tags); bool update_redis = false; if (delete_delay_us > 0) { ilog(LOG_INFO, "Scheduling deletion of call branch '" STR_FORMAT_M "' " "(via-branch '" STR_FORMAT_M "') in %" PRId64 " seconds", STR_FMT_M(&a->tag), STR_FMT0_M(&a->viabranch), delete_delay_us / 1000000L); a->deleted_us = rtpe_now + delete_delay_us; if (!call->ml_deleted_us || call->ml_deleted_us > a->deleted_us) call->ml_deleted_us = a->deleted_us; } else { ilog(LOG_INFO, "Deleting call branch '" STR_FORMAT_M "' (via-branch '" STR_FORMAT_M "')", STR_FMT_M(&a->tag), STR_FMT0_M(&a->viabranch)); monologue_destroy(a); update_redis = true; } /* Look into all associated monologues: cascade deletion to those, * which have no other associations left */ for (GList *l = associated; l; l = l->next) { struct call_monologue *b = l->data; __tags_unassociate(a, b); if (g_hash_table_size(b->associated_tags) == 0) monologue_delete_iter(b, delete_delay_us); /* schedule deletion of B */ } g_list_free(associated); return update_redis; } /** * Based on the tag lookup the monologue in the 'tags' GHashTable of the call. * * Must be called with call->master_lock held in W. */ struct call_monologue *call_get_monologue(call_t *call, const str *fromtag) { return t_hash_table_lookup(call->tags, fromtag); } /** * Based on the monologue tag, try to lookup the monologue in the 'tags' GHashTable. * If not found create a new one (call_monologue) and associate with a given tag. * * Must be called with call->master_lock held in W. */ struct call_monologue *call_get_or_create_monologue(call_t *call, const str *fromtag) { struct call_monologue *ret = call_get_monologue(call, fromtag); if (!ret) { ret = __monologue_create(call); __monologue_tag(ret, fromtag); } return ret; } /** * Must be called with call->master_lock held in W. * * Also cancel scheduled deletion during offer/answer: * * Unmark a monologue that has been scheduled for deletion when it's * associated with another one, which happens during offer/answer. */ static void __tags_associate(struct call_monologue *a, struct call_monologue *b) { a->deleted_us = 0; b->deleted_us = 0; g_hash_table_insert(a->associated_tags, b, b); g_hash_table_insert(b->associated_tags, a, a); } /** * Check whether the call object contains some other monologues, which can have own associations. */ static bool call_monologues_associations_left(call_t * c) { for (__auto_type l = c->monologues.head; l; l = l->next) { struct call_monologue * ml = l->data; if (g_hash_table_size(ml->associated_tags) > 0) return true; } return false; } /** * Based on given From-tag create a new monologue for this dialog, * if given tag wasn't present in 'tags' of this call. * * In case this is an initial offer, create both dialog sides (monologues), * even though the tag will be empty for the monologue requiring the To-tag. * * Otherwise, try to lookup the 'other side' using via branch value, and tag it * using the given To-tag, if this associated monologue didn't have a tag before. * * Must be called with call->master_lock held in W. * * `dialogue` must be initialised to zero. */ static int call_get_monologue_new(struct call_monologue *monologues[2], call_t *call, const str *fromtag, const str *totag, const str *viabranch, sdp_ng_flags *flags) { struct call_monologue *ret, *os = NULL; /* ret - initial offer, os - other side */ __C_DBG("getting monologue for tag '"STR_FORMAT"' in call '"STR_FORMAT"'", STR_FMT(fromtag), STR_FMT(&call->callid)); ret = call_get_monologue(call, fromtag); if (!ret) { /* this is a brand new offer */ ret = __monologue_create(call); __monologue_tag(ret, fromtag); goto new_branch; } __C_DBG("found existing monologue"); /* unkernelize existing monologue medias, which are subscribed to something */ dialogue_unconfirm(ret, "signalling on existing monologue"); /* If to-tag is present, retrieve it. * Create a new monologue for the other side, if the monologue with such to-tag not found. */ if (totag && totag->s) { struct call_monologue * monologue = call_get_monologue(call, totag); if (!monologue) goto new_branch; } if (!viabranch) { /* dialogue complete */ goto have_dialogue; } else { os = t_hash_table_lookup(call->viabranches, viabranch); if (os) { /* previously seen branch, use it */ __monologue_unconfirm(os, "dialogue/branch association changed"); goto have_dialogue; } } /* we need both sides of the dialogue even in the initial offer, so create * another monologue without to-tag (to be filled in later) */ new_branch: __C_DBG("create new \"other side\" monologue for viabranch "STR_FORMAT, STR_FMT0(viabranch)); os = __monologue_create(call); __monologue_viabranch(os, viabranch); goto finish; have_dialogue: for (unsigned int i = 0; i < ret->medias->len; i++) { struct call_media *media = ret->medias->pdata[i]; if (!media) continue; for (__auto_type l = media->media_subscriptions.head; l; l = l->next) { struct media_subscription * ms = l->data; if (!ms->attrs.offer_answer) continue; if (!os) os = ms->monologue; if (totag && totag->s) __monologue_tag(ms->monologue, totag); /* There should be only one monologue? * TODO: check if there's more than one-to-one mapping */ goto finish; } } finish: if (G_UNLIKELY(!os)) return -1; __tags_associate(ret, os); monologues[0] = ret; monologues[1] = os; return 0; } /** * Using the From-tag / To-tag get call monologues (dialog). Where: * - dialogue[0] is a monologue associated with the From-tag * - dialogue[1] is a monologue associated with the To-tag * * The request will be treated as a brand new offer, * in case the To-tag is still not know for this call. * * The function must be called with call->master_lock held in W. * * `dialogue` must be initialised to zero. */ static int call_get_dialogue(struct call_monologue *monologues[2], call_t *call, const str *fromtag, const str *totag, const str *viabranch, sdp_ng_flags *flags) { struct call_monologue *ft, *tt; __C_DBG("getting dialogue for tags '"STR_FORMAT"'<>'"STR_FORMAT"' in call '"STR_FORMAT"'", STR_FMT(fromtag), STR_FMT(totag), STR_FMT(&call->callid)); /* ft - is always this side's tag (in offer it's message's from-tag, in answer it's message's to-tag) * tt - is always other side's tag (in offer it's message's to-tag, in answer it's message's from-tag) */ /* we start with the to-tag. if it's not known, we treat it as a branched offer */ tt = call_get_monologue(call, totag); if (!tt) return call_get_monologue_new(monologues, call, fromtag, totag, viabranch, flags); /* if the from-tag is known already, return that */ ft = call_get_monologue(call, fromtag); if (ft) { __C_DBG("found existing dialogue"); /* detect whether given ft's medias * already seen as subscribers of tt's medias, otherwise setup tags */ for (unsigned int i = 0; i < ft->medias->len; i++) { struct call_media *media = ft->medias->pdata[i]; if (!media) continue; /* try to find tt in subscriptions of ft */ for (__auto_type l = media->media_subscriptions.head; l; l = l->next) { struct media_subscription * ms = l->data; if (ms->monologue && ms->monologue == tt) goto done; } } /* it seems ft hasn't seen tt before */ goto tag_setup; } /* try to determine the monologue from the viabranch, * or using the top most tt's subscription, if there is one. * Otherwise just create a brand-new one. */ if (viabranch) ft = t_hash_table_lookup(call->viabranches, viabranch); /* first possible subscription of tt (other side) */ if (!ft) { /* find by any other's side subscriptions (expected one-monologue to one-monologue talk) */ for (int i = 0; i < tt->medias->len; i++) { struct call_media *media = tt->medias->pdata[i]; if (!media || !media->media_subscriptions.head) continue; struct media_subscription * ms = media->media_subscriptions.head->data; if (ms->monologue) { ft = ms->monologue; __C_DBG("Found existing monologue '" STR_FORMAT "' for this side, by lookup of other side subscriptions", STR_FMT(&ft->tag)); break; } } } /* otherwise create a brand-new one. * The lookup of the offer monologue from the answer monologue is only valid, * if the offer monologue belongs to an unanswered call (empty tag), * hence `ft->tag` has to be empty at this stage. */ if (!ft) ft = __monologue_create(call); else if (ft->tag.s) { // Allow an updated/changed to-tag in answers unless the flag to // suppress this feature is set. A changed to-tag will be stored // as a tag alias. if (!flags || flags->opmode != OP_ANSWER || flags->new_branch || (ML_ISSET(ft, FINAL_RESPONSE) && !flags->provisional)) ft = __monologue_create(call); } tag_setup: if (ft == tt) return -1; // it's a hard error to have a monologue talking to itself /* the fromtag monologue may be newly created, or half-complete from the totag, or * derived from the viabranch. */ __monologue_tag(ft, fromtag); dialogue_unconfirm(ft, "dialogue signalling event"); dialogue_unconfirm(tt, "dialogue signalling event"); done: __monologue_unconfirm(ft, "dialogue signalling event"); dialogue_unconfirm(ft, "dialogue signalling event"); __tags_associate(ft, tt); /* just provide gotten dialogs, * which have all needed information about subscribers/subscriptions */ monologues[0] = ft; monologues[1] = tt; return 0; } /* fromtag and totag strictly correspond to the directionality of the message, not to the actual * SIP headers. IOW, the fromtag corresponds to the monologue sending this message, even if the * tag is actually from the TO header of the SIP message (as it would be in a 200 OK) */ int call_get_mono_dialogue(struct call_monologue *monologues[2], call_t *call, const str *fromtag, const str *totag, const str *viabranch, sdp_ng_flags *flags) { /* initial offer */ if (!totag || !totag->s) return call_get_monologue_new(monologues, call, fromtag, NULL, viabranch, flags); return call_get_dialogue(monologues, call, fromtag, totag, viabranch, flags); } static void media_stop(struct call_media *m) { if (!m) return; t38_gateway_stop(m->t38_gateway); audio_player_stop(m); codec_handlers_stop(&m->codec_handlers_store, NULL, false); rtcp_timer_stop(&m->rtcp_timer); mqtt_timer_stop(&m->mqtt_timer); } /** * Stops media player of given monologue. */ static void __monologue_stop(struct call_monologue *ml) { media_player_stop(ml->player); media_player_stop(ml->rec_player); } /** * Stops media player and all medias of given monolgue. * If asked, stops all media subscribers as well. */ static void monologue_stop(struct call_monologue *ml, bool stop_media_subsribers) { /* monologue itself */ __monologue_stop(ml); for (unsigned int i = 0; i < ml->medias->len; i++) { media_stop(ml->medias->pdata[i]); } /* monologue's subscribers */ if (stop_media_subsribers) { g_auto(GQueue) mls = G_QUEUE_INIT; /* to avoid duplications */ for (unsigned int i = 0; i < ml->medias->len; i++) { struct call_media *media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type l = media->media_subscribers.head; l; l = l->next) { struct media_subscription * ms = l->data; media_stop(ms->media); if (!g_queue_find(&mls, ms->monologue)) { __monologue_stop(ms->monologue); g_queue_push_tail(&mls, ms->monologue); } } } } } // call must be locked in W. // unlocks the call and releases the reference prior to returning, even on error. int call_delete_branch(call_t *c, const str *branch, const str *fromtag, const str *totag, ng_command_ctx_t *ctx, int64_t delete_delay) { struct call_monologue *ml; int ret; const str *match_tag; bool update = false; if (delete_delay < 0) delete_delay = rtpe_config.delete_delay_us; else delete_delay *= 1000000L; for (__auto_type i = c->monologues.head; i; i = i->next) { ml = i->data; ml->terminated = rtpe_now; ml->term_reason = REGULAR; } if (!fromtag || !fromtag->len) goto del_all; if ((!totag || !totag->len) && branch && branch->len) { // try a via-branch match ml = t_hash_table_lookup(c->viabranches, branch); if (ml) goto do_delete; } match_tag = (totag && totag->len) ? totag : fromtag; ml = call_get_monologue(c, match_tag); if (!ml) { if (branch && branch->len) { // also try a via-branch match here ml = t_hash_table_lookup(c->viabranches, branch); if (ml) goto do_delete; } /* IMPORTANT! * last resort: try the from-tag, if we tried the to-tag before and see, * if the associated dialogue has an empty tag (unknown). * If that condition is met, then we delete the entire call. * * A use case for that is: `delete` done with from-tag and to-tag, * right away after an `offer` without the to-tag and without use of via-branch. * Then, looking up the offer side of the call through the from-tag * and then checking, if the call has not been answered (answer side has an empty to-tag), * gives a clue whether to delete an entire call. */ if (match_tag == totag) { ml = call_get_monologue(c, fromtag); if (ml) { struct call_monologue * sub_ml = ml_medias_subscribed_to_single_ml(ml); if (sub_ml && !sub_ml->tag.len) goto do_delete; } } ilog(LOG_INFO, "Tag '"STR_FORMAT"' in delete message not found, ignoring", STR_FMT(match_tag)); goto err; } do_delete: c->destroyed = rtpe_now; /* stop media player and all medias of ml. * same for media subscribers */ monologue_stop(ml, true); /* check, if we have some associated monologues left, which have own associations * which means they need a media to flow */ update = monologue_delete_iter(ml, delete_delay); /* if there are no associated dialogs, which still require media, then additionally * ensure, whether we can afford to destroy the whole call now. * Maybe some of them still need a media to flow */ bool del_stop = false; del_stop = call_monologues_associations_left(c); if (!del_stop) goto del_all; if (ctx) ng_call_stats(ctx, c, fromtag, totag, NULL); goto success_unlock; del_all: if (ctx) ng_call_stats(ctx, c, NULL, NULL, NULL); for (__auto_type i = c->monologues.head; i; i = i->next) { ml = i->data; monologue_stop(ml, false); } c->destroyed = rtpe_now; if (delete_delay > 0) { ilog(LOG_INFO, "Scheduling deletion of entire call in %" PRId64 " seconds", delete_delay / 1000000L); c->deleted_us = rtpe_now + delete_delay; rwlock_unlock_w(&c->master_lock); } else { ilog(LOG_INFO, "Deleting entire call"); rwlock_unlock_w(&c->master_lock); call_destroy(c); update = false; } goto success; success_unlock: rwlock_unlock_w(&c->master_lock); success: ret = 0; goto out; err: rwlock_unlock_w(&c->master_lock); ret = -1; goto out; out: if (update) redis_update_onekey(c, rtpe_redis_write); obj_release(c); return ret; } int call_delete_branch_by_id(const str *callid, const str *branch, const str *fromtag, const str *totag, ng_command_ctx_t *ctx, int64_t delete_delay) { call_t *c = call_get(callid); if (!c) { ilog(LOG_INFO, "Call-ID to delete not found"); return -1; } return call_delete_branch(c, branch, fromtag, totag, ctx, delete_delay); } struct call_media *call_make_transform_media(struct call_monologue *ml, const str *type, enum media_type type_id, const str *media_id, const endpoint_t *remote, const str *interface) { struct call_media *ret = call_get_media(ml, type, type_id, media_id, false, ml->medias->len + 1, str_ht_null()); if (!media_id->len) generate_mid(ret, ret->unique_id); ret->protocol = &transport_protocols[PROTO_RTP_AVP]; bf_set(&ret->media_flags, MEDIA_FLAG_SEND | MEDIA_FLAG_RECV | MEDIA_FLAG_RTCP_MUX); ret->desired_family = remote->address.family; __init_interface(ret, interface, 1); struct endpoint_map *em = __get_endpoint_map(ret, 1, remote, NULL, true); if (!em) return false; __num_media_streams(ret, 1); __assign_stream_fds(ret, &em->intf_sfds); return ret; } bool monologue_transform(struct call_monologue *ml, sdp_ng_flags *flags, medias_q *out_q) { __auto_type q = &flags->medias; for (__auto_type l = q->head; l; l = l->next) { __auto_type media = l->data; if (!media->destination.address.family) return false; __auto_type m = call_make_transform_media(ml, &media->type, codec_get_type(&media->type), &media->id, &media->destination, &flags->interface); media->id = m->media_id; t_queue_push_tail(out_q, m); // subscribe to itself __add_media_subscription(m, m, NULL); __auto_type ps = m->streams.head->data; ps->advertised_endpoint = ps->endpoint = media->destination; __add_sink_handler(&ps->rtp_sinks, ps, NULL); if (!codec_handler_transform(m, &media->codecs)) return false; __init_streams(m, NULL, flags); } return true; } rtpengine-mr13.5.1.3/daemon/call_interfaces.c000066400000000000000000004036431512121055300210260ustar00rootroot00000000000000#include "call_interfaces.h" #include #include #include #include #include #include #include "call.h" #include "helpers.h" #include "log.h" #include "redis.h" #include "sdp.h" #include "str.h" #include "control_tcp.h" #include "control_udp.h" #include "control_ng.h" #include "rtp.h" #include "ice.h" #include "recording.h" #include "rtplib.h" #include "ssrc.h" #include "tcp_listener.h" #include "streambuf.h" #include "main.h" #include "load.h" #include "media_player.h" #include "dtmf.h" #include "codec.h" #include "dtmf.h" #include "control_ng_flags_parser.h" static pcre2_code *info_re; static pcre2_code *streams_re; bool trust_address_def; bool dtls_passive_def; str_case_value_ht rtpe_signalling_templates; str rtpe_default_signalling_templates[OP_COUNT + 1]; enum basic_errors { NG_ERROR_NO_SDP_BODY = 1, NG_ERROR_NO_CALL_ID = 2, NG_ERROR_NO_FROM_TAG = 3, NG_ERROR_NO_TO_TAG = 4 }; static const char* _ng_basic_errors[] = { [NG_ERROR_NO_SDP_BODY] = "No SDP body in message", [NG_ERROR_NO_CALL_ID] = "No call-id in message", [NG_ERROR_NO_FROM_TAG] = "No from-tag in message", [NG_ERROR_NO_TO_TAG] = "No to-tag in message", }; INLINE int call_ng_flags_prefix(str *s_ori, const char *prefix, void (*cb)(str *, unsigned int, helper_arg), helper_arg); static void call_ng_flags_str_ht(str *s, unsigned int, helper_arg); static void call_ng_flags_str_q_multi(str *s, unsigned int, helper_arg); static void call_ng_flags_str_list(const ng_parser_t *, parser_arg list, void (*callback)(str *, unsigned int, helper_arg), helper_arg); static void call_ng_flags_list(const ng_parser_t *, parser_arg list, void (*str_callback)(str *, unsigned int, helper_arg), void (*item_callback)(const ng_parser_t *, parser_arg, helper_arg), helper_arg); static void call_ng_flags_esc_str_list(str *s, unsigned int, helper_arg); static void ng_stats_ssrc(const ng_parser_t *parser, parser_arg dict, parser_arg list, const struct ssrc_hash *ht); static str *str_dup_escape(const str *s); static void call_set_dtmf_block(call_t *call, struct call_monologue *monologue, sdp_ng_flags *flags); static str streams_print(medias_arr *s, int start, int end, const char *prefix, enum stream_address_format format) { GString *o; int i, af, port; struct call_media *media; struct packet_stream *ps; o = g_string_new(""); if (prefix) g_string_append_printf(o, "%s ", prefix); for (i = start; i <= end; i++) { if (s->len <= i || (media = s->pdata[i - 1]) == NULL) { ilog(LOG_WARNING, "Requested media index %i not found", i); break; } if (!media->streams.head) { ilog(LOG_WARNING, "Media has no streams"); break; } ps = media->streams.head->data; if (format == SAF_TCP) call_stream_address(o, ps, format, NULL, true); port = ps->selected_sfd ? ps->selected_sfd->socket.local.port : 0; g_string_append_printf(o, (format == 1) ? "%i " : " %i", port); if (format == SAF_UDP) { af = call_stream_address(o, ps, format, NULL, true); g_string_append_printf(o, " %c", (af == AF_INET) ? '4' : '6'); } } g_string_append(o, "\n"); return g_string_free_str(o); } static int addr_parse_udp(struct stream_params *sp, char **out) { const char *cp; char c; int i; ZERO(*sp); SP_SET(sp, SEND); SP_SET(sp, RECV); sp->protocol = &transport_protocols[PROTO_UNKNOWN]; if (out[RE_UDP_UL_ADDR4] && *out[RE_UDP_UL_ADDR4]) { if (!sockaddr_parse_any(&sp->rtp_endpoint.address, out[RE_UDP_UL_ADDR4])) goto fail; } else if (out[RE_UDP_UL_ADDR6] && *out[RE_UDP_UL_ADDR6]) { if (!sockaddr_parse_any(&sp->rtp_endpoint.address, out[RE_UDP_UL_ADDR6])) goto fail; } else goto fail; sp->rtp_endpoint.port = atoi(out[RE_UDP_UL_PORT]); if (!sp->rtp_endpoint.port && strcmp(out[RE_UDP_UL_PORT], "0")) goto fail; if (out[RE_UDP_UL_FLAGS] && *out[RE_UDP_UL_FLAGS]) { i = 0; for (cp =out[RE_UDP_UL_FLAGS]; *cp && i < 2; cp++) { c = chrtoupper(*cp); if (c == 'E') sp->direction[i++] = STR("external"); else if (c == 'I') sp->direction[i++] = STR("internal"); } } if (out[RE_UDP_UL_NUM] && *out[RE_UDP_UL_NUM]) sp->index = atoi(out[RE_UDP_UL_NUM]); if (!sp->index) sp->index = 1; sp->consecutive_ports = 1; sp->rtcp_endpoint = sp->rtp_endpoint; sp->rtcp_endpoint.port++; return 0; fail: return -1; } static void updated_created_from(call_t *c, const char *addr) { if (!c->created_from.len && addr) c->created_from = call_str_cpy_c(addr); } static str call_update_lookup_udp(char **out, enum ng_opmode opmode, const char* addr) { call_t *c; struct call_monologue *monologues[2]; /* subscriber lists of both monologues */ sdp_streams_q q = TYPED_GQUEUE_INIT; struct stream_params sp; str ret; int i; g_auto(sdp_ng_flags) flags; call_ng_flags_init(&flags, opmode); str callid = STR(out[RE_UDP_UL_CALLID]); str fromtag = STR(out[RE_UDP_UL_FROMTAG]); str totag = STR(out[RE_UDP_UL_TOTAG]); if (opmode == OP_ANSWER) str_swap(&fromtag, &totag); c = call_get_opmode(&callid, opmode); if (!c) { ilog(LOG_WARNING, "[" STR_FORMAT_M "] Got UDP LOOKUP for unknown call-id", STR_FMT_M(&callid)); return str_sprintf("%s 0 0.0.0.0\n", out[RE_UDP_COOKIE]); } updated_created_from(c, addr); if (call_get_mono_dialogue(monologues, c, &fromtag, &totag, NULL, NULL)) goto ml_fail; struct call_monologue *from_ml = monologues[0]; struct call_monologue *to_ml = monologues[1]; if (opmode == OP_OFFER) { from_ml->tagtype = FROM_TAG; } else { from_ml->tagtype = TO_TAG; } if (addr_parse_udp(&sp, out)) goto addr_fail; t_queue_push_tail(&q, &sp); i = monologue_offer_answer(monologues, &q, &flags); t_queue_clear(&q); if (i) goto unlock_fail; ret = streams_print(to_ml->medias, sp.index, sp.index, out[RE_UDP_COOKIE], SAF_UDP); rwlock_unlock_w(&c->master_lock); redis_update_onekey(c, rtpe_redis_write); from_ml->started = rtpe_now; ilog(LOG_INFO, "Returning to SIP proxy: " STR_FORMAT, STR_FMT(&ret)); goto out; ml_fail: ilog(LOG_ERR, "Invalid dialogue association"); goto unlock_fail; addr_fail: ilog(LOG_ERR, "Failed to parse a media stream: %s%s/%s:%s%s", FMT_M(out[RE_UDP_UL_ADDR4], out[RE_UDP_UL_ADDR6], out[RE_UDP_UL_PORT])); goto unlock_fail; unlock_fail: rwlock_unlock_w(&c->master_lock); ret = str_sprintf("%s E8\n", out[RE_UDP_COOKIE]); out: obj_put(c); return ret; } str call_update_udp(char **out, const char* addr) { return call_update_lookup_udp(out, OP_OFFER, addr); } str call_lookup_udp(char **out) { return call_update_lookup_udp(out, OP_ANSWER, NULL); } static bool info_parse_func(char **a, void **ret, void *p) { if (!a[0] || !a[1]) return false; GHashTable *ih = p; g_hash_table_replace(ih, strdup(a[0]), strdup(a[1])); return false; } static void info_parse(const char *s, GHashTable *ih) { pcre2_multi_match(info_re, s, 3, info_parse_func, ih, NULL); } static bool streams_parse_func(char **a, void **ret, void *p) { if (!a[0] || !a[1]) return false; struct stream_params *sp; int *i; i = p; sp = g_new0(__typeof(*sp), 1); SP_SET(sp, SEND); SP_SET(sp, RECV); sp->protocol = &transport_protocols[PROTO_UNKNOWN]; if (!endpoint_parse_port_any(&sp->rtp_endpoint, a[0], atoi(a[1]))) goto fail; sp->index = ++(*i); sp->consecutive_ports = 1; sp->rtcp_endpoint = sp->rtp_endpoint; sp->rtcp_endpoint.port++; if (!sp->rtp_endpoint.port && strcmp(a[1], "0")) goto fail; *ret = sp; return true; fail: ilog(LOG_WARNING, "Failed to parse a media stream: %s%s:%s%s", FMT_M(a[0], a[1])); g_free(sp); return false; } static void streams_parse(const char *s, sdp_streams_q *q) { int i; i = 0; pcre2_multi_match(streams_re, s, 4, streams_parse_func, &i, &q->q); } void call_unlock_release(call_t *c) { rwlock_unlock_w(&c->master_lock); obj_put(c); } INLINE void call_unlock_release_update(call_t **c) { if (!*c) return; rwlock_unlock_w(&(*c)->master_lock); redis_update_onekey(*c, rtpe_redis_write); obj_release(*c); } static str call_request_lookup_tcp(char **out, enum ng_opmode opmode) { call_t *c; struct call_monologue *monologues[2]; g_auto(sdp_streams_q) s = TYPED_GQUEUE_INIT; str ret = STR_NULL; GHashTable *infohash; g_auto(sdp_ng_flags) flags; call_ng_flags_init(&flags, opmode); str callid = STR(out[RE_TCP_RL_CALLID]); infohash = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); c = call_get_opmode(&callid, opmode); if (!c) { ilog(LOG_WARNING, "[" STR_FORMAT_M "] Got LOOKUP for unknown call-id", STR_FMT_M(&callid)); goto out; } info_parse(out[RE_TCP_RL_INFO], infohash); streams_parse(out[RE_TCP_RL_STREAMS], &s); str fromtag = STR(g_hash_table_lookup(infohash, "fromtag")); if (!fromtag.s) { ilog(LOG_WARNING, "No from-tag in message"); goto out2; } str totag = STR(g_hash_table_lookup(infohash, "totag")); if (opmode == OP_ANSWER) { if (!totag.s) { ilog(LOG_WARNING, "No to-tag in message"); goto out2; } str_swap(&fromtag, &totag); } if (call_get_mono_dialogue(monologues, c, &fromtag, &totag, NULL, NULL)) { ilog(LOG_WARNING, "Invalid dialogue association"); goto out2; } if (monologue_offer_answer(monologues, &s, &flags)) goto out2; ret = streams_print(monologues[1]->medias, 1, s.length, NULL, SAF_TCP); out2: call_unlock_release_update(&c); ilog(LOG_INFO, "Returning to SIP proxy: " STR_FORMAT, STR_FMT(&ret)); out: g_hash_table_destroy(infohash); return ret; } str call_request_tcp(char **out) { return call_request_lookup_tcp(out, OP_OFFER); } str call_lookup_tcp(char **out) { return call_request_lookup_tcp(out, OP_ANSWER); } str call_delete_udp(char **out) { __C_DBG("got delete for callid '%s' and viabranch '%s'", out[RE_UDP_DQ_CALLID], out[RE_UDP_DQ_VIABRANCH]); str callid = STR(out[RE_UDP_DQ_CALLID]); str branch = STR(out[RE_UDP_DQ_VIABRANCH]); str fromtag = STR(out[RE_UDP_DQ_FROMTAG]); str totag = STR(out[RE_UDP_DQ_TOTAG]); if (call_delete_branch_by_id(&callid, &branch, &fromtag, &totag, NULL, -1)) return str_sprintf("%s E8\n", out[RE_UDP_COOKIE]); return str_sprintf("%s 0\n", out[RE_UDP_COOKIE]); } str call_query_udp(char **out) { g_autoptr(call_t) c = NULL; str ret; struct call_stats stats; __C_DBG("got query for callid '%s'", out[RE_UDP_DQ_CALLID]); str callid = STR(out[RE_UDP_DQ_CALLID]); str fromtag = STR(out[RE_UDP_DQ_FROMTAG]); str totag = STR(out[RE_UDP_DQ_TOTAG]); c = call_get(&callid); if (!c) { ilog(LOG_INFO, "[" STR_FORMAT_M "] Call-ID to query not found", STR_FMT_M(&callid)); goto err; } ng_call_stats(NULL, c, &fromtag, &totag, &stats); rwlock_unlock_w(&c->master_lock); ret = str_sprintf("%s %" PRId64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", out[RE_UDP_COOKIE], atomic_get_na(&rtpe_config.silent_timeout_us) - (rtpe_now - stats.last_packet_us), atomic64_get_na(&stats.totals[0].packets), atomic64_get_na(&stats.totals[1].packets), atomic64_get_na(&stats.totals[2].packets), atomic64_get_na(&stats.totals[3].packets)); goto out; err: ret = str_sprintf("%s E8\n", out[RE_UDP_COOKIE]); out: return ret; } void call_delete_tcp(char **out) { str callid = STR(out[RE_TCP_D_CALLID]); call_delete_branch_by_id(&callid, NULL, NULL, NULL, NULL, -1); } static void call_status_iterator(call_t *c, struct streambuf_stream *s) { // GList *l; // struct callstream *cs; // struct peer *p; // struct streamrelay *r1, *r2; // struct streamrelay *rx1, *rx2; // char addr1[64], addr2[64], addr3[64]; // mutex_lock(&c->master_lock); streambuf_printf(s->outbuf, "session "STR_FORMAT" - - - - %" PRId64 "\n", STR_FMT(&c->callid), (rtpe_now - c->created) / 1000000L); /* XXX restore function */ // mutex_unlock(&c->master_lock); } void calls_status_tcp(struct streambuf_stream *s) { rwlock_lock_r(&rtpe_callhash_lock); streambuf_printf(s->outbuf, "proxy %u %" PRIu64 "/%i/%i\n", t_hash_table_size(rtpe_callhash), atomic64_get(&rtpe_stats_rate.bytes_user) + atomic64_get(&rtpe_stats_rate.bytes_kernel), 0, 0); rwlock_unlock_r(&rtpe_callhash_lock); ITERATE_CALL_LIST_START(CALL_ITERATOR_MAIN, c); call_status_iterator(c, s); ITERATE_CALL_LIST_NEXT_END(c); } INLINE void call_ngb_hold_ref(call_t *c, ng_buffer *ngb) { /* We cannot guarantee that the "call" structures are still around at the time * when the bencode reply is finally read and sent out. Since we use scatter/gather * to avoid duplication of strings and stuff, we reserve a reference to the call * structs and have it released when the bencode buffer is destroyed. This is * necessary every time the bencode response may reference strings contained * within the call structs. */ ngb->call = obj_get(c); } INLINE void ng_sdes_option(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; /* Accept only certain individual crypto suites */ if (call_ng_flags_prefix(s, "only-", call_ng_flags_str_ht, &out->sdes_only)) return; /* Exclude individual crypto suites */ if (call_ng_flags_prefix(s, "no-", call_ng_flags_str_ht, &out->sdes_no)) return; /* Order individual crypto suites */ if (call_ng_flags_prefix(s, "order:", call_ng_flags_str_q_multi, &out->sdes_order)) return; /* Crypto suite preferences for the offerer */ if (call_ng_flags_prefix(s, "offerer_pref:", call_ng_flags_str_q_multi, &out->sdes_offerer_pref)) return; switch (__csh_lookup(s)) { case CSH_LOOKUP("no"): case CSH_LOOKUP("off"): case CSH_LOOKUP("disabled"): case CSH_LOOKUP("disable"): out->sdes_off = true; break; case CSH_LOOKUP("unencrypted_srtp"): case CSH_LOOKUP("UNENCRYPTED_SRTP"): out->sdes_unencrypted_srtp = true; break; case CSH_LOOKUP("unencrypted_srtcp"): case CSH_LOOKUP("UNENCRYPTED_SRTCP"): out->sdes_unencrypted_srtcp = true; break; case CSH_LOOKUP("unauthenticated_srtp"): case CSH_LOOKUP("UNAUTHENTICATED_SRTP"): out->sdes_unauthenticated_srtp = true; break; case CSH_LOOKUP("encrypted_srtp"): case CSH_LOOKUP("ENCRYPTED_SRTP"): out->sdes_encrypted_srtp = true; break; case CSH_LOOKUP("encrypted_srtcp"): case CSH_LOOKUP("ENCRYPTED_SRTCP"): out->sdes_encrypted_srtcp = true; break; case CSH_LOOKUP("authenticated_srtp"): case CSH_LOOKUP("AUTHENTICATED_SRTP"): out->sdes_authenticated_srtp = true; break; case CSH_LOOKUP("lifetime"): out->sdes_lifetime = true; break; case CSH_LOOKUP("pad"): out->sdes_pad = true; break; case CSH_LOOKUP("static"): out->sdes_static = true; break; case CSH_LOOKUP("nonew"): out->sdes_nonew = true; break; case CSH_LOOKUP("prefer"): case CSH_LOOKUP("priority"): out->sdes_prefer = true; break; default: ilog(LOG_WARN, "Unknown 'SDES' flag encountered: '"STR_FORMAT"'", STR_FMT(s)); } } INLINE void ng_osrtp_option(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(s)) { case CSH_LOOKUP("accept-rfc"): case CSH_LOOKUP("accept-RFC"): out->osrtp_accept_rfc = true; break; case CSH_LOOKUP("accept-legacy"): out->osrtp_accept_legacy = true; break; case CSH_LOOKUP("accept"): out->osrtp_accept_rfc = true; out->osrtp_accept_legacy = true; break; case CSH_LOOKUP("offer-legacy"): out->osrtp_offer_legacy = true; break; case CSH_LOOKUP("offer"): case CSH_LOOKUP("offer-RFC"): case CSH_LOOKUP("offer-rfc"): out->osrtp_offer = true; break; default: ilog(LOG_WARN, "Unknown 'OSRTP' flag encountered: '" STR_FORMAT "'", STR_FMT(s)); } } static void call_ng_flags_str_pair_ht(str *s, unsigned int idx, helper_arg arg) { str *s_copy = str_dup_escape(s); str token; if (!str_token(&token, s_copy, '>')) { ilog(LOG_WARN, "SDP manipulations: Ignoring invalid token '" STR_FORMAT "'", STR_FMT(s)); free(s_copy); return; } str_case_value_ht *ht = arg.svt; if (!t_hash_table_is_set(*ht)) *ht = str_case_value_ht_new(); t_hash_table_replace(*ht, str_dup(&token), s_copy); } static void call_ng_flags_item_pair_ht_iter(str *key, unsigned int idx, helper_arg arg) { str *from_to = arg.strs; if (from_to[0].len == 0) from_to[0] = *key; else if (from_to[1].len == 0) from_to[1] = *key; } static void call_ng_flags_item_pair_ht(const ng_parser_t *parser, parser_arg it, helper_arg arg) { str from_to[2] = {0}; if (!parser->is_list(it)) goto err; parser->list_iter(parser, it, call_ng_flags_item_pair_ht_iter, NULL, from_to); if (from_to[0].len == 0 || from_to[1].len == 0) goto err; str * s_copy_from = str_dup_escape(&from_to[0]); str * s_copy_to = str_dup_escape(&from_to[1]); str_case_value_ht *ht = arg.svt; if (!t_hash_table_is_set(*ht)) *ht = str_case_value_ht_new(); t_hash_table_replace(*ht, s_copy_from, s_copy_to); return; err: ilog(LOG_WARN, "SDP manipulations: Ignoring invalid contents of string-pair list"); } /** * SDP attribute manipulation praser helpers. */ static void ng_sdp_attr_media_iter(const ng_parser_t *parser, str *command_type, parser_arg command_value, helper_arg arg) { struct sdp_manipulations *sm = arg.sm; switch (__csh_lookup(command_type)) { case CSH_LOOKUP("substitute"): call_ng_flags_list(parser, command_value, call_ng_flags_str_pair_ht, call_ng_flags_item_pair_ht, &sm->subst_commands); break; case CSH_LOOKUP("add"): call_ng_flags_str_list(parser, command_value, call_ng_flags_esc_str_list, &sm->add_commands); break; case CSH_LOOKUP("remove"): call_ng_flags_str_list(parser, command_value, call_ng_flags_str_ht, &sm->rem_commands); break; default: ilog(LOG_WARN, "SDP manipulations: Unknown SDP manipulation command type."); } } static void ng_sdp_attr_manipulations_iter(const ng_parser_t *parser, str *media_type, parser_arg command_action, helper_arg arg) { struct sdp_manipulations *sm = sdp_manipulations_get_by_name(arg.flags->sdp_manipulations, media_type); if (!sm) { ilog(LOG_WARN, "SDP manipulations: unsupported SDP section '" STR_FORMAT "' targeted.", STR_FMT(media_type)); return; } if (!parser->dict_iter(parser, command_action, ng_sdp_attr_media_iter, sm)) ilog(LOG_WARN, "SDP manipulations: Wrong content for SDP section."); } INLINE void ng_sdp_attr_manipulations(const ng_parser_t *parser, sdp_ng_flags *flags, parser_arg value) { if (!parser->dict_iter(parser, value, ng_sdp_attr_manipulations_iter, flags)) ilog(LOG_WARN, "SDP manipulations: Wrong type for this type of command."); } /** * SDP media section manipulation parser helpers. */ static void ng_sdp_media_remove_iter(str *media_type, unsigned int i, helper_arg arg) { enum media_type id = codec_get_type(media_type); if (id == MT_UNKNOWN || (id == MT_OTHER && str_cmp(media_type, "other"))) { ilog(LOG_WARN, "SDP manipulations: unsupported SDP section '" STR_FORMAT "' targeted.", STR_FMT(media_type)); /* only known media types are supported */ return; } arg.flags->sdp_media_remove[id] = true; } INLINE void ng_sdp_media_remove(const ng_parser_t *parser, sdp_ng_flags *flags, parser_arg value) { if (!parser->is_list(value)) return; parser->list_iter(parser, value, ng_sdp_media_remove_iter, NULL, flags); } INLINE void ng_el_option(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(s)) { case CSH_LOOKUP("off"): out->el_option = EL_OFF; break; case CSH_LOOKUP("immediate"): out->el_option = EL_IMMEDIATE; break; case CSH_LOOKUP("delayed"): out->el_option = EL_DELAYED; break; case CSH_LOOKUP("heuristic"): out->el_option = EL_HEURISTIC; break; default: ilog(LOG_WARN, "Unknown 'endpoint-learning' flag encountered: '" STR_FORMAT "'", STR_FMT(s)); } } #ifdef WITH_TRANSCODING INLINE void ng_t38_option(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(s)) { case CSH_LOOKUP("decode"): out->t38_decode = true; break; case CSH_LOOKUP("force"): out->t38_force = true; break; case CSH_LOOKUP("stop"): out->t38_stop = true; break; case CSH_LOOKUP("no-ecm"): case CSH_LOOKUP("no-ECM"): case CSH_LOOKUP("no ecm"): case CSH_LOOKUP("no ECM"): out->t38_no_ecm = true; break; case CSH_LOOKUP("no-V17"): case CSH_LOOKUP("no-V.17"): case CSH_LOOKUP("no-v17"): case CSH_LOOKUP("no-v.17"): case CSH_LOOKUP("no V17"): case CSH_LOOKUP("no V.17"): case CSH_LOOKUP("no v17"): case CSH_LOOKUP("no v.17"): out->t38_no_v17 = true; break; case CSH_LOOKUP("no-V.27ter"): case CSH_LOOKUP("no-V27ter"): case CSH_LOOKUP("no-v.27ter"): case CSH_LOOKUP("no-v27ter"): case CSH_LOOKUP("no V.27ter"): case CSH_LOOKUP("no V27ter"): case CSH_LOOKUP("no v.27ter"): case CSH_LOOKUP("no v27ter"): out->t38_no_v27ter = true; break; case CSH_LOOKUP("no-V29"): case CSH_LOOKUP("no-V.29"): case CSH_LOOKUP("no-v29"): case CSH_LOOKUP("no-v.29"): case CSH_LOOKUP("no V29"): case CSH_LOOKUP("no V.29"): case CSH_LOOKUP("no v29"): case CSH_LOOKUP("no v.29"): out->t38_no_v29 = true; break; case CSH_LOOKUP("no-V34"): case CSH_LOOKUP("no-V.34"): case CSH_LOOKUP("no-v34"): case CSH_LOOKUP("no-v.34"): case CSH_LOOKUP("no V34"): case CSH_LOOKUP("no V.34"): case CSH_LOOKUP("no v34"): case CSH_LOOKUP("no v.34"): out->t38_no_v34 = true; break; case CSH_LOOKUP("no-IAF"): case CSH_LOOKUP("no-iaf"): case CSH_LOOKUP("no IAF"): case CSH_LOOKUP("no iaf"): out->t38_no_iaf = true; break; case CSH_LOOKUP("FEC"): case CSH_LOOKUP("fec"): out->t38_fec = true; break; default: ilog(LOG_WARN, "Unknown 'T.38' flag encountered: '" STR_FORMAT "'", STR_FMT(s)); } } #endif static void call_ng_flags_list(const ng_parser_t *parser, parser_arg list, void (*str_callback)(str *, unsigned int, helper_arg), void (*item_callback)(const ng_parser_t *, parser_arg, helper_arg), helper_arg arg) { str s; if (!parser->is_list(list)) { if (parser->get_str(list, &s)) { str token; while (str_token_sep(&token, &s, ',')) str_callback(&token, 0, arg); } else ilog(LOG_DEBUG, "Ignoring non-list non-string value"); return; } parser->list_iter(parser, list, str_callback, item_callback, arg); } static void call_ng_flags_str_list(const ng_parser_t *parser, parser_arg list, void (*callback)(str *, unsigned int, helper_arg), helper_arg arg) { call_ng_flags_list(parser, list, callback, NULL, arg); } static void call_ng_flags_rtcp_mux(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(s)) { case CSH_LOOKUP("accept"): out->rtcp_mux_accept = true; break; case CSH_LOOKUP("demux"): out->rtcp_mux_demux = true; break; case CSH_LOOKUP("offer"): out->rtcp_mux_offer = true; break; case CSH_LOOKUP("reject"): out->rtcp_mux_reject = true; break; case CSH_LOOKUP("require"): out->rtcp_mux_require = true; break; default: ilog(LOG_WARN, "Unknown 'rtcp-mux' flag encountered: '" STR_FORMAT "'", STR_FMT(s)); } } static void call_ng_flags_moh(const ng_parser_t *parser, str *key, parser_arg value, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(key)) { case CSH_LOOKUP("db-id"): out->moh_db_id = parser->get_int_str(value, out->moh_db_id); break; case CSH_LOOKUP("blob"): parser->get_str(value, &out->moh_blob); break; case CSH_LOOKUP("file"): parser->get_str(value, &out->moh_file); break; case CSH_LOOKUP("connection"):; str connection = STR_NULL; parser->get_str(value, &connection); if (!str_cmp(&connection, "zero")) out->moh_zero_connection = true; break; case CSH_LOOKUP("mode"):; str mode = STR_NULL; parser->get_str(value, &mode); if (!str_cmp(&mode, "sendrecv")) out->moh_sendrecv = true; else if (!str_cmp(&mode, "reflect")) out->moh_reflect = true; break; default: ilog(LOG_WARN, "Unknown 'moh' flag encountered: '" STR_FORMAT "'", STR_FMT(key)); } } static void call_ng_flags_replace(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(s)) { case CSH_LOOKUP("force-increment-sdp-ver"): case CSH_LOOKUP("force-increment-SDP-ver"): case CSH_LOOKUP("force increment sdp ver"): case CSH_LOOKUP("force increment SDP ver"): out->force_inc_sdp_ver = true; break; case CSH_LOOKUP("origin"): out->replace_origin = true; break; case CSH_LOOKUP("origin full"): case CSH_LOOKUP("origin-full"): case CSH_LOOKUP("origin_full"): out->replace_origin_full = true; break; case CSH_LOOKUP("sdp-version"): case CSH_LOOKUP("SDP-version"): case CSH_LOOKUP("sdp version"): case CSH_LOOKUP("SDP version"): out->replace_sdp_version = true; break; /* TODO: after a while remove silent support for this flag */ case CSH_LOOKUP("session-connection"): case CSH_LOOKUP("session connection"): ilog(LOG_INFO, "replace-session-connection flag encountered, but not supported anymore."); break; case CSH_LOOKUP("session-name"): case CSH_LOOKUP("session name"): out->replace_sess_name = true; break; case CSH_LOOKUP("username"): out->replace_username = true; break; case CSH_LOOKUP("zero-address"): case CSH_LOOKUP("zero address"): out->replace_zero_address = true; break; default: ilog(LOG_WARN, "Unknown 'replace' flag encountered: '" STR_FORMAT "'", STR_FMT(s)); } } static void call_ng_flags_supports(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; if (!str_cmp(s, "load limit")) out->supports_load_limit = true; else ilog(LOG_INFO | LOG_FLAG_LIMIT, "Optional feature '" STR_FORMAT "' not supported", STR_FMT(s)); } static str *str_dup_escape(const str *s) { str *ret = str_dup(s); int i; while ((i = str_str(ret, "--")) >= 0) { ret->s[i] = '='; memmove(&ret->s[i + 1], &ret->s[i + 2], ret->len - i - 2); ret->len--; } while ((i = str_str(ret, "..")) >= 0) { ret->s[i] = ' '; memmove(&ret->s[i + 1], &ret->s[i + 2], ret->len - i - 2); ret->len--; } return ret; } static void call_ng_flags_esc_str_list(str *s, unsigned int idx, helper_arg arg) { str *s_copy = str_dup_escape(s); t_queue_push_tail(arg.q, s_copy); } /** * Stores flag's value in the given GhashTable. */ static void call_ng_flags_str_ht(str *s, unsigned int idx, helper_arg arg) { str *s_copy = str_dup_escape(s); str_case_ht *ht = arg.sct; if (!t_hash_table_is_set(*ht)) *ht = str_case_ht_new(); t_hash_table_replace(*ht, s_copy, s_copy); } /** * Parses one-row flags separated by 'delimiter'. * Stores parsed flag's values then in the given GQueue. */ static void call_ng_flags_str_q_multi(str *s, unsigned int idx, helper_arg arg) { str *s_copy = str_dup_escape(s); str token; str_q *q = arg.q; if (s_copy->len == 0) ilog(LOG_DEBUG, "Hm, nothing to parse."); while (str_token_sep(&token, s_copy, ';')) { str * ret = str_dup(&token); t_queue_push_tail(q, ret); } free(s_copy); } #ifdef WITH_TRANSCODING static void call_ng_flags_str_ht_split(str *s, unsigned int idx, helper_arg arg) { str_case_value_ht *ht = arg.svt; if (!t_hash_table_is_set(*ht)) *ht = str_case_value_ht_new(); str splitter = *s; while (1) { t_hash_table_replace(*ht, str_dup_escape(&splitter), str_dup_escape(s)); char *c = memrchr(splitter.s, '/', splitter.len); if (!c) break; splitter.len = c - splitter.s; } } #endif static struct sdp_manipulations *call_ng_flags_sdp_attr_helper(str *s, sdp_ng_flags *flags) { // get media type str token; if (!str_token(&token, s, '-')) return NULL; struct sdp_manipulations *sm = sdp_manipulations_get_by_name(flags->sdp_manipulations, &token); if (!sm) { ilog(LOG_WARN, "SDP manipulations: unsupported SDP section '" STR_FORMAT "' targeted.", STR_FMT(&token)); return NULL; } return sm; } static void call_ng_flags_sdp_attr_helper_add(str *s, unsigned int idx, helper_arg arg) { struct sdp_manipulations *sm = call_ng_flags_sdp_attr_helper(s, arg.flags); if (!sm) return; call_ng_flags_esc_str_list(s, idx, &sm->add_commands); } static void call_ng_flags_sdp_attr_helper_remove(str *s, unsigned int idx, helper_arg arg) { struct sdp_manipulations *sm = call_ng_flags_sdp_attr_helper(s, arg.flags); if (!sm) return; call_ng_flags_str_ht(s, idx, &sm->rem_commands); } static void call_ng_flags_sdp_attr_helper_subst(str *s, unsigned int idx, helper_arg arg) { struct sdp_manipulations *sm = call_ng_flags_sdp_attr_helper(s, arg.flags); if (!sm) return; call_ng_flags_str_pair_ht(s, idx, &sm->subst_commands); } // helper to alias values from other dictionaries into the "flags" dictionary INLINE int call_ng_flags_prefix(str *s_ori, const char *prefix, void (*cb)(str *, unsigned int, helper_arg), helper_arg arg) { size_t len = strlen(prefix); str s = *s_ori; if (len > 0) if (str_shift_cmp(&s, prefix)) return 0; cb(&s, 0, arg); return 1; } void call_ng_flags_flags(str *s, unsigned int idx, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(s)) { case CSH_LOOKUP("all"): out->all = ALL_ALL; break; case CSH_LOOKUP("allow-asymmetric-codecs"): case CSH_LOOKUP("allow-asymmetric-codec"): case CSH_LOOKUP("allow asymmetric codecs"): case CSH_LOOKUP("allow asymmetric codec"): out->allow_asymmetric_codecs = true; break; case CSH_LOOKUP("allow-no-codec-media"): case CSH_LOOKUP("allow-no-codec-medias"): case CSH_LOOKUP("allow-empty-codec-media"): case CSH_LOOKUP("allow-empty-codec-medias"): case CSH_LOOKUP("allow no codec media"): case CSH_LOOKUP("allow no codec medias"): case CSH_LOOKUP("allow empty codec media"): case CSH_LOOKUP("allow empty codec medias"): out->allow_no_codec_media = true; break; case CSH_LOOKUP("allow-transcoding"): case CSH_LOOKUP("allow transcoding"): out->allow_transcoding = true; break; case CSH_LOOKUP("force-transcoding"): case CSH_LOOKUP("force transcoding"): out->force_transcoding = true; break; case CSH_LOOKUP("always-transcode"): case CSH_LOOKUP("always transcode"):; static const str str_all = STR_CONST("all"); call_ng_flags_esc_str_list((str *) &str_all, 0, &out->codec_accept); break; case CSH_LOOKUP("asymmetric"): out->asymmetric = true; break; case CSH_LOOKUP("asymmetric-codecs"): case CSH_LOOKUP("asymmetric codecs"): ilog(LOG_INFO, "Ignoring obsolete flag `asymmetric-codecs`"); break; case CSH_LOOKUP("audio-player"): case CSH_LOOKUP("audio player"): case CSH_LOOKUP("player"): out->audio_player = AP_TRANSCODING; break; case CSH_LOOKUP("block-dtmf"): case CSH_LOOKUP("block-DTMF"): case CSH_LOOKUP("block dtmf"): case CSH_LOOKUP("block DTMF"): out->block_dtmf = true; break; case CSH_LOOKUP("block-egress"): case CSH_LOOKUP("block egress"): out->block_egress = true; break; case CSH_LOOKUP("block-short"): case CSH_LOOKUP("block-shorts"): case CSH_LOOKUP("block-short-packets"): case CSH_LOOKUP("block short"): case CSH_LOOKUP("block shorts"): case CSH_LOOKUP("block short packets"): out->block_short = true; break; case CSH_LOOKUP("debug"): case CSH_LOOKUP("debugging"): out->debug = true; break; case CSH_LOOKUP("detect-DTMF"): case CSH_LOOKUP("detect-dtmf"): case CSH_LOOKUP("detect DTMF"): case CSH_LOOKUP("detect dtmf"): out->detect_dtmf = true; break; case CSH_LOOKUP("directional"): out->directional = true; break; case CSH_LOOKUP("discard-recording"): case CSH_LOOKUP("discard recording"): out->discard_recording = true; break; case CSH_LOOKUP("early-media"): case CSH_LOOKUP("early media"): out->early_media = true; break; case CSH_LOOKUP("egress"): out->egress = true; break; case CSH_LOOKUP("exclude-recording"): case CSH_LOOKUP("exclude recording"): out->exclude_recording = true; break; case CSH_LOOKUP("fatal"): out->fatal = true; break; case CSH_LOOKUP("fragment"): out->fragment = true; break; case CSH_LOOKUP("full-rtcp-attribute"): case CSH_LOOKUP("full-RTCP-attribute"): case CSH_LOOKUP("full rtcp attribute"): case CSH_LOOKUP("full RTCP attribute"): out->full_rtcp_attr = true; break; case CSH_LOOKUP("generate-mid"): case CSH_LOOKUP("generate mid"): out->generate_mid = true; break; case CSH_LOOKUP("generate-RTCP"): case CSH_LOOKUP("generate-rtcp"): case CSH_LOOKUP("generate RTCP"): case CSH_LOOKUP("generate rtcp"): out->generate_rtcp = true; break; case CSH_LOOKUP("ICE-reject"): case CSH_LOOKUP("ice-reject"): case CSH_LOOKUP("reject-ice"): case CSH_LOOKUP("reject-ICE"): case CSH_LOOKUP("ICE reject"): case CSH_LOOKUP("ice reject"): case CSH_LOOKUP("reject ice"): case CSH_LOOKUP("reject ICE"): out->ice_reject = true; break; case CSH_LOOKUP("inactive"): out->inactive = true; break; case CSH_LOOKUP("inject-DTMF"): case CSH_LOOKUP("inject-dtmf"): case CSH_LOOKUP("inject DTMF"): case CSH_LOOKUP("inject dtmf"): out->inject_dtmf = true; break; case CSH_LOOKUP("loop-protect"): case CSH_LOOKUP("loop protect"): out->loop_protect = true; break; case CSH_LOOKUP("media-handover"): case CSH_LOOKUP("media handover"): out->media_handover = true; break; case CSH_LOOKUP("mirror-RTCP"): case CSH_LOOKUP("mirror-rtcp"): case CSH_LOOKUP("RTCP-mirror"): case CSH_LOOKUP("rtcp-mirror"): case CSH_LOOKUP("mirror RTCP"): case CSH_LOOKUP("mirror rtcp"): case CSH_LOOKUP("RTCP mirror"): case CSH_LOOKUP("rtcp mirror"): out->rtcp_mirror = true; break; case CSH_LOOKUP("NAT-wait"): case CSH_LOOKUP("nat-wait"): case CSH_LOOKUP("NAT wait"): case CSH_LOOKUP("nat wait"): out->nat_wait = true; break; case CSH_LOOKUP("new-branch"): case CSH_LOOKUP("new branch"): out->new_branch = true; break; case CSH_LOOKUP("no-codec-renegotiation"): case CSH_LOOKUP("reuse-codecs"): case CSH_LOOKUP("no codec renegotiation"): case CSH_LOOKUP("reuse codecs"): out->reuse_codec = true; break; case CSH_LOOKUP("no-passthrough"): case CSH_LOOKUP("no passthrough"): out->passthrough_off = true; break; case CSH_LOOKUP("no-player"): case CSH_LOOKUP("no-audio-player"): case CSH_LOOKUP("no player"): case CSH_LOOKUP("no audio player"): out->audio_player = AP_OFF; break; case CSH_LOOKUP("no-port-latching"): case CSH_LOOKUP("no port latching"): out->no_port_latching = true; break; case CSH_LOOKUP("no-redis-update"): case CSH_LOOKUP("no redis update"): out->no_redis_update = true; break; case CSH_LOOKUP("no-rtcp-attribute"): case CSH_LOOKUP("no-RTCP-attribute"): case CSH_LOOKUP("no rtcp attribute"): case CSH_LOOKUP("no RTCP attribute"): out->no_rtcp_attr = true; break; case CSH_LOOKUP("no-jitter-buffer"): case CSH_LOOKUP("no jitter buffer"): out->disable_jb = true; break; case CSH_LOOKUP("original-sendrecv"): case CSH_LOOKUP("original sendrecv"): out->original_sendrecv = true; break; case CSH_LOOKUP("pad-crypto"): case CSH_LOOKUP("pad crypto"): out->sdes_pad = true; break; case CSH_LOOKUP("passthrough"): out->passthrough_on = true; break; case CSH_LOOKUP("pierce-NAT"): case CSH_LOOKUP("pierce-nat"): case CSH_LOOKUP("pierce NAT"): case CSH_LOOKUP("pierce nat"): out->pierce_nat = true; break; case CSH_LOOKUP("port-latching"): case CSH_LOOKUP("port latching"): out->port_latching = true; break; case CSH_LOOKUP("provisional"): out->provisional = true; break; case CSH_LOOKUP("record-call"): case CSH_LOOKUP("record call"): out->record_call = true; break; case CSH_LOOKUP("recording-vsc"): case CSH_LOOKUP("recording-VSC"): case CSH_LOOKUP("recording vsc"): case CSH_LOOKUP("recording VSC"): out->recording_vsc = true; break; case CSH_LOOKUP("recording-announcement"): case CSH_LOOKUP("recording announcement"): out->recording_announcement = true; break; case CSH_LOOKUP("recrypt"): out->recrypt = true; break; case CSH_LOOKUP("reorder-codecs"): case CSH_LOOKUP("reorder codecs"): ilog(LOG_INFO, "Ignoring obsolete flag `reorder-codecs`"); break; case CSH_LOOKUP("reset"): out->reset = true; break; case CSH_LOOKUP("single-codec"): case CSH_LOOKUP("single codec"): out->single_codec = true; break; case CSH_LOOKUP("SIP-source-address"): case CSH_LOOKUP("sip-source-address"): case CSH_LOOKUP("SIP source address"): case CSH_LOOKUP("sip source address"): out->trust_address = 0; break; case CSH_LOOKUP("SIPREC"): case CSH_LOOKUP("siprec"): out->siprec = true; break; case CSH_LOOKUP("skip-recording-db"): case CSH_LOOKUP("skip-recording-database"): case CSH_LOOKUP("skip recording db"): case CSH_LOOKUP("skip recording database"): out->skip_recording_db = true; break; case CSH_LOOKUP("static-codec"): case CSH_LOOKUP("static-codecs"): case CSH_LOOKUP("static codec"): case CSH_LOOKUP("static codecs"): out->static_codecs = true; break; case CSH_LOOKUP("strict-source"): case CSH_LOOKUP("strict source"): out->strict_source = true; break; case CSH_LOOKUP("strip-extmap"): case CSH_LOOKUP("strip extmap"): out->strip_extmap = true; break; case CSH_LOOKUP("symmetric-codecs"): case CSH_LOOKUP("symmetric codecs"): ilog(LOG_INFO, "Ignoring obsolete flag `symmetric-codecs`"); break; case CSH_LOOKUP("to tag"): case CSH_LOOKUP("to-tag"): case CSH_LOOKUP("to_tag"): /* including the “To†tag in the “delete†message allows to be more selective * about monologues within a dialog to be torn down. */ out->to_tag_flag = true; break; case CSH_LOOKUP("trickle-ICE"): case CSH_LOOKUP("trickle-ice"): case CSH_LOOKUP("trickle ICE"): case CSH_LOOKUP("trickle ice"): out->trickle_ice = true; break; case CSH_LOOKUP("trust-address"): case CSH_LOOKUP("trust address"): out->trust_address = true; break; case CSH_LOOKUP("unidirectional"): out->unidirectional = true; break; case CSH_LOOKUP("webrtc"): case CSH_LOOKUP("webRTC"): case CSH_LOOKUP("WebRTC"): case CSH_LOOKUP("WebRtc"): ng_flags_webrtc(out); break; default: /* handle values aliases from other dictionaries */ if (call_ng_flags_prefix(s, "endpoint-learning-", ng_el_option, out)) return; if (call_ng_flags_prefix(s, "from-tags-", call_ng_flags_esc_str_list, &out->from_tags)) return; /* OSRTP */ if (call_ng_flags_prefix(s, "OSRTP-", ng_osrtp_option, out)) return; /* replacing SDP body parts */ if (call_ng_flags_prefix(s, "replace-", call_ng_flags_replace, out)) return; /* rtcp-mux */ if (call_ng_flags_prefix(s, "rtcp-mux-", call_ng_flags_rtcp_mux, out)) return; /* codec manipulations */ { if (call_ng_flags_prefix(s, "codec-except-", call_ng_flags_str_ht, &out->codec_except)) return; if (call_ng_flags_prefix(s, "codec-offer-", call_ng_flags_esc_str_list, &out->codec_offer)) return; if (call_ng_flags_prefix(s, "codec-strip-", call_ng_flags_esc_str_list, &out->codec_strip)) return; if (call_ng_flags_prefix(s, "codec-ignore-", call_ng_flags_esc_str_list, &out->codec_ignore)) return; } /* SDES */ { if (call_ng_flags_prefix(s, "SDES-", ng_sdes_option, out)) return; if (call_ng_flags_prefix(s, "SDES-offerer_pref:", call_ng_flags_str_q_multi, &out->sdes_offerer_pref)) return; if (call_ng_flags_prefix(s, "SDES-no-", call_ng_flags_str_ht, &out->sdes_no)) return; if (call_ng_flags_prefix(s, "SDES-only-", call_ng_flags_str_ht, &out->sdes_only)) return; if (call_ng_flags_prefix(s, "SDES-order:", call_ng_flags_str_q_multi, &out->sdes_order)) return; } /* SDP attributes manipulations */ { if (call_ng_flags_prefix(s, "sdp-attr-add-", call_ng_flags_sdp_attr_helper_add, out)) return; if (call_ng_flags_prefix(s, "sdp-attr-remove-", call_ng_flags_sdp_attr_helper_remove, out)) return; if (call_ng_flags_prefix(s, "sdp-attr-substitute-", call_ng_flags_sdp_attr_helper_subst, out)) return; } #ifdef WITH_TRANSCODING /* transcoding */ { if (out->opmode == OP_OFFER || out->opmode == OP_SUBSCRIBE_REQ || out->opmode == OP_PUBLISH) { if (call_ng_flags_prefix(s, "transcode-", call_ng_flags_esc_str_list, &out->codec_transcode)) return; if (call_ng_flags_prefix(s, "codec-transcode-", call_ng_flags_esc_str_list, &out->codec_transcode)) return; if (call_ng_flags_prefix(s, "codec-mask-", call_ng_flags_esc_str_list, &out->codec_mask)) return; if (call_ng_flags_prefix(s, "T38-", ng_t38_option, out)) return; if (call_ng_flags_prefix(s, "T.38-", ng_t38_option, out)) return; } if (call_ng_flags_prefix(s, "codec-accept-", call_ng_flags_esc_str_list, &out->codec_accept)) return; if (call_ng_flags_prefix(s, "codec-consume-", call_ng_flags_esc_str_list, &out->codec_consume)) return; if (call_ng_flags_prefix(s, "codec-set-", call_ng_flags_str_ht_split, &out->codec_set)) return; } #endif ilog(LOG_WARN, "Unknown flag encountered: '" STR_FORMAT "'", STR_FMT(s)); } } void call_ng_flags_init(sdp_ng_flags *out, enum ng_opmode opmode) { ZERO(*out); out->opmode = opmode; out->trust_address = trust_address_def; out->dtls_passive = dtls_passive_def; out->dtls_reverse_passive = dtls_passive_def; out->el_option = rtpe_config.endpoint_learning; out->tos = 256; out->delay_buffer = -1; out->delete_delay = -1; out->volume = 9999; out->digit = -1; out->repeat_duration = -1; out->frequencies = g_array_new(false, false, sizeof(int)); for (int i = 0; i < __MT_MAX; ++i) out->sdp_media_remove[i] = false; out->t38_version = -1; } static void call_ng_direction_flag_iter(str *s, unsigned int i, helper_arg arg) { if (i >= 2) return; arg.flags->direction[i] = *s; } void call_ng_direction_flag(const ng_parser_t *parser, sdp_ng_flags *flags, parser_arg value) { if (!parser->is_list(value)) return; parser->list_iter(parser, value, call_ng_direction_flag_iter, NULL, flags); } void call_ng_codec_flags(const ng_parser_t *parser, str *key, parser_arg value, helper_arg arg) { sdp_ng_flags *out = arg.flags; switch (__csh_lookup(key)) { case CSH_LOOKUP("except"): call_ng_flags_str_list(parser, value, call_ng_flags_str_ht, &out->codec_except); return; case CSH_LOOKUP("offer"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_offer); return; case CSH_LOOKUP("strip"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_strip); return; case CSH_LOOKUP("ignore"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_ignore); return; } #ifdef WITH_TRANSCODING if (out->opmode == OP_OFFER || out->opmode == OP_SUBSCRIBE_REQ || out->opmode == OP_PUBLISH || out->opmode == OP_PLAY_MEDIA) { switch (__csh_lookup(key)) { case CSH_LOOKUP("accept"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_accept); return; case CSH_LOOKUP("consume"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_consume); return; case CSH_LOOKUP("mask"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_mask); return; case CSH_LOOKUP("set"): call_ng_flags_str_list(parser, value, call_ng_flags_str_ht_split, &out->codec_set); return; case CSH_LOOKUP("transcode"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->codec_transcode); return; } } else { // silence warnings switch (__csh_lookup(key)) { case CSH_LOOKUP("accept"): case CSH_LOOKUP("consume"): case CSH_LOOKUP("mask"): case CSH_LOOKUP("set"): case CSH_LOOKUP("transcode"): return; } } #endif ilog(LOG_WARN, "Unknown 'codec' operation encountered: '" STR_FORMAT "'", STR_FMT(key)); } #ifdef WITH_TRANSCODING static void call_ng_parse_block_mode(str *s, enum block_dtmf_mode *output) { switch (__csh_lookup(s)) { case CSH_LOOKUP("drop"): *output = BLOCK_DTMF_DROP; break; case CSH_LOOKUP("DTMF"): case CSH_LOOKUP("dtmf"): *output = BLOCK_DTMF_DTMF; break; case CSH_LOOKUP("off"): *output = BLOCK_DTMF_OFF; break; case CSH_LOOKUP("random"): *output = BLOCK_DTMF_RANDOM; break; case CSH_LOOKUP("silence"): *output = BLOCK_DTMF_SILENCE; break; case CSH_LOOKUP("tone"): *output = BLOCK_DTMF_TONE; break; case CSH_LOOKUP("zero"): *output = BLOCK_DTMF_ZERO; break; default: ilog(LOG_WARN, "Unknown DTMF block mode encountered: '" STR_FORMAT "'", STR_FMT(s)); } } #endif static void call_ng_flags_freqs(const ng_parser_t *parser, parser_arg value, sdp_ng_flags *out); static void call_ng_flags_freqs_iter(const ng_parser_t *parser, parser_arg item, helper_arg arg) { call_ng_flags_freqs(parser, item, arg.flags); } static void call_ng_flags_freqs(const ng_parser_t *parser, parser_arg value, sdp_ng_flags *out) { unsigned int val; if (parser->is_int(value)) { val = parser->get_int(value); g_array_append_val(out->frequencies, val); } else if (parser->is_list(value)) parser->list_iter(parser, value, NULL, call_ng_flags_freqs_iter, out); else { val = parser->get_int_str(value, 0); if (val) g_array_append_val(out->frequencies, val); else ilog(LOG_WARN, "Invalid content type in `frequencies` list"); } } static void call_ng_received_from_string(sdp_ng_flags *flags, str *s) { flags->received_from_family = STR_NULL; flags->received_from_address = *s; } static void call_ng_received_from_iter(str *key, unsigned int i, helper_arg arg) { switch (i) { case 0: arg.flags->received_from_family = *key; break; case 1: arg.flags->received_from_address = *key; break; } } static void call_ng_payload_type(const ng_parser_t *parser, str *key, parser_arg value, struct rtp_payload_type *pt) { str s = STR_NULL; parser->get_str(value, &s); switch (__csh_lookup(key)) { case CSH_LOOKUP("codec"): pt->encoding = s; break; case CSH_LOOKUP("payload type"): pt->payload_type = parser->get_int_str(value, -1); break; case CSH_LOOKUP("clock rate"): pt->clock_rate = parser->get_int_str(value, 0); break; case CSH_LOOKUP("channels"): pt->channels = parser->get_int_str(value, 0); break; case CSH_LOOKUP("format"): pt->format_parameters = s; break; case CSH_LOOKUP("options"): pt->codec_opts = s; break; default: ilog(LOG_WARN, "Unknown payload type key '" STR_FORMAT "'", STR_FMT(key)); } } static void call_ng_codec(const ng_parser_t *parser, str *key, parser_arg value, struct ng_codec *codec) { switch (__csh_lookup(key)) { case CSH_LOOKUP("input"): parser->dict_iter(parser, value, call_ng_payload_type, &codec->input); break; case CSH_LOOKUP("output"): parser->dict_iter(parser, value, call_ng_payload_type, &codec->output); break; default: ilog(LOG_WARN, "Unknown codec key '" STR_FORMAT "'", STR_FMT(key)); } } static void call_ng_codec_iter(const ng_parser_t *parser, parser_arg item, struct ng_media *media) { __auto_type codec = g_new0(struct ng_codec, 1); t_queue_push_tail(&media->codecs, codec); codec->input.payload_type = -1; codec->output.payload_type = -1; parser->dict_iter(parser, item, call_ng_codec, codec); if (codec->input.payload_type == -1 || codec->output.payload_type == -1) ilog(LOG_WARN, "Incomplete codec definition"); } static void call_ng_endpoint(const ng_parser_t *parser, str *key, parser_arg value, struct ng_media *media) { str s = STR_NULL; parser->get_str(value, &s); switch (__csh_lookup(key)) { case CSH_LOOKUP("address"): media->destination_address = s; break; case CSH_LOOKUP("family"): case CSH_LOOKUP("address-family"): case CSH_LOOKUP("address family"): media->destination.address.family = get_socket_family_rfc(&s); break; case CSH_LOOKUP("port"): media->destination.port = parser->get_int_str(value, 0); break; default: ilog(LOG_WARN, "Unknown endpoint key '" STR_FORMAT "'", STR_FMT(key)); } } static void call_ng_media(const ng_parser_t *parser, str *key, parser_arg value, struct ng_media *media) { str s = STR_NULL; parser->get_str(value, &s); switch (__csh_lookup(key)) { case CSH_LOOKUP("codec"): parser->list_iter(parser, value, NULL, call_ng_codec_iter, media); break; case CSH_LOOKUP("destination"): parser->dict_iter(parser, value, call_ng_endpoint, media); if (!media->destination.address.family) ilog(LOG_ERR, "Destination address without family specified"); else if (!sockaddr_parse_str(&media->destination.address, media->destination.address.family, &media->destination_address)) ilog(LOG_ERR, "Failed to parse destination address '" STR_FORMAT "'", STR_FMT(&media->destination_address)); break; case CSH_LOOKUP("id"): media->id = s; break; case CSH_LOOKUP("type"): media->type = s; break; default: ilog(LOG_WARN, "Unknown media key '" STR_FORMAT "'", STR_FMT(key)); } } static void call_ng_media_iter(const ng_parser_t *parser, parser_arg item, sdp_ng_flags *out) { __auto_type media = g_new0(struct ng_media, 1); t_queue_push_tail(&out->medias, media); parser->dict_iter(parser, item, call_ng_media, media); } void call_ng_main_flags(const ng_parser_t *parser, str *key, parser_arg value, helper_arg arg) { str s = STR_NULL; sdp_ng_flags *out = arg.flags; parser->get_str(value, &s); switch (__csh_lookup(key)) { case CSH_LOOKUP("address"): out->address = s; break; case CSH_LOOKUP("address family"): case CSH_LOOKUP("address-family"): if (s.s) { out->address_family_str = s; out->address_family = get_socket_family_rfc(&out->address_family_str); } break; case CSH_LOOKUP("all"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "all"): out->all = ALL_ALL; break; case CSH_LOOKUP_N(1, "none"): out->all = ALL_NONE; break; case CSH_LOOKUP_N(1, "offer-answer"): out->all = ALL_OFFER_ANSWER; break; case CSH_LOOKUP_N(1, "not-offer-answer"): case CSH_LOOKUP_N(1, "non-offer-answer"): case CSH_LOOKUP_N(1, "except-offer-answer"): out->all = ALL_NON_OFFER_ANSWER; break; case CSH_LOOKUP_N(1, "flows"): out->all = ALL_FLOWS; break; default: ilog(LOG_WARN, "Unknown 'all' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("audio-player"): case CSH_LOOKUP("player"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "default"): out->audio_player = AP_DEFAULT; break; case CSH_LOOKUP_N(1, "on"): case CSH_LOOKUP_N(1, "yes"): case CSH_LOOKUP_N(1, "enable"): case CSH_LOOKUP_N(1, "enabled"): case CSH_LOOKUP_N(1, "transcode"): case CSH_LOOKUP_N(1, "transcoding"): out->audio_player = AP_TRANSCODING; break; case CSH_LOOKUP_N(1, "no"): case CSH_LOOKUP_N(1, "off"): case CSH_LOOKUP_N(1, "disable"): case CSH_LOOKUP_N(1, "disabled"): out->audio_player = AP_OFF; break; case CSH_LOOKUP_N(1, "force"): case CSH_LOOKUP_N(1, "forced"): case CSH_LOOKUP_N(1, "always"): case CSH_LOOKUP_N(1, "everything"): out->audio_player = AP_FORCE; break; default: ilog(LOG_WARN, "Unknown 'audio-player' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("blob"): out->blob = s; break; case CSH_LOOKUP("call-id"): case CSH_LOOKUP("call-ID"): case CSH_LOOKUP("call id"): case CSH_LOOKUP("call ID"): out->call_id = s; break; case CSH_LOOKUP("code"): case CSH_LOOKUP("digit"): out->digit = parser->get_int_str(value, out->digit); if (s.len == 1) out->digit = s.s[0]; break; case CSH_LOOKUP("codec"): parser->dict_iter(parser, value, call_ng_codec_flags, out); break; case CSH_LOOKUP("command"): break; case CSH_LOOKUP("db-id"): out->db_id = parser->get_int_str(value, out->db_id); break; case CSH_LOOKUP("delete delay"): case CSH_LOOKUP("delete-delay"): case CSH_LOOKUP("delete_delay"): out->delete_delay = parser->get_int_str(value, out->delete_delay); break; case CSH_LOOKUP("direction"): call_ng_direction_flag(parser, out, value); break; case CSH_LOOKUP("drop-traffic"): case CSH_LOOKUP("drop traffic"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "start"): out->drop_traffic_start = true; break; case CSH_LOOKUP_N(1, "stop"): out->drop_traffic_stop = true; break; default: ilog(LOG_WARN, "Unknown 'drop-traffic' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("DTLS"): case CSH_LOOKUP("dtls"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "passive"): out->dtls_passive = true; break; case CSH_LOOKUP_N(1, "active"): out->dtls_passive = 0; break; case CSH_LOOKUP_N(1, "no"): case CSH_LOOKUP_N(1, "off"): case CSH_LOOKUP_N(1, "disabled"): case CSH_LOOKUP_N(1, "disable"): out->dtls_off = true; break; default: ilog(LOG_WARN, "Unknown 'DTLS' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("DTLS fingerprint"): case CSH_LOOKUP("DTLS-fingerprint"): case CSH_LOOKUP("dtls fingerprint"): case CSH_LOOKUP("dtls-fingerprint"): out->dtls_fingerprint = s; break; case CSH_LOOKUP("DTLS-reverse"): case CSH_LOOKUP("dtls-reverse"): case CSH_LOOKUP("DTLS reverse"): case CSH_LOOKUP("dtls reverse"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "passive"): out->dtls_reverse_passive = true; break; case CSH_LOOKUP_N(1, "active"): out->dtls_reverse_passive = 0; break; default: ilog(LOG_WARN, "Unknown 'DTLS-reverse' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("DTMF-delay"): case CSH_LOOKUP("DTMF delay"): case CSH_LOOKUP("dtmf-delay"): case CSH_LOOKUP("dtmf delay"): out->dtmf_delay = parser->get_int_str(value, out->dtmf_delay); break; case CSH_LOOKUP("dtmf-log-dest"): case CSH_LOOKUP("DTMF-log-dest"): case CSH_LOOKUP("dtmf-log-destination"): case CSH_LOOKUP("DTMF-log-destination"): if (!endpoint_parse_any_str(&out->dtmf_log_dest, &s)) ilog(LOG_WARN, "Failed to parse 'dtmf-log-dest' address '" STR_FORMAT "'", STR_FMT(&s)); break; case CSH_LOOKUP("duration"): out->duration = parser->get_int_str(value, out->duration); break; #ifdef WITH_TRANSCODING case CSH_LOOKUP("DTMF-security"): case CSH_LOOKUP("dtmf-security"): case CSH_LOOKUP("DTMF security"): case CSH_LOOKUP("dtmf security"): call_ng_parse_block_mode(&s, &out->block_dtmf_mode); break; case CSH_LOOKUP("DTMF-security-trigger"): case CSH_LOOKUP("dtmf-security-trigger"): case CSH_LOOKUP("DTMF security trigger"): case CSH_LOOKUP("dtmf security trigger"): call_ng_parse_block_mode(&s, &out->block_dtmf_mode_trigger); break; case CSH_LOOKUP("DTMF-security-trigger-end"): case CSH_LOOKUP("dtmf-security-trigger-end"): case CSH_LOOKUP("DTMF security trigger end"): case CSH_LOOKUP("dtmf security trigger end"): call_ng_parse_block_mode(&s, &out->block_dtmf_mode_trigger_end); break; case CSH_LOOKUP("delay-buffer"): case CSH_LOOKUP("delay buffer"): out->delay_buffer = parser->get_int_str(value, out->delay_buffer); break; #endif case CSH_LOOKUP("endpoint-learning"): case CSH_LOOKUP("endpoint learning"): call_ng_flags_str_list(parser, value, ng_el_option, out); break; case CSH_LOOKUP("file"): out->file = s; break; case CSH_LOOKUP("frequency"): case CSH_LOOKUP("frequencies"): call_ng_flags_freqs(parser, value, out); break; case CSH_LOOKUP("from-interface"): out->direction[0] = s; break; case CSH_LOOKUP("from-label"): case CSH_LOOKUP("label"): out->label = s; break; case CSH_LOOKUP("from-tag"): out->from_tag = s; break; case CSH_LOOKUP("from-tags"): call_ng_flags_str_list(parser, value, call_ng_flags_esc_str_list, &out->from_tags); break; case CSH_LOOKUP("flags"): call_ng_flags_str_list(parser, value, call_ng_flags_flags, out); break; case CSH_LOOKUP("generate RTCP"): case CSH_LOOKUP("generate-RTCP"): case CSH_LOOKUP("generate rtcp"): case CSH_LOOKUP("generate-rtcp"): if (!str_cmp(&s, "on")) out->generate_rtcp = true; else if (!str_cmp(&s, "off")) out->generate_rtcp_off = true; break; case CSH_LOOKUP("ICE"): case CSH_LOOKUP("ice"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "remove"): out->ice_option = ICE_REMOVE; break; case CSH_LOOKUP_N(1, "force"): out->ice_option = ICE_FORCE; break; case CSH_LOOKUP_N(1, "default"): out->ice_option = ICE_DEFAULT; break; case CSH_LOOKUP_N(1, "optional"): out->ice_option = ICE_OPTIONAL; break; case CSH_LOOKUP_N(1, "force_relay"): case CSH_LOOKUP_N(1, "force-relay"): case CSH_LOOKUP_N(1, "force relay"): out->ice_option = ICE_FORCE_RELAY; break; default: ilog(LOG_WARN, "Unknown 'ICE' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("ICE-lite"): case CSH_LOOKUP("ice-lite"): case CSH_LOOKUP("ICE lite"): case CSH_LOOKUP("ice lite"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "off"): case CSH_LOOKUP_N(1, "none"): case CSH_LOOKUP_N(1, "no"): out->ice_lite_option = ICE_LITE_OFF; break; case CSH_LOOKUP_N(1, "forward"): case CSH_LOOKUP_N(1, "offer"): case CSH_LOOKUP_N(1, "fwd"): case CSH_LOOKUP_N(1, "fw"): out->ice_lite_option = ICE_LITE_FWD; break; case CSH_LOOKUP_N(1, "backward"): case CSH_LOOKUP_N(1, "backwards"): case CSH_LOOKUP_N(1, "reverse"): case CSH_LOOKUP_N(1, "answer"): case CSH_LOOKUP_N(1, "back"): case CSH_LOOKUP_N(1, "bkw"): case CSH_LOOKUP_N(1, "bk"): out->ice_lite_option = ICE_LITE_BKW; break; case CSH_LOOKUP_N(1, "both"): out->ice_lite_option = ICE_LITE_BOTH; break; default: ilog(LOG_WARN, "Unknown 'ICE-lite' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("interface"): out->interface = s; break; case CSH_LOOKUP("instance"): out->instance = s; break; case CSH_LOOKUP("media address"): case CSH_LOOKUP("media-address"): if (!sockaddr_parse_any_str(&out->media_address, &s)) ilog(LOG_WARN, "Could not parse 'media-address'"); break; case CSH_LOOKUP("media"): parser->list_iter(parser, value, NULL, call_ng_media_iter, out); break; case CSH_LOOKUP("media echo"): case CSH_LOOKUP("media-echo"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "blackhole"): case CSH_LOOKUP_N(1, "sinkhole"): out->media_echo = MEO_BLACKHOLE; break; case CSH_LOOKUP_N(1, "forward"): case CSH_LOOKUP_N(1, "fwd"): case CSH_LOOKUP_N(1, "fw"): out->media_echo = MEO_FWD; break; case CSH_LOOKUP_N(1, "backward"): case CSH_LOOKUP_N(1, "backwards"): case CSH_LOOKUP_N(1, "reverse"): case CSH_LOOKUP_N(1, "back"): case CSH_LOOKUP_N(1, "bkw"): case CSH_LOOKUP_N(1, "bk"): out->media_echo = MEO_BKW; break; case CSH_LOOKUP_N(1, "both"): out->media_echo = MEO_BOTH; break; default: ilog(LOG_WARN, "Unknown 'media-echo' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("metadata"): out->metadata = s; break; case CSH_LOOKUP("moh"): case CSH_LOOKUP("MoH"): case CSH_LOOKUP("MOH"): parser->dict_iter(parser, value, call_ng_flags_moh, out); break; case CSH_LOOKUP("OSRTP"): case CSH_LOOKUP("osrtp"): call_ng_flags_str_list(parser, value, ng_osrtp_option, out); break; case CSH_LOOKUP("output-destination"): case CSH_LOOKUP("output-dest"): case CSH_LOOKUP("output-file"): case CSH_LOOKUP("recording-destination"): case CSH_LOOKUP("recording-dest"): case CSH_LOOKUP("recording-file"): case CSH_LOOKUP("output destination"): case CSH_LOOKUP("output dest"): case CSH_LOOKUP("output file"): case CSH_LOOKUP("recording destination"): case CSH_LOOKUP("recording dest"): case CSH_LOOKUP("recording file"): out->recording_file = s; break; case CSH_LOOKUP("recording-media-slot-offer"): // This needs to be > 0 //out->media_rec_slot_offer = bencode_get_integer_str(value, out->media_rec_slot_offer); out->media_rec_slot_offer = parser->get_int_str(value, out->media_rec_slot_offer); break; case CSH_LOOKUP("recording-media-slot-answer"): // This needs to be > 0 out->media_rec_slot_answer = parser->get_int_str(value, out->media_rec_slot_answer); break; case CSH_LOOKUP("recording-media-slots"): out->media_rec_slots = parser->get_int_str(value, out->media_rec_slots); break; case CSH_LOOKUP("passthrough"): case CSH_LOOKUP("passthru"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "on"): case CSH_LOOKUP_N(1, "yes"): case CSH_LOOKUP_N(1, "enable"): case CSH_LOOKUP_N(1, "enabled"): out->passthrough_on = true; break; case CSH_LOOKUP_N(1, "no"): case CSH_LOOKUP_N(1, "off"): case CSH_LOOKUP_N(1, "disable"): case CSH_LOOKUP_N(1, "disabled"): out->passthrough_off = true; break; default: ilog(LOG_WARN, "Unknown 'passthrough' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("pause"): out->pause = parser->get_int_str(value, out->pause); break; case CSH_LOOKUP("ptime"): if (out->opmode == OP_OFFER) out->ptime = parser->get_int_str(value, 0); break; case CSH_LOOKUP("ptime-reverse"): case CSH_LOOKUP("ptime reverse"): case CSH_LOOKUP("reverse ptime"): case CSH_LOOKUP("reverse-ptime"): if (out->opmode == OP_OFFER) out->rev_ptime = parser->get_int_str(value, 0); break; case CSH_LOOKUP("received from"): case CSH_LOOKUP("received-from"): if (!parser->is_list(value)) { call_ng_received_from_string(out, &s); break; } parser->list_iter(parser, value, call_ng_received_from_iter, NULL, out); break; case CSH_LOOKUP("record call"): case CSH_LOOKUP("record-call"): out->record_call_str = s; break; case CSH_LOOKUP("recording path"): case CSH_LOOKUP("recording dir"): case CSH_LOOKUP("recording directory"): case CSH_LOOKUP("recording folder"): case CSH_LOOKUP("output path"): case CSH_LOOKUP("output dir"): case CSH_LOOKUP("output directory"): case CSH_LOOKUP("output folder"): case CSH_LOOKUP("recording-path"): case CSH_LOOKUP("recording-dir"): case CSH_LOOKUP("recording-directory"): case CSH_LOOKUP("recording-folder"): case CSH_LOOKUP("output-path"): case CSH_LOOKUP("output-dir"): case CSH_LOOKUP("output-directory"): case CSH_LOOKUP("output-folder"): out->recording_path = s; break; case CSH_LOOKUP("recording pattern"): case CSH_LOOKUP("recording-pattern"): case CSH_LOOKUP("output pattern"): case CSH_LOOKUP("output-pattern"): out->recording_pattern = s; break; case CSH_LOOKUP("repeat-times"): out->repeat_times = parser->get_int_str(value, out->repeat_times); break; case CSH_LOOKUP("repeat-duration"): out->repeat_duration = parser->get_int_str(value, out->repeat_duration); break; case CSH_LOOKUP("replace"): call_ng_flags_str_list(parser, value, call_ng_flags_replace, out); break; case CSH_LOOKUP("rtcp-mux"): case CSH_LOOKUP("RTCP-mux"): call_ng_flags_str_list(parser, value, call_ng_flags_rtcp_mux, out); break; case CSH_LOOKUP("rtpp-flags"): case CSH_LOOKUP("rtpp_flags"):; /* s - list of rtpp flags */ parse_rtpp_flags(&s, out); break; case CSH_LOOKUP("SDES"): case CSH_LOOKUP("sdes"): call_ng_flags_str_list(parser, value, ng_sdes_option, out); break; case CSH_LOOKUP("SDP"): case CSH_LOOKUP("sdp"): out->sdp = s; break; case CSH_LOOKUP("sdp-attr"): case CSH_LOOKUP("SDP-attr"): ng_sdp_attr_manipulations(parser, out, value); break; case CSH_LOOKUP("sdp-media-remove"): case CSH_LOOKUP("SDP-media-remove"): case CSH_LOOKUP("sdp_media_remove"): case CSH_LOOKUP("SDP_media_remove"): ng_sdp_media_remove(parser, out, value); break; case CSH_LOOKUP("set-label"): out->set_label = s; break; case CSH_LOOKUP("sip-code"): case CSH_LOOKUP("sip_code"): case CSH_LOOKUP("SIP-code"): case CSH_LOOKUP("SIP_code"): case CSH_LOOKUP("sip-response-code"): case CSH_LOOKUP("sip_response_code"): case CSH_LOOKUP("SIP-response-code"): case CSH_LOOKUP("SIP_response_code"): out->code = parser->get_int_str(value, out->code); break; case CSH_LOOKUP("sip-message-type"): case CSH_LOOKUP("sip_message_type"): case CSH_LOOKUP("SIP-message-type"): case CSH_LOOKUP("SIP_message_type"): switch (__csh_lookup_n(1, &s)) { case CSH_LOOKUP_N(1, "request"): case CSH_LOOKUP_N(1, "sip-request"): case CSH_LOOKUP_N(1, "sip_request"): case CSH_LOOKUP_N(1, "SIP-request"): case CSH_LOOKUP_N(1, "SIP_request"): out->message_type = SIP_REQUEST; break; case CSH_LOOKUP_N(1, "reply"): case CSH_LOOKUP_N(1, "sip-response"): case CSH_LOOKUP_N(1, "sip_response"): case CSH_LOOKUP_N(1, "SIP-response"): case CSH_LOOKUP_N(1, "SIP_response"): case CSH_LOOKUP_N(1, "sip-reply"): case CSH_LOOKUP_N(1, "sip_reply"): case CSH_LOOKUP_N(1, "SIP-reply"): case CSH_LOOKUP_N(1, "SIP_reply"): out->message_type = SIP_REPLY; break; default: ilog(LOG_WARN, "Unknown 'sip-message-type' flag encountered: '" STR_FORMAT "'", STR_FMT(&s)); } break; case CSH_LOOKUP("start-pos"): out->start_pos = parser->get_int_str(value, out->start_pos); break; case CSH_LOOKUP("supports"): call_ng_flags_str_list(parser, value, call_ng_flags_supports, out); break; #ifdef WITH_TRANSCODING case CSH_LOOKUP("T38"): case CSH_LOOKUP("T.38"): case CSH_LOOKUP("t38"): case CSH_LOOKUP("t.38"): call_ng_flags_str_list(parser, value, ng_t38_option, out); break; case CSH_LOOKUP("T38-version"): case CSH_LOOKUP("T.38-version"): case CSH_LOOKUP("t38-version"): case CSH_LOOKUP("t.38-version"): case CSH_LOOKUP("T38 version"): case CSH_LOOKUP("T.38 version"): case CSH_LOOKUP("t38 version"): case CSH_LOOKUP("t.38 version"): out->t38_version = parser->get_int_str(value, out->t38_version); break; #endif case CSH_LOOKUP("template"):; str *tplate = t_hash_table_lookup(rtpe_signalling_templates, &s); if (!tplate) { ilog(LOG_WARN, "Templates for signalling flags '" STR_FORMAT "' not found", STR_FMT(&s)); break; } // naive approach: just parse them out every time // TODO: improve this by pre-parsing the flags at startup parse_rtpp_flags(tplate, out); break; case CSH_LOOKUP("to-interface"): out->direction[1] = s; break; case CSH_LOOKUP("to-label"): out->to_label = s; break; case CSH_LOOKUP("to-call-id"): out->to_call_id = s; break; case CSH_LOOKUP("to-tag"): out->to_tag = s; break; case CSH_LOOKUP("TOS"): case CSH_LOOKUP("tos"): out->tos = parser->get_int_str(value, out->tos); break; case CSH_LOOKUP("transport protocol"): case CSH_LOOKUP("transport-protocol"): if (!str_cmp(&s, "accept")) out->protocol_accept = true; else out->transport_protocol = transport_protocol(&s); break; case CSH_LOOKUP("trigger"): out->trigger = s; break; case CSH_LOOKUP("trigger-end"): case CSH_LOOKUP("trigger end"): case CSH_LOOKUP("end trigger"): case CSH_LOOKUP("end-trigger"): out->trigger_end = s; break; case CSH_LOOKUP("trigger-end-time"): case CSH_LOOKUP("trigger end time"): case CSH_LOOKUP("end-trigger-time"): case CSH_LOOKUP("end trigger time"): out->trigger_end_ms = parser->get_int_str(value, out->trigger_end_ms); break; case CSH_LOOKUP("trigger-end-digits"): case CSH_LOOKUP("trigger end digits"): case CSH_LOOKUP("end-trigger-digits"): case CSH_LOOKUP("end trigger digits"): out->trigger_end_digits = parser->get_int_str(value, out->trigger_end_digits); break; case CSH_LOOKUP("via-branch"): out->via_branch = s; break; case CSH_LOOKUP("volume"): out->volume = parser->get_int_str(value, out->volume); break; case CSH_LOOKUP("vsc-pause-rec"): case CSH_LOOKUP("VSC-pause-rec"): case CSH_LOOKUP("vsc-pause-recording"): case CSH_LOOKUP("VSC-pause-recording"): out->vsc_pause_rec = s; break; case CSH_LOOKUP("vsc-pause-resume-rec"): case CSH_LOOKUP("VSC-pause-resume-rec"): case CSH_LOOKUP("vsc-pause-resume-recording"): case CSH_LOOKUP("VSC-pause-resume-recording"): out->vsc_pause_resume_rec = s; break; case CSH_LOOKUP("vsc-start-pause-resume-rec"): case CSH_LOOKUP("VSC-start-pause-resume-rec"): case CSH_LOOKUP("vsc-start-pause-resume-recording"): case CSH_LOOKUP("VSC-start-pause-resume-recording"): out->vsc_start_pause_resume_rec = s; break; case CSH_LOOKUP("vsc-start-rec"): case CSH_LOOKUP("VSC-start-rec"): case CSH_LOOKUP("vsc-start-recording"): case CSH_LOOKUP("VSC-start-recording"): out->vsc_start_rec = s; break; case CSH_LOOKUP("vsc-start-stop-rec"): case CSH_LOOKUP("VSC-start-stop-rec"): case CSH_LOOKUP("vsc-start-stop-recording"): case CSH_LOOKUP("VSC-start-stop-recording"): out->vsc_start_stop_rec = s; break; case CSH_LOOKUP("vsc-stop-rec"): case CSH_LOOKUP("VSC-stop-rec"): case CSH_LOOKUP("vsc-stop-recording"): case CSH_LOOKUP("VSC-stop-recording"): out->vsc_stop_rec = s; break; case CSH_LOOKUP("xmlrpc-callback"): case CSH_LOOKUP("XMLRPC-callback"): out->xmlrpc_callback = s; break; default: ilog(LOG_WARN, "Unknown dictionary key encountered: '" STR_FORMAT "'", STR_FMT(key)); } } static void call_ng_process_flags(sdp_ng_flags *out, ng_command_ctx_t *ctx) { const ng_parser_t *parser = ctx->parser_ctx.parser; call_ng_flags_init(out, ctx->opmode); ctx->flags = out; // check for default templates, "default" first if (rtpe_default_signalling_templates[OP_OTHER].len) parse_rtpp_flags(&rtpe_default_signalling_templates[OP_OTHER], out); // and then one matching the current command if (ctx->opmode != OP_OTHER && rtpe_default_signalling_templates[ctx->opmode].len) parse_rtpp_flags(&rtpe_default_signalling_templates[ctx->opmode], out); parser->dict_iter(parser, ctx->req, call_ng_main_flags, out); } static void ng_sdp_attr_manipulations_free(struct sdp_manipulations * array[__MT_MAX]) { for (int i = 0; i < __MT_MAX; i++) { struct sdp_manipulations *sdp_manipulations = array[i]; if (!sdp_manipulations) continue; str_case_ht_destroy_ptr(&sdp_manipulations->rem_commands); str_case_value_ht_destroy_ptr(&sdp_manipulations->subst_commands); t_queue_clear_full(&sdp_manipulations->add_commands, str_free); g_free(sdp_manipulations); array[i] = NULL; } } static void ng_codecs_free(struct ng_codec *c) { g_free(c); } static void ng_media_free(struct ng_media *m) { t_queue_clear_full(&m->codecs, ng_codecs_free); g_free(m); } void call_ng_free_flags(sdp_ng_flags *flags) { str_case_value_ht_destroy_ptr(&flags->codec_set); if (flags->frequencies) g_array_free(flags->frequencies, true); #define X(x) t_queue_clear_full(&flags->x, str_free); RTPE_NG_FLAGS_STR_Q_PARAMS #undef X #define X(x) t_queue_clear_full(&flags->x, sdp_attr_free); RTPE_NG_FLAGS_SDP_ATTR_Q_PARAMS #undef X #define X(x) str_case_ht_destroy_ptr(&flags->x); RTPE_NG_FLAGS_STR_CASE_HT_PARAMS #undef X ng_sdp_attr_manipulations_free(flags->sdp_manipulations); t_queue_clear_full(&flags->medias, ng_media_free); } static enum load_limit_reasons call_offer_session_limit(void) { enum load_limit_reasons ret = LOAD_LIMIT_NONE; if (atomic_get_na(&rtpe_config.max_sessions) >= 0) { rwlock_lock_r(&rtpe_callhash_lock); if (t_hash_table_size(rtpe_callhash) - atomic64_get(&rtpe_stats_gauge.foreign_sessions) >= rtpe_config.max_sessions) { /* foreign calls can't get rejected * total_rejected_sess applies only to "own" sessions */ RTPE_STATS_INC(rejected_sess); ilog(LOG_ERROR, "Parallel session limit reached (%i)",rtpe_config.max_sessions); ret = LOAD_LIMIT_MAX_SESSIONS; } rwlock_unlock_r(&rtpe_callhash_lock); } if (ret == LOAD_LIMIT_NONE && atomic_get_na(&rtpe_config.load_limit)) { int loadavg = g_atomic_int_get(&load_average); if (loadavg >= atomic_get_na(&rtpe_config.load_limit)) { ilog(LOG_WARN, "Load limit exceeded (%.2f > %.2f)", (double) loadavg / 100.0, (double) rtpe_config.load_limit / 100.0); ret = LOAD_LIMIT_LOAD; } } if (ret == LOAD_LIMIT_NONE && atomic_get_na(&rtpe_config.cpu_limit)) { int cpu = g_atomic_int_get(&cpu_usage); if (cpu >= atomic_get_na(&rtpe_config.cpu_limit)) { ilog(LOG_WARN, "CPU usage limit exceeded (%.1f%% > %.1f%%)", (double) cpu / 100.0, (double) rtpe_config.cpu_limit / 100.0); ret = LOAD_LIMIT_CPU; } } if (ret == LOAD_LIMIT_NONE && atomic_get_na(&rtpe_config.bw_limit)) { uint64_t bw = atomic64_get(&rtpe_stats_rate.bytes_user) + atomic64_get(&rtpe_stats_rate.bytes_kernel); if (bw >= atomic_get_na(&rtpe_config.bw_limit)) { ilog(LOG_WARN, "Bandwidth limit exceeded (%" PRIu64 " > %" PRIu64 ")", bw, rtpe_config.bw_limit); ret = LOAD_LIMIT_BW; } } return ret; } void save_last_sdp(struct call_monologue *ml, str *sdp, sdp_sessions_q *parsed, sdp_streams_q *streams) { sdp_streams_clear(&ml->last_in_sdp_streams); ml->last_in_sdp_streams = *streams; t_queue_init(streams); } static enum basic_errors call_ng_basic_checks(sdp_ng_flags *flags) { if (!flags->sdp.s) return NG_ERROR_NO_SDP_BODY; if (!flags->call_id.s) return NG_ERROR_NO_CALL_ID; if (!flags->from_tag.s) return NG_ERROR_NO_FROM_TAG; if (flags->opmode == OP_ANSWER && !flags->to_tag.s) return NG_ERROR_NO_TO_TAG; return 0; } static const char *call_offer_get_call(call_t **callp, sdp_ng_flags *flags) { // are we allowed to create a call? use `errstr` to determine const char *errstr = NULL; // creation is allowed enum load_limit_reasons limit = call_offer_session_limit(); if (limit != LOAD_LIMIT_NONE) { if (!flags->supports_load_limit) errstr = "Parallel session limit reached"; // legacy protocol else errstr = magic_load_limit_strings[limit]; // errstr is set, creation not allowed } if (!errstr) *callp = call_get_or_create(&flags->call_id, false); else { *callp = call_get(&flags->call_id); if (!*callp) return errstr; } return NULL; } static const char *call_offer_answer_ng(ng_command_ctx_t *ctx, const char* addr) { const char *errstr; str sdp = STR_NULL; g_auto(sdp_sessions_q) parsed = TYPED_GQUEUE_INIT; g_auto(sdp_streams_q) streams = TYPED_GQUEUE_INIT; g_autoptr(call_t) call = NULL; struct call_monologue * monologues[2]; int ret; g_auto(sdp_ng_flags) flags; parser_arg output = ctx->resp; const ng_parser_t *parser = ctx->parser_ctx.parser; g_auto(str) sdp_out = STR_NULL; call_ng_process_flags(&flags, ctx); if ((ret = call_ng_basic_checks(&flags)) > 0) return _ng_basic_errors[ret]; if (flags.opmode == OP_OFFER) { errstr = call_offer_get_call(&call, &flags); if (errstr) goto out; } else if (flags.opmode == OP_ANSWER) { call = call_get(&flags.call_id); errstr = "Unknown call-id"; if (!call) goto out; /* for answer: swap To against From tag */ str_swap(&flags.to_tag, &flags.from_tag); } sdp = call_str_cpy(&flags.sdp); errstr = "Failed to parse SDP"; if (sdp_parse(&sdp, &parsed, &flags)) goto out; if (flags.loop_protect && sdp_is_duplicate(&parsed)) { ilog(LOG_INFO, "Ignoring message as SDP has already been processed by us"); parser->dict_add_str(output, "sdp", &flags.sdp); errstr = NULL; goto out; } errstr = "Incomplete SDP specification"; if (sdp_streams(&parsed, &streams, &flags)) goto out; // SDP fragments for trickle ICE must always operate on an existing call if (flags.opmode == OP_OFFER && trickle_ice_update(ctx->ngbuf, call, &flags, &streams)) { errstr = NULL; // SDP fragments for trickle ICE are consumed with no replacement returned goto out; } if (flags.debug) CALL_SET(call, DEBUG); if (rtpe_config.active_switchover && IS_FOREIGN_CALL(call)) call_make_own_foreign(call, false); updated_created_from(call, addr); if (flags.xmlrpc_callback.len) call->xmlrpc_callback = call_str_cpy(&flags.xmlrpc_callback); if (flags.dtmf_log_dest.address.family) call->dtmf_log_dest = flags.dtmf_log_dest; /* At least the random ICE strings are contained within the call struct, so we * need to hold a ref until we're done sending the reply */ call_ngb_hold_ref(call, ctx->ngbuf); errstr = "Invalid dialogue association"; if (call_get_mono_dialogue(monologues, call, &flags.from_tag, &flags.to_tag, flags.via_branch.s ? &flags.via_branch : NULL, &flags)) { goto out; } struct call_monologue *from_ml = monologues[0]; struct call_monologue *to_ml = monologues[1]; if (flags.opmode == OP_OFFER) { from_ml->tagtype = FROM_TAG; } else { from_ml->tagtype = TO_TAG; } if (flags.drop_traffic_start) { CALL_SET(call, DROP_TRAFFIC); } else if (flags.drop_traffic_stop) { CALL_CLEAR(call, DROP_TRAFFIC); } if (flags.block_dtmf) call_set_dtmf_block(call, monologues[0], &flags); struct recording *recording = NULL; /* offer/answer model processing */ if ((ret = monologue_offer_answer(monologues, &streams, &flags)) == 0) { update_metadata_monologue(from_ml, &flags); detect_setup_recording(call, &flags); recording = call->recording; meta_write_sdp_before(recording, &sdp, from_ml, flags.opmode); /* check if sender's monologue has any audio medias putting the call * into the sendonly state, if so, check if it wants this call * to be provided with moh playbacks */ errstr = call_check_moh(from_ml, to_ml, &flags); if (errstr) goto out; /* if all fine, prepare an outer sdp and save it */ if ((ret = sdp_create(&sdp_out, to_ml, &flags)) == 0) { /* TODO: should we save sdp_out? */ save_last_sdp(from_ml, &sdp, &parsed, &streams); } /* place return output SDP */ if (sdp_out.len) { ctx->ngbuf->sdp_out = sdp_out.s; ctx->parser_ctx.parser->dict_add_str(output, "sdp", &sdp_out); meta_write_sdp_after(recording, &sdp_out, from_ml, flags.opmode); sdp_out = STR_NULL; /* ownership passed to output */ } } recording_response(recording, ctx->parser_ctx.parser, output); dequeue_sdp_fragments(from_ml); rwlock_unlock_w(&call->master_lock); if (!flags.no_redis_update) { redis_update_onekey(call, rtpe_redis_write); } else { ilog(LOG_DEBUG, "Not updating Redis due to present no-redis-update flag"); } from_ml->started = rtpe_now; errstr = "Error rewriting SDP"; if (ret == ERROR_NO_FREE_PORTS || ret == ERROR_NO_FREE_LOGS) { ilog(LOG_ERR, "Destroying call"); errstr = "Ran out of ports"; call_destroy(call); } obj_release(call); if (ret) goto out; errstr = NULL; out: return errstr; } const char *call_offer_ng(ng_command_ctx_t *ctx, const char *addr) { return call_offer_answer_ng(ctx, addr); } const char *call_answer_ng(ng_command_ctx_t *ctx) { return call_offer_answer_ng(ctx, NULL); } const char *call_delete_ng(ng_command_ctx_t *ctx) { g_auto(sdp_ng_flags) rtpp_flags; parser_arg output = ctx->resp; const ng_parser_t *parser = ctx->parser_ctx.parser; call_ng_process_flags(&rtpp_flags, ctx); if (!rtpp_flags.call_id.len) return "No call-id in message"; call_t *c = call_get(&rtpp_flags.call_id); if (!c) goto err; if (rtpp_flags.discard_recording) recording_discard(c); if (call_delete_branch(c, &rtpp_flags.via_branch, &rtpp_flags.from_tag, (rtpp_flags.to_tag_flag ? &rtpp_flags.to_tag : NULL), ctx, rtpp_flags.delete_delay)) { goto err; } return NULL; err: if (rtpp_flags.fatal) return "Call-ID not found or tags didn't match"; parser->dict_add_string(output, "warning", "Call-ID not found or tags didn't match"); return NULL; } static void ng_stats(ng_command_ctx_t *ctx, parser_arg dict, const char *dict_name, const struct stream_stats *s, struct stream_stats *totals) { if (ctx) { const ng_parser_t *parser = ctx->parser_ctx.parser; parser_arg d = parser->dict_add_dict(dict, dict_name); parser->dict_add_int(d, "packets", atomic64_get_na(&s->packets)); parser->dict_add_int(d, "bytes", atomic64_get_na(&s->bytes)); parser->dict_add_int(d, "errors", atomic64_get_na(&s->errors)); } if (!totals) return; atomic64_add_na(&totals->packets, atomic64_get(&s->packets)); atomic64_add_na(&totals->bytes, atomic64_get(&s->bytes)); atomic64_add_na(&totals->errors, atomic64_get(&s->errors)); } static void ng_stats_endpoint(const ng_parser_t *parser, parser_arg dict, const endpoint_t *ep) { if (!ep->address.family) return; parser->dict_add_string(dict, "family", ep->address.family->name); parser->dict_add_str_dup(dict, "address", STR_PTR(sockaddr_print_buf(&ep->address))); parser->dict_add_int(dict, "port", ep->port); } #define BF_PS(k, f) if (PS_ISSET(ps, f)) parser->list_add_string(flags, k) static void ng_stats_stream(ng_command_ctx_t *ctx, parser_arg list, const struct packet_stream *ps, struct call_stats *totals) { parser_arg dict = {0}, flags; struct stream_stats *s; if (!ctx) goto stats; const ng_parser_t *parser = ctx->parser_ctx.parser; dict = parser->list_add_dict(list); if (ps->selected_sfd) { parser->dict_add_int(dict, "local port", ps->selected_sfd->socket.local.port); parser->dict_add_str_dup(dict, "local address", STR_PTR(sockaddr_print_buf(&ps->selected_sfd->socket.local.address))); parser->dict_add_string(dict, "family", ps->selected_sfd->socket.local.address.family->name); } ng_stats_endpoint(parser, parser->dict_add_dict(dict, "endpoint"), &ps->endpoint); ng_stats_endpoint(parser, parser->dict_add_dict(dict, "advertised endpoint"), &ps->advertised_endpoint); if (ps->crypto.params.crypto_suite) parser->dict_add_string(dict, "crypto suite", ps->crypto.params.crypto_suite->name); parser->dict_add_int(dict, "last packet", packet_stream_last_packet(ps) / 1000000L); parser->dict_add_int(dict, "last kernel packet", atomic64_get_na(&ps->stats_in->last_packet_us) / 1000000L); parser->dict_add_int(dict, "last user packet", atomic64_get_na(&ps->last_packet_us) / 1000000L); __auto_type se = call_get_first_ssrc(&ps->media->ssrc_hash_in); if (se) parser->dict_add_int(dict, "SSRC", se->h.ssrc); flags = parser->dict_add_list(dict, "flags"); BF_PS("RTP", RTP); BF_PS("RTCP", RTCP); BF_PS("fallback RTCP", FALLBACK_RTCP); BF_PS("filled", FILLED); BF_PS("confirmed", CONFIRMED); BF_PS("kernelized", KERNELIZED); BF_PS("no kernel support", NO_KERNEL_SUPPORT); BF_PS("DTLS fingerprint verified", FINGERPRINT_VERIFIED); BF_PS("strict source address", STRICT_SOURCE); BF_PS("media handover", MEDIA_HANDOVER); BF_PS("ICE", ICE); stats: if (totals->last_packet_us < packet_stream_last_packet(ps)) totals->last_packet_us = packet_stream_last_packet(ps); /* XXX distinguish between input and output */ s = &totals->totals[0]; if (!PS_ISSET(ps, RTP)) s = &totals->totals[1]; ng_stats(ctx, dict, "stats", ps->stats_in, s); ng_stats(ctx, dict, "stats_out", ps->stats_out, NULL); } #define BF_M(k, f) if (MEDIA_ISSET(m, f)) parser->list_add_string(flags, k) static void ng_stats_media(ng_command_ctx_t *ctx, parser_arg list, const struct call_media *m, struct call_stats *totals, parser_arg ssrc) { parser_arg dict, streams = {0}, flags; struct packet_stream *ps; const rtp_payload_type *rtp_pt = NULL; if (!ctx) goto stats; const ng_parser_t *parser = ctx->parser_ctx.parser; rtp_pt = __rtp_stats_codec((struct call_media *)m); dict = parser->list_add_dict(list); parser->dict_add_int(dict, "index", m->index); parser->dict_add_str(dict, "type", &m->type); if (m->protocol) parser->dict_add_string(dict, "protocol", m->protocol->name); if (rtp_pt) parser->dict_add_str_dup(dict, "codec", &rtp_pt->encoding_with_params); streams = parser->dict_add_list(dict, "streams"); flags = parser->dict_add_list(dict, "flags"); BF_M("initialized", INITIALIZED); BF_M("asymmetric", ASYMMETRIC); BF_M("send", SEND); BF_M("recv", RECV); BF_M("rtcp-mux", RTCP_MUX); BF_M("DTLS-SRTP", DTLS); BF_M("DTLS role active", SETUP_ACTIVE); BF_M("DTLS role passive", SETUP_PASSIVE); BF_M("SDES", SDES); BF_M("passthrough", PASSTHRU); BF_M("ICE", ICE); BF_M("trickle ICE", TRICKLE_ICE); BF_M("ICE controlling", ICE_CONTROLLING); BF_M("ICE-lite peer", ICE_LITE_PEER); BF_M("ICE-lite self", ICE_LITE_SELF); BF_M("unidirectional", UNIDIRECTIONAL); BF_M("loop check", LOOP_CHECK); BF_M("generator/sink", GENERATOR); BF_M("ptime-override", PTIME_OVERRIDE); BF_M("RTCP feedback", RTCP_FB); BF_M("RTCP generator", RTCP_GEN); BF_M("echo", ECHO); BF_M("blackhole", BLACKHOLE); BF_M("SDES reordered", REORDER_FORCED); BF_M("audio player", AUDIO_PLAYER); BF_M("legacy OSRTP", LEGACY_OSRTP); BF_M("reverse legacy OSRTP", LEGACY_OSRTP_REV); BF_M("transcoding", TRANSCODING); BF_M("block egress", BLOCK_EGRESS); ng_stats_ssrc(parser, ssrc, parser->dict_add_list(dict, "ingress SSRCs"), &m->ssrc_hash_in); ng_stats_ssrc(parser, NULL, parser->dict_add_list(dict, "egress SSRCs"), &m->ssrc_hash_out); stats: for (auto_iter(l, m->streams.head); l; l = l->next) { ps = l->data; ng_stats_stream(ctx, streams, ps, totals); } } static void ng_stats_monologue(ng_command_ctx_t *ctx, parser_arg dict, const struct call_monologue *ml, struct call_stats *totals, parser_arg ssrc) { parser_arg sub, medias = {0}; struct call_media *m; g_auto(GQueue) mls_subscriptions = G_QUEUE_INIT; /* to avoid duplications */ g_auto(GQueue) mls_subscribers = G_QUEUE_INIT; /* to avoid duplications */ if (!ml) return; if (!ctx) goto stats; const ng_parser_t *parser = ctx->parser_ctx.parser; if (ml->tag.len) sub = parser->dict_add_dict(dict, ml->tag.s); else { char buf[32]; snprintf(buf, sizeof(buf), "", ml->unique_id); sub = parser->dict_add_dict_dup(dict, buf); } parser->dict_add_str(sub, "tag", &ml->tag); if (ml->viabranch.s) parser->dict_add_str(sub, "via-branch", &ml->viabranch); if (ml->tag_aliases.length) { parser_arg aliases = parser->dict_add_list(sub, "tag-aliases"); for (auto_iter(alias, ml->tag_aliases.head); alias; alias = alias->next) parser->list_add_str_dup(aliases, alias->data); } if (ml->label.s) parser->dict_add_str(sub, "label", &ml->label); parser->dict_add_int(sub, "created", ml->created_us / 1000000L); if (ml->metadata.s) parser->dict_add_str(sub, "metadata", &ml->metadata); parser_arg b_subscriptions = parser->dict_add_list(sub, "subscriptions"); parser_arg b_subscribers = parser->dict_add_list(sub, "subscribers"); for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type subscription = media->media_subscriptions.head; subscription; subscription = subscription->next) { struct media_subscription * ms = subscription->data; if (!g_queue_find(&mls_subscriptions, ms->monologue)) { parser_arg sub1 = parser->list_add_dict(b_subscriptions); parser->dict_add_str(sub1, "tag", &ms->monologue->tag); parser->dict_add_string(sub1, "type", ms->attrs.offer_answer ? "offer/answer" : "pub/sub"); g_queue_push_tail(&mls_subscriptions, ms->monologue); } } for (__auto_type subscriber = media->media_subscribers.head; subscriber; subscriber = subscriber->next) { struct media_subscription * ms = subscriber->data; if (!g_queue_find(&mls_subscribers, ms->monologue)) { parser_arg sub1 = parser->list_add_dict(b_subscribers); parser->dict_add_str(sub1, "tag", &ms->monologue->tag); parser->dict_add_string(sub1, "type", ms->attrs.offer_answer ? "offer/answer" : "pub/sub"); g_queue_push_tail(&mls_subscribers, ms->monologue); } } } medias = parser->dict_add_list(sub, "medias"); parser_arg list = parser->dict_add_list(sub, "VSC"); for (unsigned int i = 0; i < ml->num_dtmf_triggers; i++) { const struct dtmf_trigger_state *state = &ml->dtmf_trigger_state[i]; if (state->trigger.len == 0) continue; parser_arg vsc = parser->list_add_dict(list); const char *type = dtmf_trigger_types[state->type]; if (type) parser->dict_add_string(vsc, "type", type); parser->dict_add_str(vsc, "trigger", &state->trigger); parser->dict_add_int(vsc, "active", !state->inactive); } if (ml->call->recording) { parser_arg rec = parser->dict_add_dict(sub, "recording"); parser->dict_add_int(rec, "excluded", !!ML_ISSET(ml, NO_RECORDING)); parser->dict_add_int(rec, "forwarding", !!ML_ISSET(ml, REC_FORWARDING)); } stats: for (unsigned int i = 0; i < ml->medias->len; i++) { m = ml->medias->pdata[i]; if (!m) continue; ng_stats_media(ctx, medias, m, totals, ssrc); } } static void ng_stats_ssrc_mos_entry_common(const ng_parser_t *parser, parser_arg subent, struct ssrc_stats_block *sb, unsigned int div) { parser->dict_add_int(subent, "MOS", sb->mos / div); parser->dict_add_int(subent, "round-trip time", sb->rtt / div); parser->dict_add_int(subent, "round-trip time leg", sb->rtt_leg / div); parser->dict_add_int(subent, "jitter", sb->jitter / div); parser->dict_add_int(subent, "packet loss", sb->packetloss / div); } static void ng_stats_ssrc_mos_entry(const ng_parser_t *parser, parser_arg subent, struct ssrc_stats_block *sb) { ng_stats_ssrc_mos_entry_common(parser, subent, sb, 1); parser->dict_add_int(subent, "reported at", sb->reported / 1000000L); } static void ng_stats_ssrc_mos_entry_dict(const ng_parser_t *parser, parser_arg ent, const char *label, struct ssrc_stats_block *sb) { parser_arg subent = parser->dict_add_dict(ent, label); ng_stats_ssrc_mos_entry(parser, subent, sb); } static void ng_stats_ssrc_mos_entry_dict_avg(const ng_parser_t *parser, parser_arg ent, const char *label, struct ssrc_stats_block *sb, unsigned int div) { parser_arg subent = parser->dict_add_dict(ent, label); ng_stats_ssrc_mos_entry_common(parser, subent, sb, div); parser->dict_add_int(subent, "samples", div); } static void ng_stats_ssrc_1(const ng_parser_t *parser, parser_arg ent, struct ssrc_entry_call *se) { parser->dict_add_int(ent, "bytes", atomic64_get_na(&se->stats->bytes)); parser->dict_add_int(ent, "packets", atomic64_get_na(&se->stats->packets)); parser->dict_add_int(ent, "last RTP timestamp", atomic_get_na(&se->stats->timestamp)); parser->dict_add_int(ent, "last RTP seq", atomic_get_na(&se->stats->ext_seq)); if (!se->stats_blocks.length || !se->lowest_mos || !se->highest_mos) return; parser->dict_add_int(ent, "cumulative loss", se->packets_lost); int mos_samples = se->stats_blocks.length - se->no_mos_count; if (mos_samples < 1) mos_samples = 1; ng_stats_ssrc_mos_entry_dict_avg(parser, ent, "average MOS", &se->average_mos, mos_samples); ng_stats_ssrc_mos_entry_dict(parser, ent, "lowest MOS", se->lowest_mos); ng_stats_ssrc_mos_entry_dict(parser, ent, "highest MOS", se->highest_mos); parser_arg progdict = parser->dict_add_dict(ent, "MOS progression"); // aim for about 10 entries to the list GList *listent = se->stats_blocks.head; struct ssrc_stats_block *sb = listent->data; int64_t interval = ((struct ssrc_stats_block *) se->stats_blocks.tail->data)->reported - sb->reported; interval /= 10; parser->dict_add_int(progdict, "interval", interval / 1000000L); int64_t next_step = sb->reported; parser_arg entlist = parser->dict_add_list(progdict, "entries"); for (; listent; listent = listent->next) { sb = listent->data; if (sb->reported < next_step) continue; next_step += interval; parser_arg cent = parser->list_add_dict(entlist); ng_stats_ssrc_mos_entry(parser, cent, sb); } } static void ng_stats_ssrc(const ng_parser_t *parser, parser_arg dict, parser_arg list, const struct ssrc_hash *ht) { for (GList *l = ht->nq.head; l; l = l->next) { struct ssrc_entry_call *se = l->data; char tmp[12]; snprintf(tmp, sizeof(tmp), "%" PRIu32, se->h.ssrc); parser_arg ent = parser->list_add_dict(list); parser->dict_add_int(ent, "SSRC", se->h.ssrc); ng_stats_ssrc_1(parser, ent, se); if (dict.gen && !parser->dict_contains(dict, tmp)) { ent = parser->dict_add_dict_dup(dict, tmp); ng_stats_ssrc_1(parser, ent, se); } } } /* call must be locked */ void ng_call_stats(ng_command_ctx_t *ctx, call_t *call, const str *fromtag, const str *totag, struct call_stats *totals) { parser_arg tags = {0}, dict; const str *match_tag; struct call_monologue *ml; struct call_stats t_b; parser_arg ssrc = {0}; const ng_parser_t *parser = NULL; if (!totals) totals = &t_b; ZERO(*totals); if (!ctx) goto stats; call_ngb_hold_ref(call, ctx->ngbuf); parser = ctx->parser_ctx.parser; parser->dict_add_int(ctx->resp, "created", call->created / 1000000L); parser->dict_add_int(ctx->resp, "created_us", call->created % 1000000L); parser->dict_add_int(ctx->resp, "created_ts", call->created); parser->dict_add_int(ctx->resp, "last signal", call->last_signal_us / 1000000L); parser->dict_add_int(ctx->resp, "last redis update", atomic64_get_na(&call->last_redis_update_us) / 1000000L); if (call->metadata.s) parser->dict_add_str(ctx->resp, "metadata", &call->metadata); ssrc = parser->dict_add_dict(ctx->resp, "SSRC"); tags = parser->dict_add_dict(ctx->resp, "tags"); stats: match_tag = (totag && totag->s && totag->len) ? totag : fromtag; if (!match_tag || !match_tag->len) { for (__auto_type l = call->monologues.head; l; l = l->next) { ml = l->data; ng_stats_monologue(ctx, tags, ml, totals, ssrc); } } else { ml = call_get_monologue(call, match_tag); if (ml) { ng_stats_monologue(ctx, tags, ml, totals, ssrc); g_auto(GQueue) mls = G_QUEUE_INIT; /* to avoid duplications */ for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type subscription = media->media_subscriptions.head; subscription; subscription = subscription->next) { struct media_subscription * ms = subscription->data; if (!g_queue_find(&mls, ms->monologue)) { ng_stats_monologue(ctx, tags, ms->monologue, totals, ssrc); g_queue_push_tail(&mls, ms->monologue); } } } } } if (!ctx) return; dict = parser->dict_add_dict(ctx->resp, "totals"); ng_stats(ctx, dict, "RTP", &totals->totals[0], NULL); ng_stats(ctx, dict, "RTCP", &totals->totals[1], NULL); if (call->recording) { parser_arg rec = parser->dict_add_dict(ctx->resp, "recording"); parser->dict_add_int(rec, "call recording", !!CALL_ISSET(call, RECORDING_ON)); parser->dict_add_int(rec, "forwarding", !!CALL_ISSET(call, REC_FORWARDING)); } } static void ng_list_calls(ng_command_ctx_t *ctx, parser_arg output, long long int limit) { rtpe_calls_ht_iter iter; const ng_parser_t *parser = ctx->parser_ctx.parser; rwlock_lock_r(&rtpe_callhash_lock); t_hash_table_iter_init (&iter, rtpe_callhash); str *key; while (limit-- && t_hash_table_iter_next (&iter, &key, NULL)) { parser->list_add_str_dup(output, key); } rwlock_unlock_r(&rtpe_callhash_lock); } const char *call_query_ng(ng_command_ctx_t *ctx) { str callid, fromtag, totag; call_t *call; parser_arg input = ctx->req; const ng_parser_t *parser = ctx->parser_ctx.parser; if (!parser->dict_get_str(input, "call-id", &callid)) return "No call-id in message"; call = call_get(&callid); if (!call) return "Unknown call-id"; parser->dict_get_str(input, "from-tag", &fromtag); parser->dict_get_str(input, "to-tag", &totag); ng_call_stats(ctx, call, &fromtag, &totag, NULL); rwlock_unlock_w(&call->master_lock); obj_put(call); return NULL; } const char *call_list_ng(ng_command_ctx_t *ctx) { parser_arg calls; long long int limit; parser_arg input = ctx->req; parser_arg output = ctx->resp; const ng_parser_t *parser = ctx->parser_ctx.parser; limit = parser->dict_get_int_str(input, "limit", 32); if (limit < 0) { return "invalid limit, must be >= 0"; } calls = parser->dict_add_list(output, "calls"); ng_list_calls(ctx, calls, limit); return NULL; } static const char *call_recording_common_ng(ng_command_ctx_t *ctx, void (*fn)(ng_command_ctx_t *, call_t *call)) { g_auto(sdp_ng_flags) flags; g_autoptr(call_t) call = NULL; parser_arg input = ctx->req; const ng_parser_t *parser = ctx->parser_ctx.parser; call_ng_process_flags(&flags, ctx); if (!parser->dict_get_str(input, "call-id", &flags.call_id)) return "No call-id in message"; call = call_get(&flags.call_id); if (!call) return "Unknown call-id"; struct call_monologue *ml = NULL; if (parser->dict_get_str(input, "from-tag", &flags.from_tag)) { if (flags.from_tag.s) { ml = call_get_monologue(call, &flags.from_tag); if (!ml) ilog(LOG_WARN, "Given from-tag " STR_FORMAT_M " not found", STR_FMT_M(&flags.from_tag)); } } if (ml) update_metadata_monologue(ml, &flags); else update_metadata_call(call, &flags); fn(ctx, call); call_unlock_release_update(&call); return NULL; } static void start_recording_fn(ng_command_ctx_t *ctx, call_t *call) { recording_start(call); } const char *call_start_recording_ng(ng_command_ctx_t *ctx) { return call_recording_common_ng(ctx, start_recording_fn); } static void pause_recording_fn(ng_command_ctx_t *ctx, call_t *call) { recording_pause(call); } const char *call_pause_recording_ng(ng_command_ctx_t *ctx) { return call_recording_common_ng(ctx, pause_recording_fn); } static void stop_recording_iter(str *key, unsigned int idx, helper_arg arg) { if (str_cmp(key, "pause") == 0) *arg.call_fn = recording_pause; else if (str_cmp(key, "discard-recording") == 0) *arg.call_fn = recording_discard; } static void stop_recording_fn(ng_command_ctx_t *ctx, call_t *call) { // support alternative usage for "pause" call: either `pause=yes` ... parser_arg input = ctx->req; const ng_parser_t *parser = ctx->parser_ctx.parser; str pause; if (parser->dict_get_str(input, "pause", &pause)) { if (!str_cmp(&pause, "yes") || !str_cmp(&pause, "on") || !str_cmp(&pause, "true")) { pause_recording_fn(ctx, call); return; } } // ... or `flags=[pause]` parser_arg item = parser->dict_get_expect(input, "flags", BENCODE_LIST); void (*fn)(call_t *) = recording_stop; if (item.gen) parser->list_iter(parser, item, stop_recording_iter, NULL, &fn); fn(call); } const char *call_stop_recording_ng(ng_command_ctx_t *ctx) { return call_recording_common_ng(ctx, stop_recording_fn); } static const char *media_block_match1(call_t *call, struct call_monologue **monologue, sdp_ng_flags *flags) { if (flags->label.s) { *monologue = t_hash_table_lookup(call->labels, &flags->label); if (!*monologue) return "No monologue matching the given label"; } else if (flags->address.s) { sockaddr_t addr; if (!sockaddr_parse_any_str(&addr, &flags->address)) return "Failed to parse network address"; // walk our structures to find a matching stream for (__auto_type l = call->monologues.head; l; l = l->next) { *monologue = l->data; for (unsigned int k = 0; k < (*monologue)->medias->len; k++) { struct call_media *media = (*monologue)->medias->pdata[k]; if (!media) continue; if (!media->streams.head) continue; struct packet_stream *ps = media->streams.head->data; if (!sockaddr_eq(&addr, &ps->advertised_endpoint.address)) continue; ilog(LOG_DEBUG, "Matched address %s%s%s to tag '" STR_FORMAT_M "'", FMT_M(sockaddr_print_buf(&addr)), STR_FMT_M(&(*monologue)->tag)); goto found; } } return "Failed to match address to any tag"; found: ; } /* ignore from-tag, if directional is not set */ else if (flags->from_tag.s && (!IS_OP_DIRECTIONAL(flags->opmode) || (IS_OP_DIRECTIONAL(flags->opmode) && flags->directional))) { *monologue = call_get_monologue(call, &flags->from_tag); if (!*monologue) return "From-tag given, but no such tag exists"; } if (*monologue) __monologue_unconfirm(*monologue, "media blocking signalling event"); return NULL; } static const char *media_block_match(call_t **call, struct call_monologue **monologue, sdp_ng_flags *flags, ng_command_ctx_t *ctx) { *call = NULL; *monologue = NULL; call_ng_process_flags(flags, ctx); if (!flags->call_id.s) return "No call-id in message"; *call = call_get(&flags->call_id); if (!*call) return "Unknown call-ID"; // directional? if (flags->all == ALL_ALL) // explicitly non-directional, so skip the rest return NULL; const char *err = media_block_match1(*call, monologue, flags); if (err) return err; // for generic ops, handle set-label here if given if (IS_OP_OTHER(flags->opmode) && flags->set_label.len && *monologue) { (*monologue)->label = call_str_cpy(&flags->set_label); t_hash_table_replace((*call)->labels, &(*monologue)->label, *monologue); } return NULL; } void add_media_to_sub_list(subscription_q *q, struct call_media *media, struct call_monologue *ml) { struct media_subscription *ms = g_new0(__typeof(*ms), 1); ms->media = media; ms->monologue = ml; t_queue_push_tail(q, ms); } static const char *media_block_match_mult(call_t **call, subscription_q *medias, sdp_ng_flags *flags, ng_command_ctx_t *ctx) { call_ng_process_flags(flags, ctx); if (!flags->call_id.s) return "No call-id in message"; *call = call_get(&flags->call_id); if (!*call) return "Unknown call-ID"; if (flags->all == ALL_ALL) { for (__auto_type l = (*call)->medias.head; l; l = l->next) { struct call_media *media = l->data; if (!media || (media->monologue->tagtype != FROM_TAG && media->monologue->tagtype != TO_TAG)) { continue; } add_media_to_sub_list(medias, media, media->monologue); } return NULL; } /* is a single ml given? */ struct call_monologue *ml = NULL; const char *err = media_block_match1(*call, &ml, flags); if (err) return err; if (ml) { for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media) continue; add_media_to_sub_list(medias, media, ml); } return NULL; } /* handle from-tag list */ for (__auto_type l = flags->from_tags.head; l; l = l->next) { str *s = l->data; struct call_monologue *mlf = call_get_monologue(*call, s); if (!mlf) { ilog(LOG_WARN, "Given from-tag " STR_FORMAT_M " not found", STR_FMT_M(s)); } else { for (int i = 0; i < mlf->medias->len; i++) { struct call_media * media = mlf->medias->pdata[i]; if (!media) continue; add_media_to_sub_list(medias, media, mlf); } } } if (!medias->length) return "No medias found (no monologues matched)"; return NULL; } // XXX these are all identical - unify and use a flags int and/or callback const char *call_start_forwarding_ng(ng_command_ctx_t *ctx) { g_autoptr(call_t) call = NULL; struct call_monologue *monologue; const char *errstr = NULL; g_auto(sdp_ng_flags) flags; errstr = media_block_match(&call, &monologue, &flags, ctx); if (errstr) return errstr; if (monologue) { ilog(LOG_INFO, "Start forwarding for single party (tag '" STR_FORMAT_M "')", STR_FMT_M(&monologue->tag)); ML_SET(monologue, REC_FORWARDING); } else { ilog(LOG_INFO, "Start forwarding (entire call)"); CALL_SET(call, REC_FORWARDING); } if (monologue) update_metadata_monologue(monologue, &flags); else update_metadata_call(call, &flags); recording_start_daemon(call); call_unlock_release_update(&call); return NULL; } const char *call_stop_forwarding_ng(ng_command_ctx_t *ctx) { g_autoptr(call_t) call = NULL; struct call_monologue *monologue; const char *errstr = NULL; g_auto(sdp_ng_flags) flags; errstr = media_block_match(&call, &monologue, &flags, ctx); if (errstr) return errstr; if (monologue) { ilog(LOG_INFO, "Stop forwarding for single party (tag '" STR_FORMAT_M "')", STR_FMT_M(&monologue->tag)); ML_CLEAR(monologue, REC_FORWARDING); } else { ilog(LOG_INFO, "Stop forwarding (entire call)"); CALL_CLEAR(call, REC_FORWARDING); if (flags.all == ALL_ALL) { for (__auto_type l = call->monologues.head; l; l = l->next) { monologue = l->data; ML_CLEAR(monologue, REC_FORWARDING); } } } if (monologue) update_metadata_monologue(monologue, &flags); else update_metadata_call(call, &flags); recording_stop_daemon(call); call_unlock_release_update(&call); return NULL; } static void call_monologue_set_block_mode(struct call_monologue *ml, sdp_ng_flags *flags) { if (flags->delay_buffer >= 0) { for (unsigned int i = 0; i < ml->medias->len; i++) { struct call_media *media = ml->medias->pdata[i]; if (!media) continue; media->buffer_delay = flags->delay_buffer; } } bf_set_clear(&ml->ml_flags, ML_FLAG_DETECT_DTMF, flags->detect_dtmf); if (flags->volume >= 0 && flags->volume <= 63) ml->tone_vol = flags->volume; else if (flags->volume < 0 && flags->volume >= -63) ml->tone_vol = -1 * flags->volume; if (flags->frequencies && flags->frequencies->len > 0) { if (ml->tone_freqs) g_array_free(ml->tone_freqs, true); ml->tone_freqs = flags->frequencies; flags->frequencies = NULL; } if (flags->block_dtmf_mode == BLOCK_DTMF_ZERO) ml->dtmf_digit = '0'; else { char digit = dtmf_code_to_char(flags->digit); if (digit) ml->dtmf_digit = digit; else if (dtmf_code_from_char(flags->digit) != -1) ml->dtmf_digit = flags->digit; } dtmf_trigger_set(ml, DTMF_TRIGGER_BLOCK, &flags->trigger, false); dtmf_trigger_set(ml, DTMF_TRIGGER_UNBLOCK, &flags->trigger_end, false); ml->block_dtmf_trigger = flags->block_dtmf_mode_trigger; ml->dtmf_trigger_digits = flags->trigger_end_digits; ml->block_dtmf_trigger_end_ms = flags->trigger_end_ms; ml->dtmf_delay = flags->dtmf_delay; codec_update_all_handlers(ml); } static void call_set_dtmf_block(call_t *call, struct call_monologue *monologue, sdp_ng_flags *flags) { enum block_dtmf_mode mode = BLOCK_DTMF_DROP; // special case default: if there's a trigger, default block mode is none if (flags->block_dtmf_mode_trigger || flags->trigger.len) mode = BLOCK_DTMF_OFF; if (flags->block_dtmf_mode) mode = flags->block_dtmf_mode; if (monologue) { ilog(LOG_INFO, "Blocking directional DTMF (tag '" STR_FORMAT_M "')", STR_FMT_M(&monologue->tag)); monologue->block_dtmf = mode; } else { ilog(LOG_INFO, "Blocking DTMF (entire call)"); call->block_dtmf = mode; } if (is_dtmf_replace_mode(mode) || flags->delay_buffer >= 0 || flags->trigger.len) { if (monologue) call_monologue_set_block_mode(monologue, flags); else { for (__auto_type l = call->monologues.head; l; l = l->next) { struct call_monologue *ml = l->data; call_monologue_set_block_mode(ml, flags); } } } } const char *call_block_dtmf_ng(ng_command_ctx_t *ctx) { g_autoptr(call_t) call = NULL; struct call_monologue *monologue; const char *errstr = NULL; g_auto(sdp_ng_flags) flags; errstr = media_block_match(&call, &monologue, &flags, ctx); if (errstr) return errstr; call_set_dtmf_block(call, monologue, &flags); return NULL; } const char *call_unblock_dtmf_ng(ng_command_ctx_t *ctx) { g_autoptr(call_t) call = NULL; struct call_monologue *monologue; const char *errstr = NULL; g_auto(sdp_ng_flags) flags; errstr = media_block_match(&call, &monologue, &flags, ctx); if (errstr) return errstr; if (monologue) { ilog(LOG_INFO, "Unblocking directional DTMF (tag '" STR_FORMAT_M "')", STR_FMT_M(&monologue->tag)); enum block_dtmf_mode prev_mode = monologue->block_dtmf; monologue->block_dtmf = BLOCK_DTMF_OFF; if (is_dtmf_replace_mode(prev_mode) || flags.delay_buffer >= 0) { if (flags.delay_buffer >= 0) { for (unsigned int i = 0; i < monologue->medias->len; i++) { struct call_media *media = monologue->medias->pdata[i]; if (!media) continue; media->buffer_delay = flags.delay_buffer; } } bf_set_clear(&monologue->ml_flags, ML_FLAG_DETECT_DTMF, flags.detect_dtmf); codec_update_all_handlers(monologue); } } else { ilog(LOG_INFO, "Unblocking DTMF (entire call)"); enum block_dtmf_mode prev_mode = call->block_dtmf; call->block_dtmf = BLOCK_DTMF_OFF; if (flags.all == ALL_ALL || is_dtmf_replace_mode(prev_mode) || flags.delay_buffer >= 0) { for (__auto_type l = call->monologues.head; l; l = l->next) { monologue = l->data; enum block_dtmf_mode prev_ml_mode = BLOCK_DTMF_OFF; if (flags.all == ALL_ALL) { prev_ml_mode = monologue->block_dtmf; monologue->block_dtmf = BLOCK_DTMF_OFF; } if (flags.delay_buffer >= 0) { for (unsigned int i = 0; i < monologue->medias->len; i++) { struct call_media *media = monologue->medias->pdata[i]; if (!media) continue; media->buffer_delay = flags.delay_buffer; } } bf_set_clear(&monologue->ml_flags, ML_FLAG_DETECT_DTMF, flags.detect_dtmf); if (is_dtmf_replace_mode(prev_ml_mode) || is_dtmf_replace_mode(prev_mode) || flags.delay_buffer >= 0) codec_update_all_handlers(monologue); } } } return NULL; } static const char *call_block_silence_media(ng_command_ctx_t *ctx, bool on_off, const char *ucase_verb, const char *lcase_verb, unsigned int call_flag, unsigned int ml_flag, size_t attr_offset) { g_autoptr(call_t) call = NULL; struct call_monologue *monologue; const char *errstr = NULL; g_auto(sdp_ng_flags) flags; bool found_subscriptions = false; errstr = media_block_match(&call, &monologue, &flags, ctx); if (errstr) return errstr; /* from-monologue is given */ if (monologue) { /* potential sinks (medias) towards from-monologue, * not particularly subscribed */ bool sinks = false; /* to-monologue is given */ if (flags.to_tag.len || flags.to_label.len) { struct call_monologue *sink_ml = NULL; /* to-monologue is given, check using to-tag */ if (flags.to_tag.len) { sink_ml = t_hash_table_lookup(call->tags, &flags.to_tag); if (!sink_ml) { ilog(LOG_WARN, "Media flow '" STR_FORMAT_M "' -> '" STR_FORMAT_M "' doesn't " "exist for media %s (to-tag not found)", STR_FMT_M(&monologue->tag), STR_FMT_M(&flags.to_tag), lcase_verb); return "Media flow not found (to-tag not found)"; } /* to-monologue is given, check using to-label */ } else { sink_ml = t_hash_table_lookup(call->labels, &flags.to_label); if (!sink_ml) { ilog(LOG_WARN, "Media flow '" STR_FORMAT_M "' -> label '" STR_FORMAT "' doesn't " "exist for media %s (to-label not found)", STR_FMT_M(&monologue->tag), STR_FMT(&flags.to_label), lcase_verb); return "Media flow not found (to-label not found)"; } } /* now check if any sink ml media is susbcribed to any of monologue medias */ for (int i = 0; i < sink_ml->medias->len; i++) { struct call_media * sink_md = monologue->medias->pdata[i]; if (!sink_md) continue; for (int j = 0; j < monologue->medias->len; j++) { struct call_media * ml_media = monologue->medias->pdata[j]; if (!ml_media) continue; subscription_list * ll = t_hash_table_lookup(ml_media->media_subscriptions_ht, sink_md); if (ll) { found_subscriptions = true; G_STRUCT_MEMBER(bool, &ll->data->attrs, attr_offset) = on_off; ilog(LOG_INFO, "%s directional media flow: " "monologue tag '" STR_FORMAT_M "' -> '" STR_FORMAT_M "' / " "media index '%d' -> '%d'", ucase_verb, STR_FMT_M(&monologue->tag), STR_FMT_M(&ll->data->monologue->tag), ml_media->index, ll->data->media->index); } } sinks = true; } /* one of the "all" flags is given, to-subscriptions */ } else if (flags.all == ALL_OFFER_ANSWER || flags.all == ALL_NON_OFFER_ANSWER || flags.all == ALL_FLOWS) { for (int i = 0; i < monologue->medias->len; i++) { struct call_media * ml_media = monologue->medias->pdata[i]; if (!ml_media) continue; for (__auto_type sub = ml_media->media_subscribers.head; sub; sub = sub->next) { struct media_subscription * ms = sub->data; struct call_media * sub_md = ms->media; if (!sub_md || (flags.all == ALL_OFFER_ANSWER && !ms->attrs.offer_answer) || (flags.all == ALL_NON_OFFER_ANSWER && ms->attrs.offer_answer)) { continue; } ilog(LOG_INFO, "%s directional media flow: " "monologue tag '" STR_FORMAT_M "' -> '" STR_FORMAT_M "' / " "media index '%d' -> '%d'", ucase_verb, STR_FMT_M(&monologue->tag), STR_FMT_M(&sub_md->monologue->tag), ml_media->index, sub_md->index); found_subscriptions = true; G_STRUCT_MEMBER(bool, &ms->attrs, attr_offset) = on_off; sinks = true; } } /* having an empty sinks list is an error, as "all" would be nothing */ if (!sinks) { ilog(LOG_WARN, "No eligible media subscriptions found for '" STR_FORMAT_M "' " "for media %s", STR_FMT_M(&monologue->tag), lcase_verb); return "No eligible media subscriptions found"; } } /* media sinks */ if (sinks) { if (!found_subscriptions) { /* no one of sink medias is subscribed to monologue medias */ ilog(LOG_WARN, "Media flow '" STR_FORMAT_M "' -> '" STR_FORMAT_M "' doesn't " "exist for media %s (to-tag not subscribed)", STR_FMT_M(&monologue->tag), STR_FMT_M(&flags.to_tag), lcase_verb); return "Media flow not found (to-tag not subscribed)"; } update_init_monologue_subscribers(monologue, OP_BLOCK_SILENCE_MEDIA); } else { /* it seems no to-monologue is given and no "all" flag is given as well. * In this case the from-monologue itself is flagged, * and not any of the media flows (subscription objects) */ ilog(LOG_INFO, "%s directional media (tag '" STR_FORMAT_M "')", ucase_verb, STR_FMT_M(&monologue->tag)); bf_set_clear(&monologue->ml_flags, ml_flag, on_off); } __monologue_unconfirm(monologue, "media silencing signalling event"); } else { bf_set_clear(&call->call_flags, call_flag, on_off); if (!on_off) { ilog(LOG_INFO, "%s media (entire call and participants)", ucase_verb); if (flags.all == ALL_ALL) { for (__auto_type l = call->monologues.head; l; l = l->next) { monologue = l->data; bf_set_clear(&monologue->ml_flags, ml_flag, on_off); } } } else { ilog(LOG_INFO, "%s media (entire call)", ucase_verb); } __call_unkernelize(call, "media silencing signalling event"); } return NULL; } #define CALL_BLOCK_SILENCE_MEDIA(ctx, on_off, ucase_verb, lcase_verb, member_name, flag) \ call_block_silence_media(ctx, on_off, ucase_verb, lcase_verb, \ CALL_FLAG_ ## flag, \ ML_FLAG_ ## flag, \ G_STRUCT_OFFSET(struct sink_attrs, member_name)) const char *call_block_media_ng(ng_command_ctx_t *ctx) { return CALL_BLOCK_SILENCE_MEDIA(ctx, true, "Blocking", "blocking", block_media, BLOCK_MEDIA); } const char *call_unblock_media_ng(ng_command_ctx_t *ctx) { return CALL_BLOCK_SILENCE_MEDIA(ctx, false, "Unblocking", "unblocking", block_media, BLOCK_MEDIA); } const char *call_silence_media_ng(ng_command_ctx_t *ctx) { return CALL_BLOCK_SILENCE_MEDIA(ctx, true, "Silencing", "silencing", silence_media, SILENCE_MEDIA); } const char *call_unsilence_media_ng(ng_command_ctx_t *ctx) { return CALL_BLOCK_SILENCE_MEDIA(ctx, false, "Unsilencing", "unsilencing", silence_media, SILENCE_MEDIA); } #ifdef WITH_TRANSCODING static const char *play_media_select_party(call_t **call, monologues_q *monologues, ng_command_ctx_t *ctx, sdp_ng_flags *flags) { struct call_monologue *monologue; t_queue_init(monologues); const char *err = media_block_match(call, &monologue, flags, ctx); if (err) return err; if (flags->all == ALL_ALL) t_queue_append(monologues, &(*call)->monologues); else if (!monologue) return "No participant party specified"; else t_queue_push_tail(monologues, monologue); return NULL; } #endif const char *call_play_media_ng(ng_command_ctx_t *ctx) { #ifdef WITH_TRANSCODING g_autoptr(call_t) call = NULL; g_auto(monologues_q) monologues; const char *err = NULL; g_auto(sdp_ng_flags) flags; const ng_parser_t *parser = ctx->parser_ctx.parser; err = play_media_select_party(&call, &monologues, ctx, &flags); if (err) return err; for (__auto_type l = monologues.head; l; l = l->next) { struct call_monologue *monologue = l->data; media_player_opts_t opts = MPO( .repeat = flags.repeat_times, .duration_spent = flags.repeat_duration, .start_pos = flags.start_pos, .block_egress = !!flags.block_egress, .codec_set = flags.codec_set, .file = flags.file, .blob = flags.blob, .db_id = flags.db_id, ); err = call_play_media_for_ml(monologue, opts, &flags); if (err) return err; if (l == monologues.head && monologue->player->coder.duration) parser->dict_add_int(ctx->resp, "duration", monologue->player->coder.duration); } return NULL; #else return "unsupported"; #endif } const char *call_stop_media_ng(ng_command_ctx_t *ctx) { #ifdef WITH_TRANSCODING g_autoptr(call_t) call = NULL; g_auto(monologues_q) monologues; const char *err = NULL; long long last_frame_pos = 0; g_auto(sdp_ng_flags) flags; const ng_parser_t *parser = ctx->parser_ctx.parser; err = play_media_select_party(&call, &monologues, ctx, &flags); if (err) return err; for (__auto_type l = monologues.head; l; l = l->next) { struct call_monologue *monologue = l->data; if (!monologue->player) return "Not currently playing media"; last_frame_pos = call_stop_media_for_ml(monologue); } parser->dict_add_int(ctx->resp, "last-frame-pos", last_frame_pos); return NULL; #else return "unsupported"; #endif } const char *call_play_dtmf_ng(ng_command_ctx_t *ctx) { #ifdef WITH_TRANSCODING g_autoptr(call_t) call = NULL; g_auto(monologues_q) monologues; const char *err = NULL; g_auto(sdp_ng_flags) flags; err = play_media_select_party(&call, &monologues, ctx, &flags); if (err) return err; // validate input parameters if (!flags.duration) flags.duration = 250; if (flags.duration < 100) { flags.duration = 100; ilog(LOG_WARN, "Invalid duration (%lli ms) specified, using 100 ms instead", flags.duration); } else if (flags.duration > 5000) { flags.duration = 5000; ilog(LOG_WARN, "Invalid duration (%lli ms) specified, using 5000 ms instead", flags.duration); } if (!flags.pause) flags.pause = 100; if (flags.pause < 100) { flags.pause = 100; ilog(LOG_WARN, "Invalid pause (%lli ms) specified, using 100 ms instead", flags.pause); } else if (flags.pause > 5000) { flags.pause = 5000; ilog(LOG_WARN, "Invalid pause (%lli ms) specified, using 5000 ms instead", flags.pause); } int code; if (dtmf_code_to_char(flags.digit)) code = flags.digit; // already a code else code = dtmf_code_from_char(flags.digit); // convert digit to code if (code < 0) return "Out of range 'code' specified"; else if (code > 15) return "Out of range 'code' specified"; if (flags.volume > 0) flags.volume *= -1; for (__auto_type l = monologues.head; l; l = l->next) { struct call_monologue *monologue = l->data; // find a usable output media struct call_media *media; for (unsigned int i = 0; i < monologue->medias->len; i++) { media = monologue->medias->pdata[i]; if (!media) continue; if (media->type_id != MT_AUDIO) continue; goto found; } return "Monologue has no media capable of DTMF injection"; // XXX fall back to generating a secondary stream found: ML_SET(monologue, DTMF_INJECTION_ACTIVE); dialogue_unconfirm(monologue, "DTMF playback"); for (unsigned int i = 0; i < monologue->medias->len; i++) { struct call_media *ml_media = monologue->medias->pdata[i]; if (!ml_media) continue; struct call_media * ms_media_sink = NULL; for (__auto_type ll = ml_media->media_subscribers.head; ll; ll = ll->next) { struct media_subscription * ms = ll->data; ms_media_sink = ms->media; if (!ms_media_sink || ms_media_sink->type_id != MT_AUDIO) continue; goto found_sink; } return "There is no sink media capable of DTMF playback"; found_sink: err = dtmf_inject(media, code, flags.volume, flags.duration, flags.pause, ms_media_sink); if (err) return err; } } return NULL; #else return "unsupported"; #endif } const char *call_publish_ng(ng_command_ctx_t *ctx, const char *addr) { g_auto(sdp_ng_flags) flags; g_auto(sdp_sessions_q) parsed = TYPED_GQUEUE_INIT; g_auto(sdp_streams_q) streams = TYPED_GQUEUE_INIT; str sdp_in = STR_NULL; g_auto(str) sdp_out = STR_NULL; g_autoptr(call_t) call = NULL; int ret; const ng_parser_t *parser = ctx->parser_ctx.parser; call_ng_process_flags(&flags, ctx); if ((ret = call_ng_basic_checks(&flags)) > 0) return _ng_basic_errors[ret]; call = call_get_or_create(&flags.call_id, false); sdp_in = call_str_cpy(&flags.sdp); if (sdp_parse(&sdp_in, &parsed, &flags)) return "Failed to parse SDP"; if (sdp_streams(&parsed, &streams, &flags)) return "Incomplete SDP specification"; if (trickle_ice_update(ctx->ngbuf, call, &flags, &streams)) return NULL; updated_created_from(call, addr); struct call_monologue *ml = call_get_or_create_monologue(call, &flags.from_tag); ret = monologue_publish(ml, &streams, &flags); if (ret) ilog(LOG_ERR, "Publish error"); // XXX close call? handle errors? ret = sdp_create(&sdp_out, ml, &flags); if (!ret) { save_last_sdp(ml, &sdp_in, &parsed, &streams); ctx->ngbuf->sdp_out = sdp_out.s; parser->dict_add_str(ctx->resp, "sdp", &sdp_out); sdp_out = STR_NULL; // ownership passed to output } if (ret) return "Failed to create SDP"; dequeue_sdp_fragments(ml); call_unlock_release_update(&call); return NULL; } const char *call_subscribe_request_ng(ng_command_ctx_t *ctx) { const char *err = NULL; g_auto(sdp_ng_flags) flags; char rand_buf[65]; g_autoptr(call_t) call = NULL; g_auto(subscription_q) srms = TYPED_GQUEUE_INIT; g_auto(str) sdp_out = STR_NULL; parser_arg output = ctx->resp; const ng_parser_t *parser = ctx->parser_ctx.parser; /* get source monologue */ err = media_block_match_mult(&call, &srms, &flags, ctx); if (err) return err; if (flags.sdp.len) ilog(LOG_INFO, "Subscribe-request with SDP received - ignoring SDP"); if (!srms.length) return "No call participants specified (no medias found)"; /* the `label=` option was possibly used above to select the from-tag -- * switch it out with `to-label=` or `set-label=` for monologue_subscribe_request * below which sets the label based on `label` for a newly created monologue */ flags.label = flags.to_label; if (flags.set_label.len) // set-label takes priority flags.label = flags.set_label; /* get destination monologue */ if (!flags.to_tag.len) { /* generate one */ flags.to_tag = STR_CONST(rand_buf); rand_hex_str(flags.to_tag.s, flags.to_tag.len / 2); } struct call_monologue *dest_ml = call_get_or_create_monologue(call, &flags.to_tag); int ret = monologue_subscribe_request(&srms, dest_ml, &flags); if (ret) return "Failed to request subscription"; /* create new SDP */ ret = sdp_create(&sdp_out, dest_ml, &flags); if (ret) return "Failed to create SDP"; /* place return output SDP */ if (sdp_out.len) { ctx->ngbuf->sdp_out = sdp_out.s; parser->dict_add_str(output, "sdp", &sdp_out); sdp_out = STR_NULL; /* ownership passed to output */ } /* add single response ml tag if there's just one, but always add a list * TODO: deprecate it, since initially added for monologue subscriptions. */ if (srms.length == 1) { struct media_subscription *ms = srms.head->data; struct call_monologue *source_ml = ms->monologue; parser->dict_add_str_dup(output, "from-tag", &source_ml->tag); } parser_arg tag_medias = {0}, media_labels = {0}; if (flags.siprec) { tag_medias = parser->dict_add_list(output, "tag-medias"); media_labels = parser->dict_add_dict(output, "media-labels"); } parser_arg from_list = parser->dict_add_list(output, "from-tags"); for (__auto_type l = srms.head; l; l = l->next) { struct media_subscription *ms = l->data; struct call_monologue *source_ml = ms->monologue; parser->list_add_str_dup(from_list, &source_ml->tag); if (tag_medias.gen) { parser_arg tag_label = parser->list_add_dict(tag_medias); parser->dict_add_str(tag_label, "tag", &source_ml->tag); if (source_ml->label.len) parser->dict_add_str(tag_label, "label", &source_ml->label); parser_arg medias = parser->dict_add_list(tag_label, "medias"); for (unsigned int i = 0; i < source_ml->medias->len; i++) { struct call_media *media = source_ml->medias->pdata[i]; if (!media) continue; parser_arg med_ent = parser->list_add_dict(medias); parser->dict_add_int(med_ent, "index", media->index); parser->dict_add_str(med_ent, "type", &media->type); parser->dict_add_str(med_ent, "label", &media->label); parser->dict_add_string(med_ent, "mode", sdp_get_sendrecv(media)); if (media_labels.gen) { parser_arg label = parser->dict_add_dict(media_labels, media->label.s); parser->dict_add_str(label, "tag", &source_ml->tag); parser->dict_add_int(label, "index", media->index); parser->dict_add_str(label, "type", &media->type); if (source_ml->label.len) parser->dict_add_str(label, "label", &source_ml->label); parser->dict_add_string(label, "mode", sdp_get_sendrecv(media)); } } } } parser->dict_add_str_dup(output, "to-tag", &dest_ml->tag); dequeue_sdp_fragments(dest_ml); call_unlock_release_update(&call); return NULL; } const char *call_subscribe_answer_ng(ng_command_ctx_t *ctx) { g_auto(sdp_ng_flags) flags; g_auto(sdp_sessions_q) parsed = TYPED_GQUEUE_INIT; g_auto(sdp_streams_q) streams = TYPED_GQUEUE_INIT; g_autoptr(call_t) call = NULL; call_ng_process_flags(&flags, ctx); if (!flags.call_id.s) return "No call-id in message"; call = call_get(&flags.call_id); if (!call) return "Unknown call-ID"; if (sdp_parse(&flags.sdp, &parsed, &flags)) return "Failed to parse SDP"; if (sdp_streams(&parsed, &streams, &flags)) return "Incomplete SDP specification"; if (trickle_ice_update(ctx->ngbuf, call, &flags, &streams)) return NULL; if (!flags.to_tag.s) return "No to-tag in message"; if (!flags.sdp.len) return "No SDP body in message"; // get destination monologue struct call_monologue *dest_ml = call_get_monologue(call, &flags.to_tag); if (!dest_ml) return "To-tag not found"; int ret = monologue_subscribe_answer(dest_ml, &flags, &streams); if (ret) return "Failed to process subscription answer"; call_unlock_release_update(&call); return NULL; } const char *call_unsubscribe_ng(ng_command_ctx_t *ctx) { g_auto(sdp_ng_flags) flags; g_autoptr(call_t) call = NULL; call_ng_process_flags(&flags, ctx); if (!flags.call_id.s) return "No call-id in message"; call = call_get(&flags.call_id); if (!call) return "Unknown call-ID"; if (!flags.to_tag.s) return "No to-tag in message"; // get destination monologue struct call_monologue *dest_ml = call_get_or_create_monologue(call, &flags.to_tag); if (!dest_ml) return "To-tag not found"; int ret = monologue_unsubscribe(dest_ml, &flags); if (ret) return "Failed to unsubscribe"; call_unlock_release_update(&call); return NULL; } const char *call_connect_ng(ng_command_ctx_t *ctx) { g_auto(sdp_ng_flags) flags; g_autoptr(call_t) call = NULL; g_autoptr(call_t) call2 = NULL; call_ng_process_flags(&flags, ctx); if (!flags.call_id.s) return "No call-id in message"; if (!flags.from_tag.s) return "No from-tag in message"; if (!flags.to_tag.s) return "No to-tag in message"; if (flags.to_call_id.s) { call_get2_ret_t ret = call_get2(&call, &call2, &flags.call_id, &flags.to_call_id); if (ret == CG2_NF1) return "Unknown call-ID"; if (ret == CG2_NF2) return "Unknown to-tag call-ID"; } else { call = call_get(&flags.call_id); if (!call) return "Unknown call-ID"; } struct call_monologue *src_ml = call_get_or_create_monologue(call, &flags.from_tag); if (!src_ml) return "From-tag not found"; struct call_monologue *dest_ml = call_get_or_create_monologue(call2 ?: call, &flags.to_tag); if (!dest_ml) return "To-tag not found"; if (src_ml == dest_ml) return "Trying to connect to self"; // XXX should this be allowed? if (call2) { if (!call_merge(call, &call2)) return "Failed to merge two calls into one"; } dialogue_connect(src_ml, dest_ml, &flags); call_unlock_release_update(&call); return NULL; } const char *call_transform_ng(ng_command_ctx_t *ctx) { g_auto(sdp_ng_flags) flags; g_autoptr(call_t) call = NULL; /* * { * command: transform * [ call-id: ... ] * [ from-tag: ... ] * [ instance: ... ] * [ interface: ... ] * media: [ * { * [ id: ... ] * type: audio/video/... * codec: [ * { * input: { * codec: G729 * payload type: 18 * clock rate: 8000 * channels: 1 * [ format: annexb=no ] * [ options: bitrate=xxx ] * }, * output: { * ... * }, * }, ... * ], * destination: { * family: IP4 * address: 127.0.0.1 * port: 4444 * }, * }, * ... * ] * } */ call_ng_process_flags(&flags, ctx); if (flags.instance.len && !str_cmp_str(&rtpe_instance_id, &flags.instance)) return "Transform loop detected"; char rand_call_id[65]; if (!flags.call_id.len) flags.call_id = STR_LEN(rand_hex_str(rand_call_id, 32), 64); char rand_from_tag[65]; if (!flags.from_tag.len) flags.from_tag = STR_LEN(rand_hex_str(rand_from_tag, 32), 64); call = call_get_or_create(&flags.call_id, false); struct call_monologue *ml = call_get_or_create_monologue(call, &flags.from_tag); g_auto(medias_q) mq = TYPED_GQUEUE_INIT; if (!monologue_transform(ml, &flags, &mq)) return "Failed to set up transform"; const ng_parser_t *parser = ctx->parser_ctx.parser; parser->dict_add_str_dup(ctx->resp, "call-id", &call->callid); parser->dict_add_str_dup(ctx->resp, "from-tag", &ml->tag); parser_arg list = parser->dict_add_list(ctx->resp, "media"); for (__auto_type l = mq.head; l; l = l->next) { __auto_type m = l->data; parser_arg dict = parser->list_add_dict(list); parser->dict_add_str_dup(dict, "id", &m->media_id); __auto_type ps = m->streams.head->data; __auto_type sfd = ps->selected_sfd; parser->dict_add_str(dict, "family", STR_PTR(sfd->socket.local.address.family->rfc_name)); parser->dict_add_str_dup(dict, "address", STR_PTR(sockaddr_print_buf(&sfd->socket.local.address))); parser->dict_add_int(dict, "port", sfd->socket.local.port); } call_unlock_release_update(&call); return NULL; } void call_interfaces_free(void) { if (info_re) { pcre2_code_free(info_re); info_re = NULL; } if (streams_re) { pcre2_code_free(streams_re); streams_re= NULL; } t_hash_table_destroy(rtpe_signalling_templates); } static void parse_templates(charp_ht templates) { if (!t_hash_table_is_set(templates)) return; charp_ht_iter iter; t_hash_table_iter_init(&iter, templates); char *keyp, *valuep; while (t_hash_table_iter_next(&iter, &keyp, &valuep)) { char *key = keyp; char *value = valuep; t_hash_table_insert(rtpe_signalling_templates, str_dup(STR_PTR(key)), str_dup(STR_PTR(value))); } // look for templates matching known commands for (unsigned int i = 0; i < OP_COUNT; i++) { const char *cmd = ng_command_strings[i]; str *tmpl = t_hash_table_lookup(rtpe_signalling_templates, STR_PTR(cmd)); if (tmpl) rtpe_default_signalling_templates[i] = *tmpl; } // finally look for "default" and store it in the OTHER slot str *tmpl = t_hash_table_lookup(rtpe_signalling_templates, STR_PTR("default")); if (tmpl) rtpe_default_signalling_templates[OP_OTHER] = *tmpl; } int call_interfaces_init(charp_ht templates) { int errcode; PCRE2_SIZE erroff; info_re = pcre2_compile((PCRE2_SPTR8) "^([^:,]+)(?::(.*?))?(?:$|,)", PCRE2_ZERO_TERMINATED, PCRE2_DOLLAR_ENDONLY | PCRE2_DOTALL, &errcode, &erroff, NULL); if (!info_re) return -1; streams_re = pcre2_compile((PCRE2_SPTR8) "^([\\d.]+):(\\d+)(?::(.*?))?(?:$|,)", PCRE2_ZERO_TERMINATED, PCRE2_DOLLAR_ENDONLY | PCRE2_DOTALL, &errcode, &erroff, NULL); if (!streams_re) return -1; rtpe_signalling_templates = str_case_value_ht_new(); parse_templates(templates); return 0; } rtpengine-mr13.5.1.3/daemon/cdr.c000066400000000000000000000137271512121055300164600ustar00rootroot00000000000000#include "cdr.h" #include #include "rtplib.h" #include "call.h" #include "poller.h" #include "str.h" #define CDRBUFREMAINDER cdrbufend-cdrbufcur static const char * const __term_reason_texts[] = { [TIMEOUT] = "TIMEOUT", [REGULAR] = "REGULAR", [FORCED] = "FORCED", [SILENT_TIMEOUT] = "SILENT_TIMEOUT", [FINAL_TIMEOUT] = "FINAL_TIMEOUT", [OFFER_TIMEOUT] = "OFFER_TIMEOUT", }; static const char * const __tag_type_texts[] = { [FROM_TAG] = "FROM_TAG", [TO_TAG] = "TO_TAG", }; const char * get_tag_type_text(enum tag_type t) { return get_enum_array_text(__tag_type_texts, t, "UNKNOWN"); } const char *get_opmode_text(enum ng_opmode m) { return get_enum_array_text(ng_command_strings, m, "other"); } static const char * get_term_reason_text(enum termination_reason t) { return get_enum_array_text(__term_reason_texts, t, "UNKNOWN"); } void cdr_update_entry(call_t * c) { struct call_monologue *ml; int64_t tim_result_duration; int cdrlinecnt = 0; g_autoptr(GString) cdr = g_string_new(""); struct call_media *md; const rtp_payload_type *rtp_pt; struct packet_stream *ps=0; if (!IS_OWN_CALL(c)) return; /* CDRs and statistics */ if (_log_facility_cdr) { g_string_append_printf(cdr, "ci=%s, ",c->callid.s); g_string_append_printf(cdr, "created_from=" STR_FORMAT ", ", STR_FMT(&c->created_from)); g_string_append_printf(cdr, "last_signal=%" PRId64 ", ", c->last_signal_us / 1000000L); g_string_append_printf(cdr, "tos=%u, ", (unsigned int)c->tos); } for (__auto_type l = c->monologues.head; l; l = l->next) { ml = l->data; if (!ml->terminated) { ml->terminated = rtpe_now; ml->term_reason = UNKNOWN; } tim_result_duration = ml->terminated - ml->started; if (_log_facility_cdr) { g_string_append_printf(cdr, "ml%i_start_time=%" PRId64 ".%06" PRId64 ", " "ml%i_end_time=%" PRId64 ".%06" PRId64 ", " "ml%i_duration=%" PRId64 ".%06" PRId64 ", " "ml%i_termination=%s, " "ml%i_local_tag=%s, " "ml%i_local_tag_type=%s, ", cdrlinecnt, ml->started / 1000000, ml->started % 1000000, cdrlinecnt, ml->terminated / 1000000, ml->terminated % 1000000, cdrlinecnt, tim_result_duration / 1000000, tim_result_duration % 1000000, cdrlinecnt, get_term_reason_text(ml->term_reason), cdrlinecnt, ml->tag.s, cdrlinecnt, get_tag_type_text(ml->tagtype)); g_auto(GQueue) mls = G_QUEUE_INIT; /* to avoid duplications */ for (int i = 0; i < ml->medias->len; i++) { struct call_media * media = ml->medias->pdata[i]; if (!media) continue; for (__auto_type sub = media->media_subscriptions.head; sub; sub = sub->next) { struct media_subscription * ms = sub->data; if (!g_queue_find(&mls, ms->monologue)) { g_string_append_printf(cdr, "ml%i_remote_tag=%s, ", cdrlinecnt, ms->monologue->tag.s); g_queue_push_tail(&mls, ms->monologue); } } } } for (unsigned int i = 0; i < ml->medias->len; i++) { md = ml->medias->pdata[i]; if (!md) continue; rtp_pt = __rtp_stats_codec(md); /* add PayloadType(codec) info in CDR logging */ if (_log_facility_cdr && rtp_pt) { g_string_append_printf(cdr, "payload_type=%u, ", rtp_pt->payload_type); } else if (_log_facility_cdr && !rtp_pt) { g_string_append_printf(cdr, "payload_type=unknown, "); } for (__auto_type o = md->streams.head; o; o = o->next) { ps = o->data; if (PS_ISSET(ps, FALLBACK_RTCP)) continue; char *addr = sockaddr_print_buf(&ps->endpoint.address); char *local_addr = sockaddr_print_buf(&ps->last_local_endpoint.address); if (_log_facility_cdr) { const char* protocol = (!PS_ISSET(ps, RTP) && PS_ISSET(ps, RTCP)) ? "rtcp" : "rtp"; if(!PS_ISSET(ps, RTP) && PS_ISSET(ps, RTCP)) { g_string_append_printf(cdr, "ml%i_midx%u_%s_endpoint_ip=%s, " "ml%i_midx%u_%s_endpoint_port=%u, " "ml%i_midx%u_%s_local_relay_ip=%s, " "ml%i_midx%u_%s_local_relay_port=%u, " "ml%i_midx%u_%s_relayed_packets=%" PRIu64 ", " "ml%i_midx%u_%s_relayed_bytes=%" PRIu64 ", " "ml%i_midx%u_%s_relayed_errors=%" PRIu64 ", " "ml%i_midx%u_%s_last_packet=%" PRIu64 ", " "ml%i_midx%u_%s_in_tos_tclass=%" PRIu8 ", ", cdrlinecnt, md->index, protocol, addr, cdrlinecnt, md->index, protocol, ps->endpoint.port, cdrlinecnt, md->index, protocol, local_addr, cdrlinecnt, md->index, protocol, ps->last_local_endpoint.port, cdrlinecnt, md->index, protocol, atomic64_get_na(&ps->stats_in->packets), cdrlinecnt, md->index, protocol, atomic64_get_na(&ps->stats_in->bytes), cdrlinecnt, md->index, protocol, atomic64_get_na(&ps->stats_in->errors), cdrlinecnt, md->index, protocol, packet_stream_last_packet(ps) / 1000000L, cdrlinecnt, md->index, protocol, atomic_get_na(&ps->stats_in->tos)); } else { g_string_append_printf(cdr, "ml%i_midx%u_%s_endpoint_ip=%s, " "ml%i_midx%u_%s_endpoint_port=%u, " "ml%i_midx%u_%s_local_relay_ip=%s, " "ml%i_midx%u_%s_local_relay_port=%u, " "ml%i_midx%u_%s_relayed_packets=%" PRIu64 ", " "ml%i_midx%u_%s_relayed_bytes=%" PRIu64 ", " "ml%i_midx%u_%s_relayed_errors=%" PRIu64 ", " "ml%i_midx%u_%s_last_packet=%" PRIu64 ", " "ml%i_midx%u_%s_in_tos_tclass=%" PRIu8 ", ", cdrlinecnt, md->index, protocol, addr, cdrlinecnt, md->index, protocol, ps->endpoint.port, cdrlinecnt, md->index, protocol, local_addr, cdrlinecnt, md->index, protocol, ps->last_local_endpoint.port, cdrlinecnt, md->index, protocol, atomic64_get_na(&ps->stats_in->packets), cdrlinecnt, md->index, protocol, atomic64_get_na(&ps->stats_in->bytes), cdrlinecnt, md->index, protocol, atomic64_get_na(&ps->stats_in->errors), cdrlinecnt, md->index, protocol, packet_stream_last_packet(ps) / 1000000L, cdrlinecnt, md->index, protocol, atomic_get_na(&ps->stats_in->tos)); } } } } if (_log_facility_cdr) ++cdrlinecnt; } /* log it */ cdrlog(cdr->str); } rtpengine-mr13.5.1.3/daemon/cli.c000066400000000000000000002350711512121055300164550ustar00rootroot00000000000000#include "cli.h" #include #include #include #include #include #include #include #include #include #include #include #include "poller.h" #include "helpers.h" #include "log.h" #include "log_funcs.h" #include "call.h" #include "socket.h" #include "redis.h" #include "control_ng.h" #include "media_socket.h" #include "cdr.h" #include "streambuf.h" #include "tcp_listener.h" #include "str.h" #include "statistics.h" #include "main.h" #include "media_socket.h" #include "rtplib.h" #include "ssrc.h" #include "codec.h" #include "media_player.h" typedef struct cli_handler_t cli_handler_t; typedef struct cli_command_t cli_command_t; typedef void (*cli_handler_func)(str *, struct cli_writer *, const cli_handler_t *); struct cli_command_t { const char *cmd; cli_handler_func handler; const cli_handler_t *next; const char *params; const char *help; }; struct cli_handler_t { unsigned int section; const cli_command_t *commands; unsigned int num_commands; }; static void cli_generic_handler(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_terminate(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_ksadd(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_ksrm(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_kslist(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_active(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_standby(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_debug(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_call(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_usage(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_maxopenfiles(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_maxsessions(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_maxcpu(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_maxload(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_maxbw(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_timeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_silenttimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_offertimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_finaltimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_loglevel(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_redisallowederrors(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_redisdisabletime(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_redisdisable(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_redisconnecttimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_rediscmdtimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_controltos(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_set_deletedelay(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_params_start(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_params_current(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_params_diff(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_params_revert(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_numsessions(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_maxsessions(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_maxcpu(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_maxload(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_maxbw(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_maxopenfiles(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_totals(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_counters(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_sessions(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_timeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_silenttimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_offertimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_finaltimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_loglevel(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_loglevels(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_redisallowederrors(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_redisdisabletime(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_redisconnecttimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_rediscmdtimeout(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_controltos(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_deletedelay(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_interfaces(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_jsonstats(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_list_transcoders(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_call_info(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_call_terminate(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_call_debug(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_call_tag(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_tag_info(str *instr, struct cli_writer *cw, const cli_handler_t *); #ifdef WITH_TRANSCODING static void cli_incoming_tag_delay(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_tag_detdtmf(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_list_files(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_list_dbs(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_list_caches(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_list_players(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_reload_file(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_reload_files(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_reload_db(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_reload_dbs(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_reload_cache(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_reload_caches(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_add_file(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_add_db(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_add_cache(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_file(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_files(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_db(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_dbs(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_cache(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_caches(str *instr, struct cli_writer *cw, const cli_handler_t *); static void cli_incoming_media_evict_players(str *instr, struct cli_writer *cw, const cli_handler_t *); #endif #define HANDLER_START(n) static const cli_handler_t n = { .section = CSH_SECTION, .commands = (const struct cli_command_t []) { #define HANDLER_CMD(c, f, p, s) [CSH_LOOKUP(c)] = { .cmd = c, .handler = f, .params = p, .help = s }, #define HANDLER_GENERIC(c, h) [CSH_LOOKUP(c)] = { .cmd = c, .handler = cli_generic_handler, .next = &h, .params = "