├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── SECURITY.md ├── cmd ├── call-api-client │ └── main.go ├── call-api │ └── main.go └── call-cmd │ └── main.go ├── config ├── call-api.yml └── call-cmd.yml ├── docs ├── Commands.md └── README.md ├── examples └── javascript │ ├── call-api.js │ └── index.html ├── go.mod ├── go.sum ├── images └── logo │ ├── call-api-logo-short.png │ ├── call-api-logo-short.svg │ ├── call-api-logo-square.png │ ├── call-api-logo.png │ └── call-api-logo.svg ├── internal └── jsonrpc │ └── jsonrpc.go ├── pkg ├── cmd │ ├── call_attended_transfer.go │ ├── call_blind_transfer.go │ ├── call_end.go │ ├── call_hold.go │ ├── call_start.go │ ├── cmd.go │ ├── echo.go │ ├── event.go │ └── test.go ├── config │ └── config.go ├── event │ ├── datagram.go │ └── event.go ├── mi │ ├── datagram.go │ └── mi.go ├── proxy │ └── proxy.go └── ws_server │ └── ws_server.go └── utils └── version.go /.gitignore: -------------------------------------------------------------------------------- 1 | /bin 2 | /main 3 | *.swp 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use the official Golang image as the base image 2 | FROM golang:1.14 3 | 4 | # Set the working directory 5 | WORKDIR /go/src/app 6 | 7 | COPY go.mod go.sum ./ 8 | 9 | # Download dependencies using Go modules 10 | RUN go get -d ./... 11 | 12 | COPY . . 13 | 14 | # Build the Call API tools and place them in the /go/bin directory 15 | RUN GOBIN=/usr/bin make install 16 | 17 | # Expose the WebSocket port 18 | EXPOSE 5059 19 | 20 | # Default is 'call-api' when the container starts 21 | # to run the others, simply override the CMD 22 | # docker run call-api-client 23 | # docker run call-cmd 24 | CMD ["call-api"] 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | GOPATH ?= $(HOME)/go 3 | GOBIN ?= $(GOPATH)/bin 4 | BUILD_DIR ?= bin 5 | CFG_BASE_DIR ?= /etc/call-api 6 | BUILD_FLAGS ?= -i 7 | GITREPO=github.com/OpenSIPS/call-api 8 | 9 | CMD_TOOLS=$(wildcard cmd/*/main.go) 10 | 11 | TOOLS?=$(patsubst cmd/%/main.go,%,$(CMD_TOOLS)) 12 | 13 | BUILD_TOOLS=$(addprefix $(BUILD_DIR)/,$(TOOLS)) 14 | INSTALL_TOOLS=$(addprefix $(GOBIN)/,$(TOOLS)) 15 | 16 | CFG_FILES=$(wildcard config/*.yml) 17 | CFG_TOOLS=$(filter $(patsubst config/%.yml,%,$(CFG_FILES)),$(TOOLS)) 18 | INSTALL_CFG_TOOLS=$(addsuffix .yml,$(addprefix $(CFG_BASE_DIR)/,$(CFG_TOOLS))) 19 | 20 | GIT_COMMIT := $(shell git rev-list -1 HEAD) 21 | BUILD_TIME := $(shell date +%Y%m%d%H%m%S) 22 | LDFLAGS := -ldflags "-X $(GITREPO)/utils.GitCommit=$(GIT_COMMIT) \ 23 | -X $(GITREPO)/utils.BuildTime=$(BUILD_TIME)" 24 | 25 | build: build-all 26 | 27 | install: install-all 28 | 29 | build-all: build-tools 30 | 31 | install-all: install-tools install-cfg 32 | 33 | install-cfg: $(INSTALL_CFG_TOOLS) 34 | 35 | build-tools: $(BUILD_DIR) $(BUILD_TOOLS) 36 | 37 | install-tools: $(GOBIN) $(INSTALL_TOOLS) 38 | 39 | $(BUILD_DIR) $(GOBIN) $(CFG_BASE_DIR): 40 | @mkdir -p $@ 41 | 42 | $(BUILD_DIR)/%: cmd/%/main.go 43 | go build $(BUILD_FLAGS) $(LDFLAGS) -o $@ $^ 44 | 45 | $(GOBIN)/%: cmd/%/main.go 46 | go install $(LDFLAGS) $^ && mv $(GOBIN)/main $@ 47 | 48 | $(CFG_BASE_DIR)/%.yml: config/%.yml $(CFG_BASE_DIR) 49 | @test -e $@ || cp $< $@ 2>/dev/null || cp $< $(HOME)/.$(notdir $@) 50 | 51 | .PHONY: clean 52 | clean: 53 | @rm -f $(BUILD_TOOLS) 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Call API](images/logo/call-api-logo.png "Call API") 2 | # Call API 3 | 4 | ---- 5 | 6 | The Call API is a front-end for SIP Proxies (such as [OpenSIPS](https://opensips.org)), aiming to simplify the management of more advanced SIP call flows. Combining built-in SIP scenarios (such as the ones from [RFC 5359](https://tools.ietf.org/html/rfc5359)) with real-time notifications as the call commands take place, the API is meant to help VoIP system developers build complex SIP services with ease, altogether while providing live reporting for such services. 7 | 8 | The API listens for [WebSocket](https://en.wikipedia.org/wiki/WebSocket) connections on `ws://localhost:5059/call-api` and talks [JSON-RPC 2.0](https://www.jsonrpc.org/specification) over them. 9 | 10 | ## Requirements 11 | 12 | ### Go version 13 | 14 | The Call API tool is using go modules, introduced in go 1.13, but the tool was 15 | developed based on go version 1.14. We recommend you install at least go 1.14 16 | using your distribution's repositories, or from the official 17 | [Golang repository](https://golang.org/dl/). 18 | 19 | ### SIP Proxy 20 | 21 | In order to be able to start and control calls, you need to have a running SIP 22 | proxy instance that is able to communicate with the Call API daemon through a 23 | supported communication mechanisms, and that is able to perform the required 24 | logic. Current supported SIP proxies and their requirements are: 25 | 26 | * [OpenSIPS](https://opensips.org) 27 | * [MI Datagram](https://opensips.org/docs/modules/3.1.x/mi_datagram.html) 28 | * [Event Datagram](https://opensips.org/docs/modules/3.1.x/event_datagram.html) 29 | * [Call OPerationS](https://opensips.org/docs/modules/3.1.x/callops.html) 30 | 31 | Please read more about each project's requirements on their website. 32 | 33 | ## Installation 34 | 35 | ### Download the sources 36 | 37 | You can either use git or go to download the Call API sources 38 | 39 | * Git 40 | * go to your sources directory (such as `/usr/local/src`) and clone the repository 41 | 42 | ``` 43 | git clone https://github.com/OpenSIPS/call-api.git 44 | cd call-api 45 | ``` 46 | 47 | * Go 48 | * (_optional_) set up your [`$GOPATH` variable](https://github.com/golang/go/wiki/SettingGOPATH), if not already provided: 49 | 50 | ``` 51 | go get github.com/OpenSIPS/call-api 52 | cd ${GOPATH:-$HOME/go}/src/github.com/OpenSIPS/call-api 53 | ``` 54 | 55 | ### Download dependencies 56 | 57 | ``` 58 | go get -d ./... 59 | ``` 60 | 61 | ### Manual run 62 | 63 | You can run the tools directly from the source code using the `go run` command: 64 | 65 | ``` 66 | go run cmd/call-api/main.go 67 | ``` 68 | 69 | ### Build packages 70 | 71 | The following command will build all tools and place them in the `bin/` folder of the project. 72 | 73 | ``` 74 | make build 75 | ``` 76 | 77 | After this command you can find all the binaries in the `bin/` directory. 78 | 79 | ### Install packages 80 | 81 | The following command install all tools in the `$GOBIN` directory, and all 82 | their configuration files in `/etc/call-api` directory. The default value of 83 | `$GOBIN` is `$GOPATH/bin` which defaults to `$HOME/go/bin`. Make sure to 84 | properly tune your `$GOBIN` variable if you want to install your binaries in a 85 | different place (for example set `GOBIN=/usr/bin` to install them in 86 | `/usr/bin`). 87 | 88 | ``` 89 | make install 90 | export PATH=$PATH:${GOBIN:-${GOPATH:-$HOME/go}/bin} 91 | call-api 92 | ``` 93 | 94 | Note that you can also use the go-flavor install `go install ./...`, but this 95 | will not install the configuration files. 96 | 97 | In order to install the binaries in a standard path (such as `/usr/bin`), make 98 | sure to overwrite the `$GOBIN` variable: 99 | 100 | ``` 101 | GOBIN=/usr/bin make install 102 | call-api 103 | ``` 104 | 105 | After the install is complete, you can find the configuration files in the 106 | `/etc/call-api` directory if you are running as `root`, or in 107 | `$HOME/..yml` otherwise. 108 | 109 | ## Tools 110 | 111 | The project builds and installs the following tools: 112 | 113 | * **[call-api](cmd/call-api/main.go)** - a WebSocket Server that listens for JSON-RPC requests 114 | * **[call-cmd](cmd/call-cmd/main.go)** - a command line tool that runs the command without having the `call-api` server running 115 | * **[call-api-client](cmd/call-api-client/main.go)** - a command line tool that sends JSON-RPC requests to the `call-api` daemon and prints the notifications at stdout 116 | 117 | ## Configuration 118 | 119 | Each tool uses a configuration file that defaults to `.yml` (ex: 120 | `call-api.yml` or `call-cmd.yml`). This file is automatically searched in the 121 | following places: `$HOME/..yml`, `config/.yml`, 122 | `/etc/.yml` and `/etc/call-api/.yml`, in this specific 123 | order. A custom path can be specified using the `-config cfg_file.yml` 124 | parameter when starting the tool (ex: `call-api -config /etc/custom-config.yml`). 125 | 126 | Examples of configuration files can be found in the [config](config/) directory. 127 | 128 | ## API Call Commands 129 | 130 | Below are the API's [commands](docs/Commands.md) available for building your JSON-RPC requests. Read the documentation of each command for a listing of its input parameters and their accepted values: 131 | 132 | * **[CallStart](docs/Commands.md#callstart)** - start a call between two participants 133 | * **[CallBlindTransfer](docs/Commands.md#callblindtransfer)** - perform an unattended call transfer (see [RFC 5359 example](https://tools.ietf.org/html/rfc5359#page-50)) 134 | * **[CallAttendedTransfer](docs/Commands.md#callattendedtransfer)** - perform an attended call transfer (see [RFC 5359 example](https://tools.ietf.org/html/rfc5359#page-58)) 135 | * **[CallHold](docs/Commands.md#callhold)** - put one or both participants on hold 136 | * **[CallUnhold](docs/Commands.md#callunhold)** - resume an on-hold call 137 | * **[CallEnd](docs/Commands.md#callend)** - terminate an ongoing call 138 | 139 | ## Interacting with the API 140 | 141 | By default, the API listens on `ws://localhost:5059/call-api`. Below is an example way of launching a `CallStart` command using an [API client written in Go](cmd/call-api-client/main.go): 142 | 143 | ``` 144 | go run cmd/call-api-client/main.go \ 145 | -method CallStart \ 146 | -params '{"caller": "sip:alice@localhost", "callee": "sip:bob@localhost"}' 147 | ``` 148 | 149 | The same behavior can be done using the [Call cmd](cmd/call-cmd/main.go) tool: 150 | ``` 151 | go run cmd/call-cmd/main.go CallStart caller=sip:alice@localhost callee=sip:bob@localhost 152 | ``` 153 | 154 | ## Documentation 155 | 156 | The [docs](docs/) folder contains the documentation for this project. 157 | 158 | ## Build and run docker containers 159 | 160 | You can build and run the three tools under a docker container. 161 | 162 | ```sh 163 | docker build -t opensips-call-api:latest . 164 | ``` 165 | 166 | By default the `call-api` will be run: 167 | 168 | ```sh 169 | > docker run opensips-call-api:latest 170 | time="2023-10-10T21:42:48Z" level=info msg="Listening for JSON-RPC over WebSocket on localhost:5059/call-api ..." 171 | ``` 172 | 173 | But, you can specify the `call-cmd` and `call-api-client` tools: 174 | 175 | ```sh 176 | docker run opensips-call-api:latest call-api-client \ 177 | -method CallStart \ 178 | -params '{"caller": "sip:alice@localhost", "callee": "sip:bob@localhost"}' 179 | ``` 180 | 181 | ```bash 182 | docker run opensips-call-api:latest call-cmd CallStart caller=sip:alice@localhost callee=sip:bob@localhost 183 | ``` 184 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | All available versions are eligible for security updates 6 | 7 | ## Reporting a Vulnerability 8 | 9 | For any security/vulnerability issues you may discover, please send us a full report at security@opensips.org. 10 | -------------------------------------------------------------------------------- /cmd/call-api-client/main.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package main 19 | 20 | import ( 21 | "encoding/json" 22 | "flag" 23 | "fmt" 24 | "net/url" 25 | "os" 26 | "os/signal" 27 | "time" 28 | 29 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 30 | "github.com/OpenSIPS/call-api/pkg/config" 31 | "github.com/gorilla/websocket" 32 | "github.com/sirupsen/logrus" 33 | ) 34 | 35 | func usage(prog string) { 36 | logrus.Fatalf("Usage: %s jsonrpc_method [jsonrpc_arguments]", prog) 37 | } 38 | 39 | func ParseClientArgs() (string, int, string, string, interface{}, string) { 40 | var wsServer, method, params, id string 41 | var wsPort int 42 | 43 | flag.StringVar(&wsServer, "wshost", "", "The websocket host to connect to") 44 | flag.IntVar(&wsPort, "wsport", 0, "The websocket port to connect to") 45 | flag.StringVar(&method, "method", "", "JSON-RPC method") 46 | flag.StringVar(¶ms, "params", "", "JSON-RPC params") 47 | flag.StringVar(&id, "id", "", "JSON-RPC id") 48 | 49 | cfgPath, err := config.ParseFlags("call-api") 50 | if err != nil { 51 | logrus.Fatal(err) 52 | } 53 | 54 | if method == "" { 55 | logrus.Error("no method specified!") 56 | usage(os.Args[0]) 57 | } 58 | 59 | var v interface{} 60 | 61 | if params != "" { 62 | err = json.Unmarshal([]byte(params), &v) 63 | if err != nil { 64 | logrus.Fatalf("failed to parse JSON args: %s", err) 65 | } 66 | } 67 | 68 | return wsServer, wsPort, cfgPath, method, v, id 69 | } 70 | 71 | func closeWSConnection(c *websocket.Conn) { 72 | 73 | logrus.Info("gracefully closing connection...") 74 | 75 | // Cleanly close the connection by sending a close message 76 | err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) 77 | if err != nil { 78 | logrus.Errorf("write close: %s", err) 79 | return 80 | } 81 | } 82 | 83 | func main() { 84 | // parse cmdline args 85 | wsServer, wsPort, cfgPath, method, params, id := ParseClientArgs() 86 | 87 | // read configuration 88 | cfg, err := config.NewConfig(cfgPath) 89 | if err != nil { 90 | logrus.Fatal(err) 91 | } 92 | 93 | if wsServer == "" { 94 | wsServer = cfg.WSServer.Host 95 | } 96 | 97 | if wsPort == 0 { 98 | wsPort = cfg.WSServer.Port 99 | } 100 | 101 | // prepare logging 102 | logfile, err := config.InitLogging(cfg) 103 | if err != nil { 104 | logrus.Fatal(err) 105 | } 106 | if logfile != nil { 107 | defer logfile.Close() 108 | } 109 | 110 | interrupt := make(chan os.Signal, 1) 111 | signal.Notify(interrupt, os.Interrupt) 112 | 113 | api_hostport := fmt.Sprintf("%s:%d", wsServer, wsPort) 114 | u := url.URL{Scheme: "ws", Host: api_hostport, Path: cfg.WSServer.Path} 115 | logrus.Printf("connecting to %s", u.String()) 116 | 117 | // open a single WebSocket connection 118 | c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) 119 | if err != nil { 120 | logrus.Fatal("dial:", err) 121 | } 122 | defer c.Close() 123 | 124 | done := make(chan struct{}) 125 | 126 | // keep listening for messages until EOF 127 | go func() { 128 | defer close(done) 129 | for { 130 | _, message, err := c.ReadMessage() 131 | if err != nil { 132 | logrus.Println("read:", err) 133 | return 134 | } 135 | 136 | logrus.Printf("recv: %s", message) 137 | 138 | var v interface{} 139 | 140 | err = json.Unmarshal(message, &v) 141 | if err != nil { 142 | logrus.Printf("failed to parse JSON reply: %s", err) 143 | return 144 | } 145 | 146 | params := v.(map[string]interface{})["params"] 147 | if params != nil { 148 | status := params.(map[string]interface{})["event"] 149 | if status == "Ended" || status == "Error" { 150 | closeWSConnection(c) 151 | return 152 | } 153 | } 154 | } 155 | }() 156 | 157 | // create a JSON-RPC request 158 | req := jsonrpc.NewRequest(id, method, params) 159 | if req == nil { 160 | logrus.Fatal("failed to create JSON-RPC request") 161 | } 162 | 163 | // ... serialize it 164 | buf, err := req.Buffer() 165 | if err != nil { 166 | logrus.Fatal("write:", err) 167 | } 168 | logrus.Infof("send: %s", buf) 169 | 170 | // ... and send it! 171 | err = c.WriteMessage(websocket.TextMessage, buf) 172 | if err != nil { 173 | logrus.Fatal("write:", err) 174 | } 175 | 176 | select { 177 | case <-done: 178 | return 179 | case <-interrupt: 180 | logrus.Println("interrupt") 181 | closeWSConnection(c) 182 | 183 | // wait (with timeout) for the server to close the connection 184 | select { 185 | case <-done: 186 | case <-time.After(time.Second): 187 | } 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /cmd/call-api/main.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package main 19 | 20 | import ( 21 | "github.com/sirupsen/logrus" 22 | "github.com/OpenSIPS/call-api/pkg/config" 23 | "github.com/OpenSIPS/call-api/pkg/ws_server" 24 | ) 25 | 26 | 27 | func main() { 28 | // parse cmdline args 29 | cfgPath, err := config.ParseFlags("call-api") 30 | if err != nil { 31 | logrus.Fatal(err) 32 | } 33 | 34 | // read configuration 35 | cfg, err := config.NewConfig(cfgPath) 36 | if err != nil { 37 | logrus.Fatal(err) 38 | } 39 | 40 | // prepare logging 41 | logfile, err := config.InitLogging(cfg) 42 | if err != nil { 43 | logrus.Fatal(err) 44 | } 45 | if logfile != nil { 46 | defer logfile.Close() 47 | } 48 | 49 | ws_server.Run(cfg) 50 | } 51 | -------------------------------------------------------------------------------- /cmd/call-cmd/main.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package main 19 | 20 | import ( 21 | "flag" 22 | "os" 23 | "strings" 24 | 25 | "github.com/sirupsen/logrus" 26 | "github.com/OpenSIPS/call-api/pkg/cmd" 27 | "github.com/OpenSIPS/call-api/pkg/proxy" 28 | "github.com/OpenSIPS/call-api/pkg/config" 29 | ) 30 | 31 | func usage(prog string) { 32 | logrus.Fatalf("Usage: %s command [arguments...]", prog) 33 | } 34 | 35 | func main() { 36 | 37 | cfgPath, err := config.ParseFlags("call-cmd") 38 | if err != nil { 39 | logrus.Fatal(err) 40 | } 41 | 42 | cfg, err := config.NewConfig(cfgPath) 43 | if err != nil { 44 | logrus.Fatal(err) 45 | } 46 | 47 | /* initialize logging */ 48 | logfile, err := config.InitLogging(cfg) 49 | if err != nil { 50 | logrus.Fatal(err) 51 | } 52 | if logfile != nil { 53 | defer logfile.Close() 54 | } 55 | 56 | if flag.NArg() < 1 { 57 | logrus.Error("no command specified!") 58 | usage(os.Args[0]) 59 | } 60 | 61 | proxy := proxy.NewProxy(cfg) 62 | if proxy == nil { 63 | logrus.Fatal("could not initialize SIP proxy") 64 | } 65 | command := flag.Arg(0) 66 | logrus.Debugf("Running command %s", command) 67 | c := cmd.New(command, "", proxy) 68 | if c == nil { 69 | logrus.Fatalf("could not initialize %s command", command) 70 | } 71 | var arguments = map[string]interface{}{} 72 | for _, arg := range flag.Args()[1:] { 73 | param := strings.Split(arg, "=") 74 | arguments[param[0]] = strings.Join(param[1:], "=") 75 | } 76 | c.Run(arguments) 77 | for { 78 | event := <-c.Wait() 79 | if event == nil { 80 | break 81 | } else if event.IsError() { 82 | logrus.Fatal(event.String()) 83 | } else { 84 | logrus.Printf("%s:%s: %+v", c.Command, c.ID, event.String()) 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /config/call-api.yml: -------------------------------------------------------------------------------- 1 | # The Call API configuration file 2 | 3 | 4 | # the API WS listener accepts long-lived WebSocket 5 | # connections and talks JSON-RPC over them 6 | ws_server: 7 | # the local machine IP Address to bind the API to 8 | host: localhost 9 | 10 | # the local machine TCP port to bind the API to 11 | port: 5059 12 | 13 | # the HTTP endpoint which accepts WebSocket connections 14 | http_path: /call-api 15 | 16 | 17 | # properties for the MI communication 18 | mi: 19 | # proxy's MI datagram listening socket 20 | url: 127.0.0.1:8080 21 | 22 | # properties for SIP communication 23 | sip: 24 | # proxy SIP URI 25 | #uri: sip:127.0.0.1 26 | 27 | # logging configuration (by default, the API logs to stderr) 28 | log: 29 | # absolute path 30 | #file_path: /var/log/call-api.log 31 | 32 | # possible levels: DEBUG, INFO, WARN, ERROR 33 | level: INFO 34 | -------------------------------------------------------------------------------- /config/call-cmd.yml: -------------------------------------------------------------------------------- 1 | # The OpenSIPS Calling CMD configuration file 2 | 3 | # properties for the MI communication 4 | mi: 5 | url: 127.0.0.1:8080 6 | 7 | # properties for SIP communication 8 | sip: 9 | # proxy SIP URI 10 | #uri: sip:127.0.0.1 11 | 12 | # logging configuration (by default, the API logs to stderr) 13 | log: 14 | # absolute path 15 | #file_path: /var/log/call-cmd.log 16 | 17 | # possible levels: DEBUG, INFO, WARN, ERROR 18 | level: DEBUG 19 | -------------------------------------------------------------------------------- /docs/Commands.md: -------------------------------------------------------------------------------- 1 | # JSON-RPC Protocol Documentation 2 | 3 | Once a WebSocket channel is established between the client and the API, communication will take place strictly using JSON messages which follow the JSON-RPC 2.0 request/response/notification protocol. Note that API _clients are expected to process notifications_ from the API, while their launched commands are being handled asynchronously. 4 | 5 | The Call API daemon receives a set of commands as JSON-RPC requests. A typical 6 | command would look as it follows (note that `<...>` indicates a placeholder 7 | for the actual values): 8 | 9 | ``` 10 | { 11 | "jsonrpc": "2.0" 12 | "id": , 13 | "method": "", 14 | "params": 15 | } 16 | ``` 17 | 18 | The request will contain the following placeholders: 19 | 20 | * `request-id`: an unique identifier of the JSON-RPC request 21 | * `method`: of the commands provided by the Call API engine 22 | * `params`: a JSON object containing different parameters, mandatory or 23 | optional, required by the command to run 24 | 25 | For each command sent, the JSON-RPC client will immediately receive a response 26 | from the server, with the following format: 27 | 28 | ``` 29 | { 30 | "jsonrpc": "2.0" 31 | "id": , 32 | "result": { 33 | "cmd_id": "", 34 | "event": "Started", 35 | } 36 | } 37 | ``` 38 | 39 | The JSON above contains the following placeholders: 40 | 41 | * `cmd-id`: an identifier of the command sent. If a `cmd_id` node has been 42 | specified in the request, then the same id will be returned otherwise an 43 | unique uuid will be generated for the command; this id would be present in all 44 | the following notifications sent for this specific command. 45 | * `request-id`: is the identifier sent in the JSON-RPC request 46 | 47 | In case of a failure to initiate the command, a standard JSON-RPC error will 48 | be triggered, with the following format: 49 | 50 | ``` 51 | { 52 | "jsonrpc": "2.0" 53 | "id": , 54 | "error": { 55 | "code": , 56 | "message": "" 57 | } 58 | } 59 | ``` 60 | 61 | The placeholders for an error will contain the following values: 62 | 63 | * `request-id`: the same identifier received in the JSON-RPC request 64 | * `code`: an integer indicated the code of the error 65 | * `reason`: a string containing the reason of the error 66 | 67 | If, however, the command invocation was successful, the Call API engine will 68 | start to generate JSON-RPC notifications about the progress of the command. 69 | These notifications look like this: 70 | 71 | ``` 72 | "jsonrpc": "2.0" 73 | "method": "", 74 | "params": { 75 | "cmd_id": "", 76 | "event": "", 77 | "data": "", 78 | } 79 | ``` 80 | 81 | A notification will contain the following values as placeholders: 82 | 83 | * `command`: the command that triggered this notification 84 | * `cmd-id`: the id of the command, as provided in the initial JSON-RPC 85 | response 86 | * `event`: one of the following values: 87 | * `Error`: indicates an error has been triggered 88 | * `Ended`: indicates that the command has been completed 89 | * an arbitrary name describing the status of the execution 90 | * `data`: optional JSON node, containing extra information about the error, or 91 | the progress of the command being executed; note that the `Ended` event 92 | does not have a `data` node. 93 | 94 | # Commands 95 | 96 | ## CallStart 97 | 98 | ### Parameters 99 | 100 | * _"caller"_ (string, mandatory) 101 | * _"callee"_ (string, mandatory) 102 | 103 | ### Events 104 | 105 | * _CallerAnswered_: triggered when the caller answered the initial call 106 | * _caller_: the caller that has just answered the call 107 | * _callee_: the callee that is being reached next 108 | * _Transferring_: triggered when the caller is trying to reach the callee 109 | * _caller_: the caller of the new call 110 | * _destination_: the SIP URI that is being called 111 | * _TransferStart_: triggered when the caller starts the call to callee 112 | * _callid_: the Call-ID of the new call 113 | * _caller_: the caller of the new call 114 | * _callee_: the callee that is being called 115 | * _TransferPending_: _optional_, contains extra information provided by the UAC 116 | regarding the new call 117 | * _callid_: the Call-ID of the new call 118 | * _caller_: the caller of the new call 119 | * _callee_: the callee of the new call 120 | * _extra_: _optional_, extra information provided by the caller 121 | * _CalleeAnswered_: triggered when the callee answers the call 122 | * _callid_: the Call-ID of the new call 123 | * _caller_: the caller of the new call 124 | * _callee_: the callee of the new call 125 | 126 | ### Example JSON-RPC flow: 127 | 128 | ``` 129 | 1) WS client ----------> API 130 | 131 | { 132 | "method": "CallStart", 133 | "params": { 134 | "caller": "sip:alice@10.0.0.10", 135 | "callee": "sip:bob@10.0.0.11" 136 | }, 137 | "id": "831717ed97e5", 138 | "jsonrpc": "2.0" 139 | } 140 | 141 | 2) WS client <---------- API 142 | 143 | { 144 | "result": { 145 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 146 | "status": "Started" 147 | }, 148 | "id": "831717ed97e5", 149 | "jsonrpc": "2.0" 150 | } 151 | 152 | 3) WS client <---------- API 153 | 154 | { 155 | "method": "CallStart", 156 | "params": { 157 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 158 | "status": "CallerAnswered" 159 | "data": { 160 | "caller": "sip:alice@10.0.0.10", 161 | "callee": "sip:bob@10.0.0.11" 162 | } 163 | }, 164 | "jsonrpc": "2.0" 165 | } 166 | 167 | 4) WS client <---------- API 168 | 169 | { 170 | "method": "CallStart", 171 | "params": { 172 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 173 | "status": "Transferring" 174 | "data": { 175 | "caller": "sip:alice@10.0.0.10", 176 | "callee": "sip:bob@10.0.0.11" 177 | } 178 | }, 179 | "jsonrpc": "2.0" 180 | } 181 | 182 | 5) WS client <---------- API 183 | 184 | { 185 | "method": "CallStart", 186 | "params": { 187 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 188 | "status": "TransferStart" 189 | "data": { 190 | "callid": "1fc8043a-3f89-49f9-8f8c-4c284faf69e3", 191 | "caller": "sip:alice@10.0.0.10", 192 | "callee": "sip:bob@10.0.0.11" 193 | } 194 | }, 195 | "jsonrpc": "2.0" 196 | } 197 | 198 | 6) WS client <---------- API 199 | 200 | { 201 | "method": "CallStart", 202 | "params": { 203 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 204 | "status": "TransferPending" 205 | "data": { 206 | "callid": "1fc8043a-3f89-49f9-8f8c-4c284faf69e3", 207 | "caller": "sip:alice@10.0.0.10", 208 | "callee": "sip:bob@10.0.0.11", 209 | "extra":"100 Trying" 210 | } 211 | }, 212 | "jsonrpc": "2.0" 213 | } 214 | 215 | 7) WS client <---------- API 216 | 217 | { 218 | "method": "CallStart", 219 | "params": { 220 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 221 | "status": "CalleeAnswered" 222 | "data": { 223 | "callid": "1fc8043a-3f89-49f9-8f8c-4c284faf69e3", 224 | "caller": "sip:alice@10.0.0.10", 225 | "callee": "sip:bob@10.0.0.11" 226 | } 227 | }, 228 | "jsonrpc": "2.0" 229 | } 230 | 231 | 8) WS client <---------- API 232 | 233 | { 234 | "method": "CallStart", 235 | "params": { 236 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178" 237 | "status": "Ended" 238 | }, 239 | "jsonrpc": "2.0" 240 | } 241 | ``` 242 | 243 | ## CallBlindTransfer 244 | 245 | ### Parameters 246 | 247 | * _"callid"_ (string, mandatory) - the SIP Call-ID of the targeted dialog 248 | * _"leg"_ (string, mandatory) - which party to transfer. Possible values: _"caller"_, _"callee"_ 249 | * _"destination"_ (string, mandatory) - SIP URI of the blind transfer target 250 | 251 | ### Events 252 | 253 | * _Transferring_: triggered when the transferrer has accepted the transfer 254 | * _destination_: the destination URI specified in the request 255 | * _TransferStart_: triggered when the leg starts the call the new destination 256 | * _callid_: the Call-ID of the new call 257 | * _destination_: SIP URI of the party that we are transferring to - note 258 | that the URI might be altered after the lookup has been performed 259 | * _TransferPending_: _optional_, triggered when the participant starts the 260 | transferring call 261 | * _callid_: the Call-ID of the new call 262 | * _destination_: SIP URI of the party that we are transferring to 263 | * _extra_: _optional_, extra information provided by the transferrer 264 | * _TransferSuccessful_: triggered when the destination accepted the new call 265 | * _callid_: the Call-ID of the new call 266 | * _destination_: SIP URI of the party that we are transferring to 267 | 268 | ### Example JSON-RPC flow: 269 | 270 | ``` 271 | # 1) WS client ----------> API 272 | 273 | { 274 | "method": "CallBlindTransfer", 275 | "params": { 276 | "callid": "431fc357.a3e3.49c2@127.0.0.1", 277 | "leg": "callee", 278 | "destination": "sip:cindy@10.0.0.11" 279 | }, 280 | "id": "831717ed97e5", 281 | "jsonrpc": "2.0" 282 | } 283 | 284 | # 2) WS client <---------- API 285 | 286 | { 287 | "result": { 288 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 289 | "status": "Started" 290 | }, 291 | "id": "831717ed97e5", 292 | "jsonrpc": "2.0" 293 | } 294 | 295 | # 3) WS client <---------- API 296 | 297 | { 298 | "method": "CallBlindTransfer", 299 | "params": { 300 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 301 | "event": "Transferring", 302 | "data": { 303 | "destination": "sip:cindy@10.0.0.11" 304 | } 305 | }, 306 | "jsonrpc": "2.0" 307 | } 308 | 309 | # 4) WS client <---------- API 310 | 311 | { 312 | "method": "CallBlindTransfer", 313 | "params": { 314 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 315 | "event": "TransferStart" 316 | "data": { 317 | "callid": "29ad6fdb-7806-4c17-b235-02b8f9fad1ae", 318 | "destination": "sip:cindy@10.0.0.11" 319 | } 320 | }, 321 | "jsonrpc": "2.0" 322 | } 323 | 324 | # 5) WS client <---------- API 325 | 326 | { 327 | "method": "CallBlindTransfer", 328 | "params": { 329 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 330 | "event": "TransferSuccessful" 331 | "data": { 332 | "callid": "29ad6fdb-7806-4c17-b235-02b8f9fad1ae", 333 | "destination": "sip:cindy@10.0.0.11" 334 | } 335 | }, 336 | "jsonrpc": "2.0" 337 | } 338 | 339 | # 6) WS client <---------- API 340 | 341 | { 342 | "method": "CallBlindTransfer", 343 | "params": { 344 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178" 345 | "event": "Ended" 346 | }, 347 | "jsonrpc": "2.0" 348 | } 349 | ``` 350 | 351 | ## CallAttendedTransfer 352 | 353 | ### Parameters 354 | 355 | * _"callidA"_ (string, mandatory) - the SIP Call-ID of the dialog #1 356 | * _"legA"_ (string, mandatory) - which party to transfer from dialog #1. Possible values: _"caller"_, _"callee"_ 357 | * _"callidB"_ (string, mandatory) - the SIP Call-ID of the dialog #2 358 | * _"legB"_ (string, mandatory) - which party to transfer from dialog #2. Possible values: _"caller"_, _"callee"_ 359 | 360 | ### Events 361 | 362 | * _Transferring_: triggered when the transferrer has accepted the transfer 363 | * _TransferStart_: triggered when the transferring leg of Call-ID of the 364 | dialog #1 is calling the leg in dialog #2 365 | * _callid_: the Call-ID of the new call 366 | * _destination_: SIP URI of the party that we are transferring to 367 | * _TransferPending_: _optional_, triggered when the participant starts the 368 | transferring call 369 | * _callid_: the Call-ID of the new call 370 | * _destination_: SIP URI of the party that we are transferring to 371 | * _extra_: _optional_, extra information provided by the transferrer 372 | * _TransferSuccessful_: triggered when the destination accepted the new call 373 | * _callid_: the Call-ID of the new call 374 | * _destination_: SIP URI of the party that we are transferring to 375 | 376 | ### Example JSON-RPC flow: 377 | 378 | ``` 379 | # 1) WS client ----------> API 380 | 381 | { 382 | "method": "CallAttendedTransfer", 383 | "params": { 384 | "callidA": "431fc357.a3e3.49c2@127.0.0.1", 385 | "legA": "caller", 386 | "callidB": "0ba2cf53-9a78-41de-8fe6-f2e5bb4d1a1e", 387 | "legB": "callee", 388 | } 389 | 390 | "id": "831717ed97e5", 391 | "jsonrpc": "2.0" 392 | } 393 | 394 | # 2) WS client <---------- API 395 | 396 | { 397 | "result": { 398 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 399 | "status": "Started" 400 | } 401 | 402 | "id": "831717ed97e5", 403 | "jsonrpc": "2.0" 404 | } 405 | 406 | # 3) WS client <---------- API 407 | 408 | { 409 | "method": "CallAttendedTransfer", 410 | "params": { 411 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 412 | "event": "Transferring" 413 | }, 414 | "jsonrpc": "2.0" 415 | } 416 | 417 | # 4) WS client <---------- API 418 | 419 | { 420 | "method": "CallAttendedTransfer", 421 | "params": { 422 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 423 | "event": "TransferStart" 424 | "data": { 425 | "callid": "29ad6fdb-7806-4c17-b235-02b8f9fad1ae", 426 | "destination": "sip:cindy@10.0.0.11" 427 | } 428 | }, 429 | "jsonrpc": "2.0" 430 | } 431 | 432 | # 5) WS client <---------- API 433 | 434 | { 435 | "method": "CallAttendedTransfer", 436 | "params": { 437 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 438 | "event": "TransferSuccessful" 439 | "data": { 440 | "callid": "29ad6fdb-7806-4c17-b235-02b8f9fad1ae", 441 | "destination": "sip:cindy@10.0.0.11" 442 | } 443 | }, 444 | "jsonrpc": "2.0" 445 | } 446 | 447 | # 6) WS client <---------- API 448 | 449 | { 450 | "method": "CallAttendedTransfer", 451 | "params": { 452 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178" 453 | "event": "Ended" 454 | }, 455 | "jsonrpc": "2.0" 456 | } 457 | ``` 458 | 459 | ## CallHold 460 | 461 | ### Parameters 462 | 463 | * _"callid"_ (string, mandatory) - the SIP Call-ID of the target dialog 464 | 465 | ### Events 466 | 467 | * _CallHolding_: triggered when the command was received by the proxy 468 | * _CallHoldStart_: triggered when the proxy sends a hold INVITE to one of the 469 | legs 470 | * _leg_: the call's leg that the message is being sent to (_caller_ or 471 | _callee_) 472 | * _CallHoldSuccessful_: triggered when one of the legs successfully accepted 473 | the call hold 474 | * _leg_: the call's leg that completed the call hold (_caller_ or _callee_) 475 | 476 | ### Example JSON-RPC flow: 477 | 478 | ``` 479 | # 1) WS client ----------> API 480 | 481 | { 482 | "method": "CallHold", 483 | "params": { 484 | "callid": "431fc357.a3e3.49c2@127.0.0.1", 485 | }, 486 | "id": "831717ed97e5", 487 | "jsonrpc": "2.0" 488 | } 489 | 490 | # 2) WS client <---------- API 491 | 492 | { 493 | "result": { 494 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 495 | "status": "Started" 496 | }, 497 | "id": "831717ed97e5", 498 | "jsonrpc": "2.0" 499 | } 500 | 501 | # 3) WS client <---------- API 502 | 503 | { 504 | "method": "CallHold", 505 | "params": { 506 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 507 | "event": "CallHolding" 508 | }, 509 | "jsonrpc": "2.0" 510 | } 511 | 512 | # 4) WS client <---------- API 513 | 514 | { 515 | "method": "CallHold", 516 | "params": { 517 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 518 | "event": "CallHoldStart", 519 | "data": { 520 | "leg": "caller" 521 | }, 522 | }, 523 | "jsonrpc": "2.0" 524 | } 525 | 526 | # 5) WS client <---------- API 527 | 528 | { 529 | "method": "CallHold", 530 | "params": { 531 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 532 | "event": "CallHoldStart" 533 | "data": { 534 | "leg": "callee" 535 | }, 536 | }, 537 | "jsonrpc": "2.0" 538 | } 539 | 540 | # 6) WS client <---------- API 541 | 542 | { 543 | "method": "CallHold", 544 | "params": { 545 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 546 | "event": "CallHoldSuccessful" 547 | "data": { 548 | "leg": "caller" 549 | }, 550 | }, 551 | "jsonrpc": "2.0" 552 | } 553 | 554 | # 7) WS client <---------- API 555 | 556 | { 557 | "method": "CallHold", 558 | "params": { 559 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 560 | "event": "CallHoldSuccessful" 561 | "data": { 562 | "leg": "callee" 563 | }, 564 | }, 565 | "jsonrpc": "2.0" 566 | } 567 | 568 | # 8) WS client <---------- API 569 | 570 | { 571 | "method": "CallHold", 572 | "params": { 573 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 574 | "event": "Ended" 575 | }, 576 | "jsonrpc": "2.0" 577 | } 578 | ``` 579 | 580 | ## CallUnhold 581 | 582 | ### Parameters 583 | 584 | * _"callid"_ (string, mandatory) - the SIP Call-ID of the target dialog 585 | 586 | ### Events 587 | 588 | * _CallUnholding_: triggered when the command was received by the proxy 589 | * _CallUnholdStart_: triggered when the proxy sends a hold INVITE to one of the 590 | legs 591 | * _leg_: the call's leg that the message is being sent to (_caller_ or 592 | _callee_) 593 | * _CallUnholdSuccessful_: triggered when one of the legs successfully resumes 594 | * _leg_: the call's leg that resumed the call (_caller_ or _callee_) 595 | 596 | ### Example JSON-RPC flow: 597 | 598 | ``` 599 | # 1) WS client ----------> API 600 | 601 | { 602 | "method": "CallUnhold", 603 | "params": { 604 | "callid": "431fc357.a3e3.49c2@127.0.0.1", 605 | }, 606 | "id": "831717ed97e5", 607 | "jsonrpc": "2.0" 608 | } 609 | 610 | # 2) WS client <---------- API 611 | 612 | { 613 | "result": { 614 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 615 | "status": "Started" 616 | }, 617 | "id": "831717ed97e5", 618 | "jsonrpc": "2.0" 619 | } 620 | 621 | # 3) WS client <---------- API 622 | 623 | { 624 | "method": "CallUnhold", 625 | "params": { 626 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 627 | "event": "CallUnholding" 628 | }, 629 | "jsonrpc": "2.0" 630 | } 631 | 632 | # 4) WS client <---------- API 633 | 634 | { 635 | "method": "CallUnhold", 636 | "params": { 637 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 638 | "event": "CallUnholdStart", 639 | "data": { 640 | "leg": "caller" 641 | }, 642 | }, 643 | "jsonrpc": "2.0" 644 | } 645 | 646 | # 5) WS client <---------- API 647 | 648 | { 649 | "method": "CallUnhold", 650 | "params": { 651 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 652 | "event": "CallUnholdStart" 653 | "data": { 654 | "leg": "callee" 655 | }, 656 | }, 657 | "jsonrpc": "2.0" 658 | } 659 | 660 | # 6) WS client <---------- API 661 | 662 | { 663 | "method": "CallUnhold", 664 | "params": { 665 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 666 | "event": "CallUnholdSuccessful" 667 | "data": { 668 | "leg": "caller" 669 | }, 670 | }, 671 | "jsonrpc": "2.0" 672 | } 673 | 674 | # 7) WS client <---------- API 675 | 676 | { 677 | "method": "CallUnhold", 678 | "params": { 679 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 680 | "event": "CallUnholdSuccessful" 681 | "data": { 682 | "leg": "callee" 683 | }, 684 | }, 685 | "jsonrpc": "2.0" 686 | } 687 | 688 | # 8) WS client <---------- API 689 | 690 | { 691 | "method": "CallUnhold", 692 | "params": { 693 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 694 | "event": "Ended" 695 | }, 696 | "jsonrpc": "2.0" 697 | } 698 | ``` 699 | 700 | ## CallEnd 701 | 702 | ### Parameters 703 | 704 | * _"callid"_ (string, mandatory) - the SIP Call-ID of the target dialog 705 | 706 | ### Events 707 | 708 | *NO events* 709 | 710 | ### Example JSON-RPC flow: 711 | 712 | ``` 713 | # 1) WS client ----------> API 714 | 715 | { 716 | "method": "CallEnd", 717 | "params": { 718 | "callid": "431fc357.a3e3.49c2@127.0.0.1" 719 | }, 720 | "id": "831717ed97e5", 721 | "jsonrpc": "2.0" 722 | } 723 | 724 | # 2) WS client <---------- API 725 | 726 | { 727 | "result": { 728 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 729 | "status": "Started" 730 | }, 731 | "id": "831717ed97e5", 732 | "jsonrpc": "2.0" 733 | } 734 | 735 | # 3) WS client <---------- API 736 | 737 | { 738 | "method": "CallEnd", 739 | "params": { 740 | "cmd_id": "b8179f1e-b4e4-4ac7-9990-4bf64f084178", 741 | "event": "Ended" 742 | } 743 | "jsonrpc": "2.0" 744 | } 745 | ``` 746 | 747 | ## Echo 748 | 749 | Command that receives arbitrary parameters and outputs them back as a 750 | notification. This command is useful to test connectivity to the API server. 751 | 752 | ### Parameters 753 | 754 | _Any_ parameter 755 | 756 | ### Events 757 | 758 | * _Reply_: contains a JSON object with the same JSON as specified in the request. 759 | 760 | ### Example JSON-RPC flow: 761 | 762 | ``` 763 | 1) WS client ----------> API 764 | 765 | { 766 | "method": "Echo", 767 | "params": { 768 | "test": "echo", 769 | }, 770 | "id": "33f6c98c821b", 771 | "jsonrpc": "2.0" 772 | } 773 | 774 | 2) WS client <---------- API 775 | 776 | { 777 | "result": { 778 | "cmd_id": "0f8a1664-01e2-46fe-ae55-e02715afee02", 779 | "event": "Started" 780 | }, 781 | "id": "33f6c98c821b", 782 | "jsonrpc": "2.0" 783 | } 784 | 785 | 3) WS client <---------- API 786 | 787 | { 788 | "method": "Echo", 789 | "params": { 790 | "cmd_id": "0f8a1664-01e2-46fe-ae55-e02715afee02", 791 | "event": "Reply", 792 | "data": {"test":"echo"} 793 | }, 794 | "jsonrpc": "2.0" 795 | } 796 | 797 | 4) WS client <---------- API 798 | 799 | { 800 | "method": "Echo", 801 | "params": { 802 | "cmd_id": "0f8a1664-01e2-46fe-ae55-e02715afee02", 803 | "event": "Ended" 804 | }, 805 | "jsonrpc": "2.0" 806 | } 807 | ``` 808 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | This page contains the documentation of the Call API project, split in 2 | multiple pages: 3 | 4 | * **[Commands](Commands.md)** - commands accepted by the **Call API** engine 5 | -------------------------------------------------------------------------------- /examples/javascript/call-api.js: -------------------------------------------------------------------------------- 1 | var callApiURL = "ws://127.0.0.1:5059/call-api"; 2 | 3 | var client = new $.JsonRpcClient({socketUrl: callApiURL, onmessage: CallOnMessage }); 4 | 5 | var callid = null; 6 | var onHold = false; 7 | 8 | function CallStart() { 9 | var caller = document.getElementById("caller").value; 10 | var callee = document.getElementById("callee").value; 11 | 12 | $('#callModal').on('hidden.bs.modal', function () { 13 | if (callid) 14 | CallEnd(); 15 | }); 16 | toastr.info("Starting Call to " + caller); 17 | 18 | client.call("CallStart", { caller: caller, callee: callee}, 19 | function(result) { 20 | toastr.info("Call initiated to caller"); 21 | $('#callModal').find('.modal-title').text("Calling to " + caller); 22 | $('#caller-out').text(caller); 23 | $('#callee-out').text(callee); 24 | }, toastr.error); 25 | } 26 | 27 | function CallHold() { 28 | if (!callid) { 29 | toastr.error("Unknown call"); 30 | return; 31 | } 32 | if (!onHold) { 33 | client.call("CallHold", { callid: callid }, 34 | function(result) { 35 | toastr.info("Call on hold"); 36 | $('#callModal').find('.modal-title').text("Call on hold") 37 | $('#callHold').addClass("active"); 38 | $("#callHold").prop('aria-pressed', true) 39 | onHold = true; 40 | }, toastr.error); 41 | } else { 42 | client.call("CallUnhold", { callid: callid }, 43 | function(result) { 44 | toastr.info("Call resumed"); 45 | $('#callModal').find('.modal-title').text("Call resumed") 46 | $('#callHold').removeClass("active"); 47 | $("#callHold").prop('aria-pressed', false) 48 | onHold = false; 49 | }, toastr.error); 50 | } 51 | } 52 | 53 | function CallEnd() { 54 | if (!callid) { 55 | toastr.error("Unknown call"); 56 | return; 57 | } 58 | client.call("CallEnd", { callid: callid}, 59 | function(result) { 60 | toastr.error("Call Ended"); 61 | $('#callHold').addClass("invisible"); 62 | $('#callEnd').addClass("invisible"); 63 | $('#callid').text(""); 64 | $('#callModal').modal('hide'); 65 | callid = null; 66 | onHold = false; 67 | }, toastr.error); 68 | } 69 | 70 | function CallOnMessage(message) { 71 | var obj = JSON.parse(message.data); 72 | switch(obj.params.event) { 73 | case "Error": 74 | toastr.error(obj.params.data); 75 | $('#callModal').modal('hide'); 76 | break; 77 | case "CallerAnswered": 78 | toastr.info("Caller Answered"); 79 | $('#callModal').find('.modal-title').text(obj.params.data.caller + " answered"); 80 | break; 81 | case "TransferStart": 82 | toastr.info("Calling Callee"); 83 | $('#callModal').find('.modal-title').text("Calling to " + obj.params.data.callee); 84 | callid = obj.params.data.callid; 85 | $('#callid').text(callid); 86 | break; 87 | case "TransferPending": 88 | toastr.info("Callee status: " + obj.params.data.extra); 89 | break; 90 | case "Transferring": 91 | toastr.info("Transferring"); 92 | break; 93 | case "CalleeAnswered": 94 | toastr.success("Callee Answered"); 95 | $('#callModal').find('.modal-title').text("Ongoing call"); 96 | $('#callHold').removeClass("invisible"); 97 | $('#callEnd').removeClass("invisible"); 98 | break; 99 | case "CallHolding": 100 | case "CallUnholding": 101 | case "CallHoldStart": 102 | case "CallUnholdStart": 103 | case "CallHoldSuccessful": 104 | case "CallUnholdSuccessful": 105 | case "Ended": 106 | break; 107 | default: 108 | toastr.warning("Unhandled message: " + obj.params.data); 109 | console.log(obj.params); 110 | break; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /examples/javascript/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Call API Javascript Example 16 | 17 | 18 |
19 |

Start Call

20 |
21 |
22 | Caller 23 |
24 | 26 |
27 |
28 |
29 | Callee 30 |
31 | 33 |
34 |
35 | 37 |
38 |
39 | 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/OpenSIPS/call-api 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/google/uuid v1.1.1 7 | github.com/gorilla/websocket v1.4.2 8 | github.com/sirupsen/logrus v1.6.0 9 | gopkg.in/yaml.v3 v3.0.0 10 | ) 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= 4 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 5 | github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= 6 | github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 7 | github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= 8 | github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 9 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 10 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 11 | github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= 12 | github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= 13 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 14 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 15 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= 16 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 17 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 18 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 19 | gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= 20 | gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 21 | -------------------------------------------------------------------------------- /images/logo/call-api-logo-short.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSIPS/call-api/98b62861af3d604a1dec2cc91e91a22387dbf214/images/logo/call-api-logo-short.png -------------------------------------------------------------------------------- /images/logo/call-api-logo-short.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /images/logo/call-api-logo-square.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSIPS/call-api/98b62861af3d604a1dec2cc91e91a22387dbf214/images/logo/call-api-logo-square.png -------------------------------------------------------------------------------- /images/logo/call-api-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenSIPS/call-api/98b62861af3d604a1dec2cc91e91a22387dbf214/images/logo/call-api-logo.png -------------------------------------------------------------------------------- /images/logo/call-api-logo.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /internal/jsonrpc/jsonrpc.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package jsonrpc 19 | 20 | import ( 21 | "encoding/json" 22 | "errors" 23 | "strconv" 24 | 25 | "github.com/sirupsen/logrus" 26 | ) 27 | 28 | type JsonRPCRequest struct { 29 | JSONRPC string `json:"jsonrpc"` 30 | ID interface{} `json:"id"` 31 | Method string `json:"method"` 32 | Params interface{} `json:"params,omitempty"` 33 | } 34 | 35 | type JsonRPCResponse struct { 36 | JSONRPC string `json:"jsonrpc"` 37 | ID interface{} `json:"id"` 38 | Result interface{} `json:"result,omitempty"` 39 | Error *JsonRPCError `json:"error,omitempty"` 40 | } 41 | 42 | type JsonRPCError struct { 43 | Code int `json:"code"` 44 | Message string `json:"message"` 45 | Data interface{} `json:"data,omitempty"` 46 | } 47 | 48 | type JsonRPCNotification struct { 49 | JSONRPC string `json:"jsonrpc"` 50 | Method string `json:"method"` 51 | Params interface{} `json:"params,omitempty"` 52 | } 53 | 54 | func (err *JsonRPCError) Error() (string) { 55 | return strconv.Itoa(err.Code) + " " + err.Message 56 | } 57 | 58 | func NewRequest(id interface{}, method string, params interface{}) (*JsonRPCRequest) { 59 | if _, ok := id.(uint64); !ok { 60 | if _, ok := id.(string); !ok { 61 | logrus.Errorf("unsupported ID type, must be uint64 or string: %s", id) 62 | return nil 63 | } 64 | } 65 | 66 | req := &JsonRPCRequest{ 67 | JSONRPC: "2.0", 68 | ID: id, 69 | Method: method, 70 | Params: params, 71 | } 72 | return req 73 | } 74 | 75 | func NewNotification(method string, params interface{}) (*JsonRPCNotification) { 76 | notify := &JsonRPCNotification{ 77 | JSONRPC: "2.0", 78 | Method: method, 79 | Params: params, 80 | } 81 | return notify 82 | } 83 | 84 | func (request *JsonRPCRequest) Buffer() ([]byte, error) { 85 | return json.Marshal(request) 86 | } 87 | func (request *JsonRPCRequest) Parse(bytes []byte) (error) { 88 | return json.Unmarshal(bytes, request) 89 | } 90 | 91 | func (reply *JsonRPCResponse) Parse(bytes []byte) (error) { 92 | return json.Unmarshal(bytes, reply) 93 | } 94 | 95 | func (reply *JsonRPCNotification) Parse(bytes []byte) (error) { 96 | return json.Unmarshal(bytes, reply) 97 | } 98 | 99 | func (reply *JsonRPCResponse) IsError() (bool) { 100 | return reply.Error != nil 101 | } 102 | 103 | func getInterface(i interface{}, name string) (interface{}, error) { 104 | m, ok := i.(map[string]interface{}) 105 | if !ok { 106 | return nil, errors.New("result is not a map") 107 | } 108 | val, ok := m[name] 109 | if ok != true { 110 | return nil, errors.New("value not found") 111 | } 112 | return val, nil 113 | } 114 | 115 | func getString(i interface{}, name string) (string, error) { 116 | v, err := getInterface(i, name) 117 | if err != nil { 118 | return "", nil 119 | } 120 | val, ok := v.(string) 121 | if ok != true { 122 | return "", errors.New("invalid type for " + name) 123 | } 124 | return val, nil 125 | } 126 | 127 | func (reply *JsonRPCResponse) GetString(name string) (string, error) { 128 | return getString(reply.Result, name) 129 | } 130 | 131 | func (notify *JsonRPCNotification) GetString(name string) (string, error) { 132 | return getString(notify.Params, name) 133 | } 134 | 135 | func (notify *JsonRPCNotification) Get(name string) (interface{}, error) { 136 | return getInterface(notify.Params, name) 137 | } 138 | -------------------------------------------------------------------------------- /pkg/cmd/call_attended_transfer.go: -------------------------------------------------------------------------------- 1 | // 2 | // This program is free software: you can redistribute it and/or modify 3 | // it under the terms of the GNU General Public License as published by 4 | // the Free Software Foundation, either version 3 of the License, or 5 | // (at your option) any later version. 6 | // 7 | // This program is distributed in the hope that it will be useful, 8 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | // GNU General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | 16 | package cmd 17 | 18 | import ( 19 | "github.com/OpenSIPS/call-api/pkg/event" 20 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 21 | ) 22 | 23 | type callAttendedTransferCmd struct { 24 | ended bool 25 | cmd *Cmd 26 | callid, dst string 27 | sub event.Subscription 28 | } 29 | 30 | func (ca *callAttendedTransferCmd) callAttendedTransferEnd() { 31 | var byeParams = map[string]string{ 32 | "dialog_id": ca.callid, 33 | } 34 | ca.cmd.proxy.MICall("dlg_end_dlg", &byeParams, nil) 35 | } 36 | 37 | func (ca *callAttendedTransferCmd) callAttendedTransferNotify(sub event.Subscription, notify *jsonrpc.JsonRPCNotification) { 38 | 39 | var event string 40 | 41 | state, err := notify.GetString("state") 42 | if err != nil { 43 | ca.sub.Unsubscribe() 44 | ca.cmd.NotifyError(err) 45 | return 46 | } 47 | status, err := notify.GetString("status") 48 | if err != nil { 49 | ca.sub.Unsubscribe() 50 | ca.cmd.NotifyError(err) 51 | return 52 | } 53 | 54 | callid, err := notify.GetString("transfer_callid") 55 | if err != nil { 56 | ca.cmd.NotifyError(err) 57 | return 58 | } 59 | 60 | switch state { 61 | case "failure": 62 | ca.sub.Unsubscribe() 63 | ca.cmd.NotifyNewError("transfer failed with status " + status) 64 | case "ok": 65 | if !ca.ended { 66 | ca.callAttendedTransferEnd() 67 | } 68 | event = "TransferSuccessful" 69 | status = "" 70 | case "start": 71 | event = "TransferStart" 72 | ca.dst, err = notify.GetString("destination") 73 | if err != nil { 74 | ca.cmd.NotifyError(err) 75 | return 76 | } 77 | default: 78 | event = "TransferPending" 79 | // this is a provisional that has a sip status in it - if 200, then we 80 | // should terminate the initial dialog 81 | if status != "" && status[0] == '2' { 82 | ca.callAttendedTransferEnd() 83 | ca.ended = true 84 | } 85 | } 86 | 87 | body := map[string]interface{}{ 88 | "callid": callid, 89 | } 90 | if ca.dst != "" { 91 | body["destination"] = ca.dst 92 | } 93 | if status != "" { 94 | body["extra"] = status 95 | } 96 | ca.cmd.NotifyEvent(event, body) 97 | if state == "ok" { 98 | ca.cmd.NotifyEnd() 99 | } 100 | } 101 | 102 | func (ca *callAttendedTransferCmd) callAttendedTransferReply(response *jsonrpc.JsonRPCResponse) { 103 | 104 | if response.IsError() { 105 | ca.cmd.NotifyError(response.Error) 106 | ca.sub.Unsubscribe() 107 | return 108 | } 109 | 110 | ca.cmd.NotifyEvent("Transferring", nil) 111 | } 112 | 113 | func (c *Cmd) CallAttendedTransfer(params map[string]interface{}) { 114 | 115 | callidA, ok := params["callidA"].(string) 116 | if !ok { 117 | c.NotifyNewError("callidA not specified") 118 | return 119 | } 120 | legA, ok := params["legA"].(string) 121 | if !ok { 122 | c.NotifyNewError("legA not specified") 123 | return 124 | } 125 | callidB, ok := params["callidB"].(string) 126 | if !ok { 127 | c.NotifyNewError("callidB not specified") 128 | return 129 | } 130 | legB, ok := params["legB"].(string) 131 | if !ok { 132 | c.NotifyNewError("legB not specified") 133 | return 134 | } 135 | 136 | var transferParams = map[string]string{ 137 | "callid": callidA, 138 | "leg": legA, 139 | "transfer_callid": callidB, 140 | "transfer_leg": legB, 141 | } 142 | 143 | var transferFilter = map[string]interface{}{ 144 | "callid": callidA, 145 | } 146 | 147 | ca := &callAttendedTransferCmd{ 148 | cmd: c, 149 | callid: callidA, 150 | } 151 | 152 | /* before transfering, register for new blind transfer events */ 153 | ca.sub = c.proxy.SubscribeFilter("E_CALL_TRANSFER", ca.callAttendedTransferNotify, transferFilter) 154 | if ca.sub == nil { 155 | c.NotifyNewError("Could not subscribe for event") 156 | return 157 | } 158 | 159 | err := c.proxy.MICall("call_transfer", &transferParams, ca.callAttendedTransferReply) 160 | if err != nil { 161 | ca.sub.Unsubscribe() 162 | c.NotifyError(err) 163 | return 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /pkg/cmd/call_blind_transfer.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | import ( 21 | "github.com/OpenSIPS/call-api/pkg/event" 22 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 23 | ) 24 | 25 | type callBlindTransferCmd struct { 26 | cmd *Cmd 27 | callid, dst string 28 | sub event.Subscription 29 | } 30 | 31 | func (cb *callBlindTransferCmd) callBlindTransferEnd() { 32 | var byeParams = map[string]string{ 33 | "dialog_id": cb.callid, 34 | } 35 | cb.sub.Unsubscribe() 36 | cb.cmd.proxy.MICall("dlg_end_dlg", &byeParams, nil) 37 | } 38 | 39 | func (cb *callBlindTransferCmd) callBlindTransferNotify(sub event.Subscription, notify *jsonrpc.JsonRPCNotification) { 40 | 41 | var event string 42 | 43 | state, err := notify.GetString("state") 44 | if err != nil { 45 | cb.cmd.NotifyError(err) 46 | return 47 | } 48 | 49 | status, err := notify.GetString("status") 50 | if err != nil { 51 | cb.cmd.NotifyError(err) 52 | return 53 | } 54 | 55 | callid, err := notify.GetString("transfer_callid") 56 | if err != nil { 57 | cb.cmd.NotifyError(err) 58 | return 59 | } 60 | 61 | switch state { 62 | case "failure": 63 | cb.cmd.NotifyNewError("Transfer failed with status " + status) 64 | return 65 | case "ok": 66 | event = "TransferSuccessful" 67 | status = "" 68 | case "start": 69 | event = "TransferStart" 70 | cb.dst, err = notify.GetString("destination") 71 | if err != nil { 72 | cb.cmd.NotifyError(err) 73 | return 74 | } 75 | default: 76 | event = "TransferPending" 77 | } 78 | 79 | body := map[string]interface{}{ 80 | "callid": callid, 81 | "destination": cb.dst, 82 | } 83 | 84 | if status != "" { 85 | body["extra"] = status 86 | } 87 | cb.cmd.NotifyEvent(event, body) 88 | 89 | if state == "ok" { 90 | cb.callBlindTransferEnd() 91 | cb.cmd.NotifyEnd() 92 | } 93 | } 94 | 95 | func (cb *callBlindTransferCmd) callBlindTransferReply(response *jsonrpc.JsonRPCResponse) { 96 | 97 | if response.IsError() { 98 | cb.cmd.NotifyError(response.Error) 99 | cb.sub.Unsubscribe() 100 | return 101 | } 102 | 103 | cb.cmd.NotifyEvent("Transferring", map[string]interface{}{ 104 | "destination": cb.dst, 105 | }) 106 | } 107 | 108 | func (c *Cmd) CallBlindTransfer(params map[string]interface{}) { 109 | 110 | callid, ok := params["callid"].(string) 111 | if !ok { 112 | c.NotifyNewError("callid not specified") 113 | return 114 | } 115 | leg, ok := params["leg"].(string) 116 | if !ok { 117 | c.NotifyNewError("leg not specified") 118 | return 119 | } 120 | destination, ok := params["destination"].(string) 121 | if !ok { 122 | c.NotifyNewError("destination not specified") 123 | return 124 | } 125 | 126 | var transferParams = map[string]string{ 127 | "callid": callid, 128 | "leg": leg, 129 | "destination": destination, 130 | } 131 | 132 | var transferFilter = map[string]interface{}{ 133 | "callid": callid, 134 | } 135 | 136 | cb := &callBlindTransferCmd{ 137 | cmd: c, 138 | callid: callid, 139 | dst: destination, 140 | } 141 | 142 | /* before transfering, register for new blind transfer events */ 143 | cb.sub = c.proxy.SubscribeFilter("E_CALL_TRANSFER", cb.callBlindTransferNotify, transferFilter) 144 | if cb.sub == nil { 145 | c.NotifyNewError("Could not subscribe for event") 146 | return 147 | } 148 | 149 | err := c.proxy.MICall("call_transfer", &transferParams, cb.callBlindTransferReply) 150 | if err != nil { 151 | c.NotifyError(err) 152 | return 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /pkg/cmd/call_end.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | import ( 21 | ) 22 | 23 | func (c *Cmd) CallEnd(params map[string]interface{}) { 24 | 25 | callid, ok := params["callid"].(string) 26 | if !ok { 27 | c.NotifyNewError("callid not specified") 28 | return 29 | } 30 | 31 | var endParams = map[string]string{ 32 | "dialog_id": callid, 33 | } 34 | 35 | ret, err := c.proxy.MICallSync("dlg_end_dlg", &endParams) 36 | if err != nil { 37 | c.NotifyError(err) 38 | } else if ret.IsError() { 39 | c.NotifyError(ret.Error) 40 | } else { 41 | c.NotifyEnd() 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /pkg/cmd/call_hold.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | import ( 21 | "github.com/OpenSIPS/call-api/pkg/event" 22 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 23 | ) 24 | 25 | type callHoldCmd struct { 26 | cmd *Cmd 27 | hold bool 28 | callid string 29 | caller_done, callee_done bool 30 | sub event.Subscription 31 | } 32 | 33 | func (ch *callHoldCmd) callHoldNotify(sub event.Subscription, notify *jsonrpc.JsonRPCNotification) { 34 | 35 | var event string 36 | 37 | state, err := notify.GetString("state") 38 | if err != nil { 39 | ch.cmd.NotifyError(err) 40 | return 41 | } 42 | 43 | leg, err := notify.GetString("leg") 44 | if err != nil { 45 | ch.cmd.NotifyError(err) 46 | return 47 | } 48 | 49 | switch state { 50 | case "failure": 51 | ch.cmd.NotifyNewError("Transfer failed") 52 | case "ok": 53 | if leg == "caller" { 54 | ch.caller_done = true 55 | } else { 56 | ch.callee_done = true 57 | } 58 | if ch.hold { 59 | event = "CallHoldSuccessful" 60 | } else { 61 | event = "CallUnholdSuccessful" 62 | } 63 | case "start": 64 | if ch.hold { 65 | event = "CallHoldStart" 66 | } else { 67 | event = "CallUnholdStart" 68 | } 69 | } 70 | 71 | ch.cmd.NotifyEvent(event, map[string]interface{}{ 72 | "leg": leg, 73 | }) 74 | 75 | if state == "ok" && ch.caller_done && ch.callee_done { 76 | ch.sub.Unsubscribe() 77 | ch.cmd.NotifyEnd() 78 | } 79 | } 80 | 81 | func (ch *callHoldCmd) callHoldReply(response *jsonrpc.JsonRPCResponse) { 82 | 83 | var event string 84 | 85 | if response.IsError() { 86 | ch.cmd.NotifyError(response.Error) 87 | ch.sub.Unsubscribe() 88 | return 89 | } 90 | 91 | if ch.hold { 92 | event = "CallHolding" 93 | } else { 94 | event = "CallUnholding" 95 | } 96 | 97 | ch.cmd.NotifyEvent(event, nil) 98 | } 99 | 100 | func (ch *callHoldCmd) callHoldUnhold(cmd string, params map[string]interface{}) { 101 | 102 | callid, ok := params["callid"].(string) 103 | if !ok { 104 | ch.cmd.NotifyNewError("callid not specified") 105 | return 106 | } 107 | ch.callid = callid 108 | 109 | /* before transfering, register for new blind transfer events */ 110 | ch.sub = ch.cmd.proxy.Subscribe("E_CALL_HOLD", ch.callHoldNotify) 111 | if ch.sub == nil { 112 | ch.cmd.NotifyNewError("Could not subscribe for event") 113 | return 114 | } 115 | 116 | var holdParams = map[string]string{ 117 | "callid": callid, 118 | } 119 | 120 | err := ch.cmd.proxy.MICall(cmd, &holdParams, ch.callHoldReply) 121 | if err != nil { 122 | ch.sub.Unsubscribe() 123 | ch.cmd.NotifyError(err) 124 | } 125 | } 126 | 127 | func (c *Cmd) CallHold(params map[string]interface{}) { 128 | 129 | ch := &callHoldCmd{ 130 | cmd: c, 131 | hold: true, 132 | } 133 | ch.callHoldUnhold("call_hold", params) 134 | } 135 | 136 | func (c *Cmd) CallUnhold(params map[string]interface{}) { 137 | 138 | ch := &callHoldCmd{ 139 | cmd: c, 140 | hold: false, 141 | } 142 | ch.callHoldUnhold("call_unhold", params) 143 | } 144 | -------------------------------------------------------------------------------- /pkg/cmd/call_start.go: -------------------------------------------------------------------------------- 1 | 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | import ( 21 | "fmt" 22 | "strings" 23 | "time" 24 | "github.com/OpenSIPS/call-api/pkg/event" 25 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 26 | ) 27 | 28 | type callStartCmd struct { 29 | caller, callee, ruri, dlginfo string 30 | sub event.Subscription 31 | cmd *Cmd 32 | } 33 | 34 | func (cs *callStartCmd) callStartEnd() { 35 | var byeParams = map[string]string{ 36 | "method": "BYE", 37 | "ruri": cs.ruri, 38 | "headers": cs.dlginfo + "CSeq: 3 BYE\r\n", /* guessing the cseq */ 39 | } 40 | cs.sub.Unsubscribe() 41 | cs.cmd.proxy.MICall("t_uac_dlg", &byeParams, nil) 42 | } 43 | 44 | 45 | func (cs *callStartCmd) callStartNotify(sub event.Subscription, notify *jsonrpc.JsonRPCNotification) { 46 | 47 | var event string 48 | 49 | state, err := notify.GetString("state") 50 | if err != nil { 51 | cs.cmd.NotifyError(err) 52 | return 53 | } 54 | 55 | status, err := notify.GetString("status") 56 | if err != nil { 57 | cs.cmd.NotifyError(err) 58 | return 59 | } 60 | 61 | callid, err := notify.GetString("transfer_callid") 62 | if err != nil { 63 | cs.cmd.NotifyError(err) 64 | return 65 | } 66 | 67 | switch state { 68 | case "failure": 69 | cs.cmd.NotifyNewError("transfer failed with status " + status) 70 | return 71 | case "ok": 72 | event = "CalleeAnswered" 73 | status = "" 74 | case "start": 75 | event = "TransferStart" 76 | default: 77 | event = "TransferPending" 78 | } 79 | 80 | body := map[string]interface{}{ 81 | "callid": callid, 82 | "caller": cs.caller, 83 | "callee": cs.callee, 84 | } 85 | 86 | if status != "" { 87 | body["extra"] = status 88 | } 89 | cs.cmd.NotifyEvent(event, body) 90 | 91 | if state == "ok" { 92 | cs.callStartEnd() 93 | cs.cmd.NotifyEnd() 94 | } 95 | } 96 | 97 | func (cs *callStartCmd) callStartTransfer(response *jsonrpc.JsonRPCResponse) { 98 | 99 | if response.IsError() { 100 | cs.callStartEnd() 101 | cs.cmd.NotifyError(response.Error) 102 | return 103 | } 104 | 105 | cs.cmd.NotifyEvent("Transferring", map[string]interface{}{ 106 | "caller": cs.caller, 107 | "destination": cs.callee, 108 | }) 109 | } 110 | 111 | 112 | func (cs *callStartCmd) callStartInitial(response *jsonrpc.JsonRPCResponse) { 113 | 114 | if response.IsError() { 115 | cs.cmd.NotifyError(response.Error) 116 | return 117 | } 118 | 119 | status, err := response.GetString("Status") 120 | if err != nil { 121 | cs.cmd.NotifyError(err) 122 | return 123 | } 124 | 125 | if strings.Split(status, " ")[0] != "200" { 126 | cs.cmd.NotifyNewError("failed to establish initial call: " + status) 127 | return 128 | } 129 | 130 | cs.ruri, err = response.GetString("RURI") 131 | if err != nil { 132 | cs.cmd.NotifyError(err) 133 | return 134 | } 135 | 136 | message, err := response.GetString("Message"); 137 | if err != nil { 138 | cs.cmd.NotifyError(err) 139 | return 140 | } 141 | 142 | /* gather information about the dialog, so we can close it later */ 143 | for _, header := range strings.Split(message, "\r\n") { 144 | switch strings.Split(header, ":")[0] { 145 | case "From", "To", "Routes", "Call-ID", "Call-Id": 146 | cs.dlginfo += header + "\r\n" 147 | } 148 | } 149 | 150 | cs.cmd.NotifyEvent("CallerAnswered", map[string]interface{}{ 151 | "caller": cs.caller, 152 | "callee": cs.callee, 153 | }) 154 | 155 | var transferParams = map[string]string{ 156 | "callid": cs.cmd.ID, 157 | "leg": "callee", 158 | "destination": cs.callee, 159 | } 160 | 161 | var transferFilter = map[string]interface{}{ 162 | "callid": cs.cmd.ID, 163 | } 164 | 165 | /* before transfering, register for new blind transfer events */ 166 | cs.sub = cs.cmd.proxy.SubscribeFilter("E_CALL_TRANSFER", cs.callStartNotify, transferFilter) 167 | if cs.sub == nil { 168 | cs.cmd.NotifyNewError("Could not subscribe for event") 169 | return 170 | } 171 | 172 | time.Sleep(500 * time.Millisecond) 173 | err = cs.cmd.proxy.MICall("call_transfer", &transferParams, cs.callStartTransfer) 174 | if err != nil { 175 | cs.sub.Unsubscribe() 176 | cs.cmd.NotifyError(err) 177 | return 178 | } 179 | } 180 | 181 | func (c *Cmd) CallStart(params map[string]interface{}) { 182 | 183 | const headersFormat = "From: <%s>\r\n" + 184 | "To: <%s>\r\n" + 185 | "Contact: <%s>\r\n" + 186 | "Content-Type: application/sdp\r\n" + 187 | "CSeq: 1 INVITE\r\n" + 188 | "Call-Id: %s\r\n" 189 | 190 | const inviteBody = "v=0\r\n" + 191 | "o=click-to-dial 0 0 IN IP4 0.0.0.0\r\n" + 192 | "s=session\r\n" + 193 | "c=IN IP4 0.0.0.0\r\n" + 194 | "t=0 0\r\n" + 195 | "m=audio 9 RTP/AVP 0\r\n" + 196 | "a=rtpmap:0 PCMU/8000\r\n" 197 | 198 | caller, ok := params["caller"].(string) 199 | if !ok { 200 | c.NotifyNewError("caller not specified") 201 | return 202 | } 203 | callee, ok := params["callee"].(string) 204 | if !ok { 205 | c.NotifyNewError("callee not specified") 206 | return 207 | } 208 | 209 | headers := fmt.Sprintf(headersFormat, caller, callee, caller, c.ID) 210 | 211 | var inviteParams = map[string]string{ 212 | "method": "INVITE", 213 | "ruri": caller, 214 | "headers": headers, 215 | "body": inviteBody, 216 | } 217 | var next_hop = c.proxy.GetURI() 218 | if next_hop != "" { 219 | inviteParams["next_hop"] = next_hop 220 | } 221 | 222 | cs := &callStartCmd{ 223 | caller: caller, 224 | callee: callee, 225 | ruri: caller, 226 | dlginfo: "", 227 | cmd: c, 228 | } 229 | 230 | err := c.proxy.MICall("t_uac_dlg", &inviteParams, cs.callStartInitial) 231 | if err != nil { 232 | c.NotifyError(err) 233 | return 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /pkg/cmd/cmd.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | import ( 21 | "errors" 22 | "fmt" 23 | "reflect" 24 | 25 | "github.com/google/uuid" 26 | "github.com/OpenSIPS/call-api/pkg/proxy" 27 | ) 28 | 29 | type Notify func(cmd *Cmd, notify interface{}) 30 | 31 | 32 | type Cmd struct { 33 | ID string 34 | Command string 35 | 36 | proxy *proxy.Proxy 37 | notify chan *CmdEvent 38 | hdl reflect.Value 39 | } 40 | 41 | func New(command string, id string, p *proxy.Proxy) (c *Cmd) { 42 | c = &Cmd{ 43 | Command: command, 44 | ID: id, 45 | proxy: p, 46 | notify: make(chan *CmdEvent, 1), 47 | } 48 | 49 | if c.ID == "" { 50 | c.ID = uuid.New().String() 51 | } 52 | 53 | c.hdl = reflect.ValueOf(c).MethodByName(command) 54 | if !c.hdl.IsValid() { 55 | return nil 56 | } 57 | return c 58 | } 59 | 60 | func (c *Cmd) Run(params map[string]interface{}) (err error) { 61 | // TODO: remove this check once non-strings are handled under the hood 62 | for key := range params { 63 | if _, ok := params[key].(string); !ok { 64 | err = fmt.Errorf("non-string parameter values are not yet supported") 65 | return 66 | } 67 | } 68 | 69 | in := []reflect.Value{reflect.ValueOf(params)} 70 | go c.hdl.Call(in) 71 | return 72 | } 73 | 74 | func (c *Cmd) Wait() (chan *CmdEvent) { 75 | 76 | return c.notify 77 | } 78 | 79 | func (c *Cmd) RunSync(params map[string]interface{}) (error) { 80 | 81 | c.Run(params) 82 | for { 83 | event := <-c.Wait() 84 | if event == nil { 85 | return nil 86 | } else if event.IsError() { 87 | return event.Error 88 | } 89 | } 90 | } 91 | 92 | /* Notify an arbitrary event */ 93 | func (c *Cmd) Notify(ce *CmdEvent) { 94 | c.notify <- ce 95 | } 96 | 97 | /* Notify an existing error - closes the channel */ 98 | func (c *Cmd) NotifyError(err error) { 99 | c.Notify(NewError(err)) 100 | close(c.notify) 101 | } 102 | 103 | /* Notify a new error - closes the channel */ 104 | func (c *Cmd) NotifyNewError(err string ) { 105 | c.Notify(NewError(errors.New(err))) 106 | close(c.notify) 107 | } 108 | 109 | /* Notify an event */ 110 | func (c *Cmd) NotifyEvent(name string, event interface{}) { 111 | c.Notify(NewEvent(name, event)) 112 | } 113 | 114 | /* Notify the termination of the command handling */ 115 | func (c *Cmd) NotifyEnd() { 116 | close(c.notify) 117 | } 118 | -------------------------------------------------------------------------------- /pkg/cmd/echo.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | func (c *Cmd) Echo(params map[string]interface{}) { 21 | c.NotifyEvent("Reply", params) 22 | c.NotifyEnd() 23 | } 24 | -------------------------------------------------------------------------------- /pkg/cmd/event.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | import ( 21 | "fmt" 22 | ) 23 | 24 | type CmdEvent struct { 25 | Error error 26 | Name string 27 | Params interface{} 28 | } 29 | 30 | func NewError(err error) (c *CmdEvent) { 31 | return &CmdEvent{Error: err} 32 | } 33 | 34 | func NewEvent(name string, event interface{}) (c *CmdEvent) { 35 | switch name { 36 | case 37 | "End", 38 | "Started", 39 | "Error": 40 | panic("Event '" + name + "' is reserved") 41 | } 42 | return &CmdEvent{Name: name, Params: event} 43 | } 44 | 45 | func (c *CmdEvent) IsError() (bool) { 46 | return c.Error != nil 47 | } 48 | 49 | func (c *CmdEvent) HasParams() (bool) { 50 | return c.Params != nil 51 | } 52 | 53 | func (c *CmdEvent) String() (string) { 54 | if c.IsError() { 55 | return c.Error.Error() 56 | } else if !c.HasParams() { 57 | return c.Name 58 | } else { 59 | return c.Name + ": " + fmt.Sprint(c.Params) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /pkg/cmd/test.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package cmd 19 | 20 | func (c *Cmd) Test(params map[string]interface{}) { 21 | c.NotifyEvent("TODO", params) 22 | sub := c.proxy.Subscribe("E_CALL_TRANSFER", nil) 23 | sub.Unsubscribe() 24 | c.NotifyEnd() 25 | } 26 | -------------------------------------------------------------------------------- /pkg/config/config.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package config 19 | 20 | import ( 21 | "flag" 22 | "fmt" 23 | "os" 24 | "strings" 25 | 26 | "github.com/OpenSIPS/call-api/utils" 27 | "github.com/sirupsen/logrus" 28 | "gopkg.in/yaml.v3" 29 | ) 30 | 31 | // Default config dirs 32 | var defaultConfigDirs = [3]string{"config","/etc","/etc/call-api"} 33 | 34 | // Call API "config.yml" file structure 35 | type Config struct { 36 | WSServer struct { 37 | Host string `yaml:"host,omitempty"` 38 | Port int `yaml:"port,omitempty"` 39 | Path string `yaml:"http_path,omitempty"` 40 | } `yaml:"ws_server"` 41 | 42 | Log struct { 43 | FilePath string `yaml:"file_path",omitempty"` 44 | Level string `yaml:"level",omitempty"` 45 | } `yaml:"log"` 46 | 47 | SIP struct { 48 | URI string `yaml:"uri",omitempty"` 49 | } `yaml:"sip"` 50 | 51 | MI struct { 52 | URL string `yaml:"url,omitempty"` 53 | } `yaml:"mi"` 54 | } 55 | 56 | func printVersion(tool string) { 57 | logrus.Printf("%s: %s", tool, utils.GetFullVersion()); 58 | os.Exit(0) 59 | } 60 | 61 | // read & parse configuration file 62 | func NewConfig(configPath string) (*Config, error) { 63 | if err := ValidateConfigPath(configPath); err != nil { 64 | return nil, err 65 | } 66 | 67 | config := &Config{} 68 | 69 | file, err := os.Open(configPath) 70 | if err != nil { 71 | return nil, err 72 | } 73 | defer file.Close() 74 | 75 | d := yaml.NewDecoder(file) 76 | if err := d.Decode(&config); err != nil { 77 | return nil, err 78 | } 79 | 80 | return config, nil 81 | } 82 | 83 | 84 | func ValidateConfigPath(path string) error { 85 | s, err := os.Stat(path) 86 | if err != nil { 87 | return err 88 | } 89 | if s.IsDir() { 90 | return fmt.Errorf("'%s' is a directory, not a normal file", path) 91 | } 92 | return nil 93 | } 94 | 95 | 96 | // Call API command-line parameters 97 | func ParseFlags(tool string) (string, error) { 98 | var err error 99 | var configPath string 100 | 101 | versionFlag := flag.Bool("v", false, "Print the current version and exit") 102 | flag.StringVar(&configPath, "config", "", "path to config file") 103 | 104 | flag.Parse() 105 | 106 | if *versionFlag { 107 | printVersion(tool) 108 | } 109 | 110 | if (configPath == "") { 111 | configPath, err = GetDefaultConfigPath(tool) 112 | } 113 | 114 | return configPath, err 115 | } 116 | 117 | 118 | func InitLogging(cfg *Config) (file *os.File, err error) { 119 | if cfg.Log.FilePath != "" { 120 | f, err := os.OpenFile(cfg.Log.FilePath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) 121 | if err != nil { 122 | logrus.Fatal(err) 123 | } 124 | 125 | logrus.SetOutput(f) 126 | file = f 127 | } 128 | 129 | if cfg.Log.Level != "" { 130 | level, err := logrus.ParseLevel(cfg.Log.Level) 131 | if err != nil { 132 | logrus.Fatal(err) 133 | } 134 | 135 | logrus.SetLevel(level) 136 | } 137 | 138 | return 139 | } 140 | 141 | func GetDefaultConfigPath(tool string) (string, error) { 142 | 143 | var err error 144 | var cfg string 145 | var tested []string 146 | 147 | // first search in $HOME/..yml 148 | home := os.Getenv("HOME") 149 | cfg = fmt.Sprintf("%s/.%s.yml", home, tool) 150 | err = ValidateConfigPath(cfg) 151 | if err == nil { 152 | return cfg, nil 153 | } 154 | 155 | for _, d := range defaultConfigDirs { 156 | cfg = fmt.Sprintf("%s/%s.yml", d, tool) 157 | err = ValidateConfigPath(cfg) 158 | if err == nil { 159 | return cfg, nil 160 | } else { 161 | logrus.Debug(err.Error()) 162 | } 163 | tested = append(tested, cfg) 164 | } 165 | return "", fmt.Errorf("No config file found in any of %s", strings.Join(tested, ",")) 166 | } 167 | -------------------------------------------------------------------------------- /pkg/event/datagram.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package event 19 | 20 | import ( 21 | "errors" 22 | "net" 23 | "sync" 24 | "syscall" 25 | 26 | "github.com/sirupsen/logrus" 27 | "github.com/OpenSIPS/call-api/pkg/mi" 28 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 29 | ) 30 | 31 | // DatagramSubscription - object referenced by Event users 32 | type DatagramSubscription struct { 33 | valid bool 34 | notify EventNotification 35 | filter map[string]interface{} 36 | handler *EventDatagramSub 37 | } 38 | 39 | func (sub *DatagramSubscription) Event() (string) { 40 | return sub.handler.String() 41 | } 42 | 43 | func (sub *DatagramSubscription) String() (string) { 44 | return sub.handler.String() // TODO: add filters 45 | } 46 | 47 | func (sub *DatagramSubscription) Unsubscribe() { 48 | sub.valid = false 49 | sub.handler.removeSubscription(sub) 50 | } 51 | 52 | func (sub *DatagramSubscription) MatchFilter(notify *jsonrpc.JsonRPCNotification) (bool) { 53 | if sub.filter == nil { 54 | return true 55 | } 56 | for k, v := range sub.filter { 57 | r, err := notify.Get(k) 58 | if err != nil || r != v { 59 | return false 60 | } 61 | } 62 | return true 63 | } 64 | 65 | // EventDatagramSub - manages a subscription to an event to the proxy 66 | type EventDatagramSub struct { 67 | event string 68 | subscribed bool 69 | confirm chan error 70 | lock sync.RWMutex 71 | handler *EventDatagram 72 | subscriptions []*DatagramSubscription 73 | } 74 | 75 | func (sub *EventDatagramSub) String() (string) { 76 | return sub.event 77 | } 78 | 79 | func (sub *EventDatagramSub) IsSubscribed() (bool) { 80 | return sub.subscribed 81 | } 82 | 83 | func (sub *EventDatagramSub) WaitSubscribed() (bool) { 84 | if sub.IsSubscribed() { 85 | return true 86 | } 87 | // wait for it to subscribe 88 | <-sub.confirm 89 | return sub.IsSubscribed() 90 | } 91 | 92 | func (sub *EventDatagramSub) newSubscription(notify EventNotification, filter map[string]interface{}) (*DatagramSubscription) { 93 | 94 | ds := &DatagramSubscription{ 95 | notify: notify, 96 | filter: filter, 97 | handler: sub, 98 | valid: true, 99 | } 100 | sub.lock.Lock() 101 | sub.subscriptions = append(sub.subscriptions, ds) 102 | sub.lock.Unlock() 103 | return ds 104 | } 105 | 106 | func (sub *EventDatagramSub) removeSubscription(ds *DatagramSubscription) { 107 | sub.lock.Lock() 108 | for i, s := range sub.subscriptions { 109 | if s == ds { 110 | sub.subscriptions = append(sub.subscriptions[0:i], sub.subscriptions[i+1:]...) 111 | break 112 | } 113 | } 114 | if len(sub.subscriptions) == 0 { 115 | sub.handler.removeEventSubscription(sub) 116 | } 117 | sub.lock.Unlock() 118 | if !sub.IsSubscribed() { 119 | return 120 | } 121 | // we now properly unregister 122 | var eviParams = map[string]interface{}{ 123 | "event": sub.event, 124 | "socket": sub.handler.String(), 125 | "expire": 0, 126 | } 127 | err := sub.handler.mi.Call("event_subscribe", &eviParams, nil); 128 | if err != nil { 129 | logrus.Error("could not unsubscribe for event " + sub.event + " " + err.Error()) 130 | } else { 131 | logrus.Debug("successfully unsubscribed " + sub.event) 132 | } 133 | } 134 | 135 | func (sub *EventDatagramSub) subscribeReply(response *jsonrpc.JsonRPCResponse) { 136 | 137 | if !response.IsError() { 138 | // confirm the event is properly subscribed 139 | sub.subscribed = true 140 | } else { 141 | // wake up the event loop to inform there's no one in there 142 | sub.lock.Lock() 143 | if len(sub.subscriptions) == 0 { 144 | sub.handler.removeEventSubscription(sub) 145 | } 146 | sub.lock.Unlock() 147 | } 148 | close(sub.confirm) 149 | } 150 | 151 | func (sub *EventDatagramSub) notify(n *jsonrpc.JsonRPCNotification) { 152 | sub.lock.RLock() 153 | for _, s := range sub.subscriptions { 154 | if s.valid && s.MatchFilter(n) { 155 | go s.notify(s, n) 156 | } 157 | } 158 | sub.lock.RUnlock() 159 | } 160 | 161 | // EventDatagram - handler of the Datagram connection 162 | type EventDatagram struct { 163 | mi mi.MI 164 | lock sync.Mutex 165 | conn *net.UDPConn 166 | subs []*EventDatagramSub 167 | } 168 | 169 | func (event *EventDatagram) waitForEvents() { 170 | 171 | var sub *EventDatagramSub 172 | 173 | buffer := make([]byte, 65535) 174 | for { 175 | r, _, err := event.conn.ReadFrom(buffer) 176 | if err == nil { 177 | result := &jsonrpc.JsonRPCNotification{} 178 | err = result.Parse(buffer[0:r]) 179 | if err != nil { 180 | logrus.Error("could not parse notification: " + err.Error()) 181 | } else { 182 | sub = event.getEventSubscription(result.Method) 183 | // run in a different routine to avoid blocking 184 | if sub != nil { 185 | sub.notify(result) 186 | } 187 | } 188 | } else { 189 | logrus.Warn("error while listening for events: " + err.Error()) 190 | } 191 | } 192 | } 193 | 194 | func (event *EventDatagram) getEventSubscription(ev string) (*EventDatagramSub) { 195 | var es *EventDatagramSub 196 | for _, es = range event.subs { 197 | if es.event == ev { 198 | break 199 | } else { 200 | es = nil 201 | } 202 | } 203 | return es 204 | } 205 | 206 | func (event *EventDatagram) newEventSubscription(ev string) (*EventDatagramSub) { 207 | return &EventDatagramSub{ 208 | event: ev, 209 | handler: event, 210 | confirm: make(chan error, 1), 211 | subscriptions: make([]*DatagramSubscription, 0), 212 | } 213 | } 214 | 215 | func (event *EventDatagram) removeEventSubscription(evSub *EventDatagramSub) { 216 | event.lock.Lock() 217 | for i, s := range event.subs { 218 | if evSub == s { 219 | logrus.Info("removing event " + evSub.String()) 220 | event.subs = append(event.subs[0:i], event.subs[i+1:]...) 221 | break; 222 | } 223 | } 224 | event.lock.Unlock() 225 | } 226 | 227 | func (event *EventDatagram) Init(mi mi.MI) (error) { 228 | 229 | miAddr, ok := mi.Addr().(*net.UDPAddr) 230 | if ok != true { 231 | return errors.New("using non-UDP protocol to connect to MI") 232 | } 233 | c, err := net.DialUDP("udp", nil, miAddr) 234 | if err != nil { 235 | return err 236 | } 237 | udpAddr, ok := c.LocalAddr().(*net.UDPAddr) 238 | if ok != true { 239 | return errors.New("using non-UDP local socket to connect to MI") 240 | } 241 | local := net.UDPAddr{IP: udpAddr.IP} 242 | udpConn, err := net.ListenUDP(c.LocalAddr().Network(), &local) 243 | if err != nil { 244 | return err 245 | } 246 | udpConn.SetReadBuffer(65535) 247 | udpConn.SetWriteBuffer(65535) 248 | 249 | file, _ := udpConn.File() 250 | fd := file.Fd() 251 | syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 0) 252 | 253 | event.mi = mi 254 | event.conn = udpConn 255 | event.subs = make([]*EventDatagramSub, 0, 1) 256 | 257 | go event.waitForEvents() 258 | return nil 259 | } 260 | 261 | func (event *EventDatagram) SubscribeFilter(ev string, notify EventNotification, filter map[string]interface{}) (Subscription) { 262 | 263 | var newSub bool 264 | newSub = false 265 | 266 | /* search for a connection that does not have this event registered */ 267 | event.lock.Lock() 268 | evSub := event.getEventSubscription(ev) 269 | if evSub == nil { 270 | evSub = event.newEventSubscription(ev) 271 | if evSub == nil { 272 | logrus.Error("could not create new subscription") 273 | return nil 274 | } else { 275 | event.subs = append(event.subs, evSub) 276 | newSub = true 277 | } 278 | } 279 | event.lock.Unlock() 280 | 281 | if newSub { 282 | /* we now have a proper conn to listen for events on */ 283 | logrus.Debug("subscribing for " + ev + " on " + event.String()) 284 | 285 | /* we've got the connection - let us subscribe */ 286 | var eviParams = map[string]interface{}{ 287 | "event": ev, 288 | "socket": event.String(), 289 | "expire": 120, 290 | } 291 | err := event.mi.Call("event_subscribe", &eviParams, evSub.subscribeReply) 292 | if err != nil { 293 | logrus.Error("could not subscribe for event " + ev + ": " + err.Error()) 294 | event.removeEventSubscription(evSub) 295 | return nil 296 | } 297 | } 298 | 299 | if !evSub.WaitSubscribed() { 300 | logrus.Error("could not subscribe for event " + ev) 301 | event.removeEventSubscription(evSub) 302 | return nil 303 | } 304 | 305 | return evSub.newSubscription(notify, filter) 306 | } 307 | 308 | func (event *EventDatagram) Subscribe(ev string, notify EventNotification) (Subscription) { 309 | return event.SubscribeFilter(ev, notify, nil) 310 | } 311 | 312 | func (event *EventDatagram) String() (string) { 313 | return event.conn.LocalAddr().Network() + ":" + event.conn.LocalAddr().String() 314 | } 315 | -------------------------------------------------------------------------------- /pkg/event/event.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package event 19 | 20 | import ( 21 | "github.com/sirupsen/logrus" 22 | "github.com/OpenSIPS/call-api/pkg/mi" 23 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 24 | ) 25 | 26 | type EventNotification func(sub Subscription, notify *jsonrpc.JsonRPCNotification) 27 | 28 | type Subscription interface { 29 | Event() (string) 30 | String() (string) 31 | Unsubscribe() 32 | } 33 | 34 | type Event interface { 35 | Init(mi.MI) (error) 36 | Subscribe(event string, notify EventNotification) (Subscription) 37 | SubscribeFilter(event string, notify EventNotification, filter map[string]interface{}) (Subscription) 38 | } 39 | 40 | func EventHandler(mi mi.MI) (Event) { 41 | /* TODO: check based on config what exactly to do here */ 42 | event := new(EventDatagram) 43 | if err := event.Init(mi); err != nil { 44 | logrus.Printf("ERROR creating: %v", err) 45 | return nil 46 | } 47 | return event 48 | } 49 | -------------------------------------------------------------------------------- /pkg/mi/datagram.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package mi 19 | 20 | import ( 21 | "errors" 22 | "net" 23 | "sync" 24 | "time" 25 | 26 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 27 | ) 28 | 29 | type MIDatagram struct { 30 | conn *net.UDPConn 31 | buffer []byte 32 | idLock sync.Mutex 33 | id uint64 34 | done chan error 35 | } 36 | 37 | func (mi *MIDatagram) Connect(url string) error { 38 | 39 | addr, err := net.ResolveUDPAddr("udp", url) 40 | if err != nil { 41 | return err 42 | } 43 | conn, err := net.DialUDP("udp", nil, addr) 44 | if err != nil { 45 | return err 46 | } 47 | conn.SetReadBuffer(65535) 48 | conn.SetWriteBuffer(65535) 49 | mi.buffer = make([]byte, 65535) 50 | mi.conn = conn 51 | mi.done = make(chan error, 1) 52 | return nil 53 | } 54 | 55 | func (mi *MIDatagram) Addr() (net.Addr) { 56 | return mi.conn.RemoteAddr() 57 | } 58 | 59 | func (mi *MIDatagram) getReply(currentId uint64, fn MIreply) { 60 | 61 | r, _, err := mi.conn.ReadFrom(mi.buffer) 62 | if err != nil { 63 | mi.done <- err 64 | return 65 | } 66 | 67 | reply := &jsonrpc.JsonRPCResponse{} 68 | err = reply.Parse(mi.buffer[0:r]) 69 | if err != nil { 70 | mi.done <- err 71 | return 72 | } 73 | 74 | replyId, ok := reply.ID.(float64) 75 | if !ok { 76 | mi.done <- errors.New("id type error") 77 | return 78 | } 79 | 80 | if uint64(replyId) != currentId { 81 | mi.done <- errors.New("id mismatch %d") 82 | return 83 | } 84 | 85 | if fn != nil { 86 | fn(reply) 87 | } 88 | mi.done <- nil 89 | } 90 | 91 | func (mi *MIDatagram) Wait() (error) { 92 | return <- mi.done 93 | } 94 | 95 | func (mi *MIDatagram) Call(command string, params interface{}, fn MIreply) (error) { 96 | 97 | mi.idLock.Lock() 98 | currentId := mi.id 99 | mi.id += 1 100 | mi.idLock.Unlock() 101 | 102 | js := jsonrpc.NewRequest(currentId, command, params) 103 | jb, err := js.Buffer() 104 | if err != nil { 105 | return err 106 | } 107 | 108 | /* make sure the channel is drained */ 109 | for len(mi.done) > 0 { 110 | <-mi.done 111 | } 112 | /* writing the request */ 113 | mi.conn.SetWriteDeadline(time.Now().Add(time.Second)) 114 | _, err = mi.conn.Write(jb) 115 | if err != nil { 116 | return err 117 | } 118 | 119 | /* waiting for the reply */ 120 | go mi.getReply(currentId, fn) 121 | return nil 122 | } 123 | 124 | type miDatagramSync struct { 125 | reply chan *jsonrpc.JsonRPCResponse 126 | } 127 | 128 | func (mi *miDatagramSync) callSyncStore(response *jsonrpc.JsonRPCResponse) { 129 | 130 | mi.reply <- response 131 | } 132 | 133 | func (mi *MIDatagram) CallSync(command string, param interface{}) (*jsonrpc.JsonRPCResponse, error) { 134 | dgramSync := &miDatagramSync{make(chan *jsonrpc.JsonRPCResponse, 1)} 135 | 136 | err := mi.Call(command, param, dgramSync.callSyncStore); 137 | if err != nil { 138 | return nil, err 139 | } 140 | 141 | err = mi.Wait() 142 | if err != nil { 143 | return nil, err 144 | } 145 | 146 | return <- dgramSync.reply, nil 147 | } 148 | -------------------------------------------------------------------------------- /pkg/mi/mi.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package mi 19 | 20 | import ( 21 | "net" 22 | 23 | "github.com/sirupsen/logrus" 24 | "github.com/OpenSIPS/call-api/pkg/config" 25 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 26 | ) 27 | 28 | type MIreply func(response *jsonrpc.JsonRPCResponse) 29 | 30 | const default_url string = "127.0.0.1:8080" 31 | 32 | type MI interface { 33 | Addr() (net.Addr) 34 | Connect(url string) (error) 35 | Wait() (error) 36 | Call(command string, params interface{}, fn MIreply) (error) 37 | CallSync(command string, params interface{}) (*jsonrpc.JsonRPCResponse, error) 38 | } 39 | 40 | func MIHandler(config *config.Config) (MI) { 41 | /* TODO: make a wiser detection here when/if we have multiple backends */ 42 | var url string 43 | 44 | mi := new(MIDatagram) 45 | if config.MI.URL != "" { 46 | url = config.MI.URL 47 | } else { 48 | url = default_url 49 | logrus.Debugf("using default url=%s", url) 50 | } 51 | if err := mi.Connect(url); err != nil { 52 | logrus.Printf("ERROR connecting: %v", err) 53 | return nil 54 | } 55 | return mi 56 | } 57 | -------------------------------------------------------------------------------- /pkg/proxy/proxy.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package proxy 19 | 20 | import ( 21 | "github.com/sirupsen/logrus" 22 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 23 | "github.com/OpenSIPS/call-api/pkg/config" 24 | "github.com/OpenSIPS/call-api/pkg/event" 25 | "github.com/OpenSIPS/call-api/pkg/mi" 26 | ) 27 | 28 | type Proxy struct { 29 | mi mi.MI 30 | ev event.Event 31 | cfg *config.Config 32 | } 33 | 34 | func NewProxy(cfg *config.Config) (p *Proxy) { 35 | p = &Proxy{cfg: cfg} 36 | p.mi = mi.MIHandler(cfg) 37 | if p.mi == nil { 38 | logrus.Error("could not create MI handler") 39 | return nil 40 | } 41 | p.ev = event.EventHandler(p.mi) 42 | if p.ev == nil { 43 | logrus.Error("could not create event handler") 44 | return nil 45 | } 46 | return p 47 | } 48 | 49 | func (proxy *Proxy) MICall(command string, params interface{}, fn mi.MIreply) (error) { 50 | return proxy.mi.Call(command, params, fn) 51 | } 52 | 53 | func (proxy *Proxy) MICallSync(command string, params interface{}) (*jsonrpc.JsonRPCResponse, error) { 54 | return proxy.mi.CallSync(command, params) 55 | } 56 | 57 | func (proxy *Proxy) Subscribe(event string, notify event.EventNotification) (event.Subscription) { 58 | return proxy.ev.SubscribeFilter(event, notify, nil) 59 | } 60 | 61 | func (proxy *Proxy) SubscribeFilter(event string, notify event.EventNotification, filter map[string]interface{}) (event.Subscription) { 62 | return proxy.ev.SubscribeFilter(event, notify, filter) 63 | } 64 | 65 | func (proxy *Proxy) GetURI() (string) { 66 | return proxy.cfg.SIP.URI 67 | } 68 | -------------------------------------------------------------------------------- /pkg/ws_server/ws_server.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package ws_server 19 | 20 | import ( 21 | "encoding/json" 22 | "fmt" 23 | "net/http" 24 | 25 | "github.com/gorilla/websocket" 26 | "github.com/sirupsen/logrus" 27 | "github.com/OpenSIPS/call-api/internal/jsonrpc" 28 | "github.com/OpenSIPS/call-api/pkg/cmd" 29 | "github.com/OpenSIPS/call-api/pkg/config" 30 | "github.com/OpenSIPS/call-api/pkg/proxy" 31 | ) 32 | 33 | const default_ws_host string = "localhost" 34 | const default_ws_port int = 5059 35 | const default_ws_path string = "/call-api" 36 | 37 | func IgnoreCheckOrigin(r *http.Request) bool { 38 | return true; 39 | } 40 | 41 | var upgrader = websocket.Upgrader{ 42 | CheckOrigin: IgnoreCheckOrigin, 43 | } 44 | var Cfg *config.Config 45 | 46 | type WSConnection struct { 47 | conn *websocket.Conn 48 | proxy *proxy.Proxy // two-way UDP connection to a SIP proxy 49 | } 50 | 51 | type WSCmdEvent struct { 52 | cmd *cmd.Cmd 53 | event *cmd.CmdEvent 54 | } 55 | 56 | func (wsc *WSConnection) ReplyError(error_msg string, jsonrpc_id interface{}) { 57 | response := &jsonrpc.JsonRPCResponse{ 58 | JSONRPC: "2.0", 59 | ID: jsonrpc_id, 60 | Error: &jsonrpc.JsonRPCError{ 61 | Code: 32000, 62 | Message: error_msg, 63 | }, 64 | } 65 | 66 | message, err := json.Marshal(response) 67 | if err != nil { 68 | logrus.Error("failed to build JSON-RPC error") 69 | return 70 | } 71 | 72 | err = wsc.conn.WriteMessage(websocket.TextMessage, message) 73 | if err != nil { 74 | logrus.Error("write: ", err) 75 | } 76 | } 77 | 78 | func (wsc *WSConnection) ReplyOK(jsonrpc_id interface{}, cmd_id string) { 79 | response := &jsonrpc.JsonRPCResponse{ 80 | JSONRPC: "2.0", 81 | ID: jsonrpc_id, 82 | Result: &map[string]string { 83 | "event": "Started", 84 | "cmd_id": cmd_id, 85 | }, 86 | } 87 | 88 | message, err := json.Marshal(response) 89 | if err != nil { 90 | logrus.Error("failed to build JSON-RPC error message") 91 | return 92 | } 93 | 94 | err = wsc.conn.WriteMessage(websocket.TextMessage, message) 95 | if err != nil { 96 | logrus.Error("write: ", err) 97 | } 98 | } 99 | 100 | // wait for random OpenSIPS MI events on a given WebSocket connection, 101 | // possibly from multiple Call Commands running concurrently, and forward them 102 | // to the WebSocket client as JSON-RPC Notifications 103 | func (wsc *WSConnection) pollWSConnection(agg chan *WSCmdEvent) { 104 | var response *jsonrpc.JsonRPCNotification 105 | 106 | for ev := range agg { 107 | c := ev.cmd 108 | 109 | if ev.event == nil { 110 | response = jsonrpc.NewNotification(c.Command, 111 | &map[string]interface{}{ 112 | "cmd_id": c.ID, 113 | "event": "Ended", 114 | }, 115 | ) 116 | } else { 117 | logrus.Debugf("event on cmd %s (%s), event: %s", c.Command, c.ID, ev.event) 118 | 119 | if ev.event.IsError() { 120 | response = jsonrpc.NewNotification(c.Command, 121 | &map[string]interface{}{ 122 | "cmd_id": c.ID, 123 | "event": "Error", 124 | "data": ev.event.Error.Error(), 125 | }, 126 | ) 127 | } else { 128 | body := map[string]interface{}{ 129 | "cmd_id": c.ID, 130 | "event": ev.event.Name, 131 | } 132 | if ev.event.HasParams() { 133 | body["data"] = ev.event.Params 134 | } 135 | response = jsonrpc.NewNotification(c.Command, body) 136 | } 137 | } 138 | 139 | message, err := json.Marshal(response) 140 | if err != nil { 141 | logrus.Errorf("cmd %s (%s): failed to build JSON notification: %s", 142 | c.Command, c.ID, ev.event) 143 | return 144 | } 145 | 146 | err = wsc.conn.WriteMessage(websocket.TextMessage, message) 147 | if err != nil { 148 | logrus.Error("write: ", err) 149 | } 150 | } 151 | } 152 | 153 | // JSON-RPC based, two-way communication over a long-lived WebSocket connection 154 | func wsConnection(w http.ResponseWriter, r *http.Request) { 155 | var err error 156 | var cmd_id string 157 | 158 | logrus.Debugf("new connection from %s", r.RemoteAddr) 159 | 160 | wsc := &WSConnection{} 161 | wsc.conn, err = upgrader.Upgrade(w, r, nil) 162 | if err != nil { 163 | logrus.Print("upgrade:", err) 164 | return 165 | } 166 | defer wsc.conn.Close() 167 | 168 | logrus.Debug("upgraded to WebSocket") 169 | 170 | wsc.proxy = proxy.NewProxy(Cfg) 171 | if wsc.proxy == nil { 172 | logrus.Fatal("could not initialize SIP proxy") 173 | } 174 | 175 | agg := make(chan *WSCmdEvent) 176 | 177 | go wsc.pollWSConnection(agg) 178 | 179 | for { 180 | _, message, err := wsc.conn.ReadMessage() 181 | if err != nil { 182 | logrus.Info("read: ", err) 183 | break 184 | } 185 | 186 | logrus.Infof("recv: %s", message) 187 | 188 | // validate the incoming JSON-RPC query 189 | req := &jsonrpc.JsonRPCRequest{} 190 | err = req.Parse(message) 191 | if err != nil { 192 | wsc.ReplyError("failed to parse JSON-RPC request", "") 193 | continue 194 | } 195 | 196 | params, ok := req.Params.(map[string]interface{}) 197 | if !ok { 198 | wsc.ReplyError("non-object parameters are not accepted", req.ID) 199 | continue 200 | } 201 | 202 | cmd_any_id, ok := params["cmd_id"] 203 | // if there was a cmd_id in the initial request 204 | if ok { 205 | cmd_id, ok = cmd_any_id.(string) 206 | if !ok { 207 | wsc.ReplyError("bad cmd_id (must be a string)", req.ID) 208 | continue 209 | } 210 | } else { 211 | cmd_id = "" 212 | } 213 | 214 | c := cmd.New(req.Method, cmd_id, wsc.proxy) 215 | if c == nil { 216 | wsc.ReplyError("unknown JSON-RPC method", req.ID) 217 | continue 218 | } 219 | 220 | // we expect to receive at least a close on this command's channel 221 | go func(c *cmd.Cmd) { 222 | for event := range c.Wait() { 223 | agg <- &WSCmdEvent{c, event} 224 | } 225 | 226 | logrus.Debugf("done reading events for cmd %s (%s)", c.Command, c.ID) 227 | agg <- &WSCmdEvent{c, nil} 228 | }(c) 229 | 230 | // launch the Calling command to run asynchronously 231 | err = c.Run(params) 232 | if err != nil { 233 | wsc.ReplyError("bad JSON-RPC parameters", req.ID) 234 | continue 235 | } 236 | 237 | // indicate that we've successfully launched the command 238 | wsc.ReplyOK(req.ID, c.ID) 239 | } 240 | 241 | close(agg) 242 | logrus.Debugf("closed connection from %s", r.RemoteAddr) 243 | } 244 | 245 | func Run(cfg *config.Config) { 246 | var host, path string 247 | var port int 248 | Cfg = cfg 249 | 250 | if cfg.WSServer.Host != "" { 251 | host = cfg.WSServer.Host 252 | } else { 253 | host = default_ws_host 254 | } 255 | 256 | if cfg.WSServer.Port != 0 { 257 | port = cfg.WSServer.Port 258 | } else { 259 | port = default_ws_port 260 | } 261 | 262 | if cfg.WSServer.Path != "" { 263 | path = cfg.WSServer.Path 264 | } else { 265 | path = default_ws_path 266 | } 267 | 268 | http.HandleFunc(path, wsConnection) 269 | 270 | listen := fmt.Sprintf("%s:%d", host, port) 271 | logrus.Infof("Listening for JSON-RPC over WebSocket on %s%s ...", listen, path) 272 | logrus.Fatal(http.ListenAndServe(listen, nil)) 273 | } 274 | -------------------------------------------------------------------------------- /utils/version.go: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (C) 2020 OpenSIPS Solutions 3 | // 4 | // Call API is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // Call API is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | // 17 | 18 | package utils 19 | 20 | const ( 21 | VERSION = "0.1" 22 | RELEASE = "beta" 23 | ) 24 | 25 | var ( 26 | GitCommit string 27 | BuildTime string 28 | ) 29 | 30 | func GetFullVersion() (string) { 31 | var version string 32 | 33 | version = "v" + VERSION 34 | if RELEASE != "" { 35 | version += "-" + RELEASE 36 | } 37 | if GitCommit != "" { 38 | version += "-" + GitCommit[0:12] 39 | } 40 | if BuildTime != "" { 41 | version += "@" + BuildTime 42 | } 43 | return version 44 | } 45 | --------------------------------------------------------------------------------