├── .gitignore ├── .idea └── codeStyles │ └── Project.xml ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── data ├── org.asamk.Signal.conf ├── org.asamk.Signal.service ├── signal-cli@.service └── signal.service ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── man ├── Makefile └── signal-cli.1.adoc ├── settings.gradle └── src └── main ├── AndroidManifest.xml ├── java └── org │ └── asamk │ ├── Signal.java │ └── signal │ ├── AttachmentInvalidException.java │ ├── GroupNotFoundException.java │ ├── JsonAttachment.java │ ├── JsonCallMessage.java │ ├── JsonDataMessage.java │ ├── JsonError.java │ ├── JsonGroupInfo.java │ ├── JsonMessageEnvelope.java │ ├── JsonSyncMessage.java │ ├── Main.java │ ├── Manager.java │ ├── NotAGroupMemberException.java │ ├── TrustLevel.java │ ├── UserAlreadyExists.java │ ├── WhisperTrustStore.java │ ├── storage │ ├── contacts │ │ ├── ContactInfo.java │ │ └── JsonContactsStore.java │ ├── groups │ │ ├── GroupInfo.java │ │ └── JsonGroupStore.java │ ├── protocol │ │ ├── JsonIdentityKeyStore.java │ │ ├── JsonPreKeyStore.java │ │ ├── JsonSessionStore.java │ │ ├── JsonSignalProtocolStore.java │ │ └── JsonSignedPreKeyStore.java │ └── threads │ │ ├── JsonThreadStore.java │ │ └── ThreadInfo.java │ └── util │ ├── Hex.java │ └── Util.java └── resources └── org └── asamk └── signal └── whisper.store /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/* 3 | !.idea/codeStyles/ 4 | build/ 5 | *~ 6 | *.swp 7 | *.iml 8 | local.properties 9 | .classpath 10 | .project 11 | .settings/ 12 | out/ 13 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 16 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | before_cache: 3 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 4 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 5 | cache: 6 | directories: 7 | - $HOME/.gradle/caches/ 8 | - $HOME/.gradle/wrapper/ 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # signal-cli 2 | 3 | signal-cli is a commandline interface for [libsignal-service-java](https://github.com/WhisperSystems/libsignal-service-java). It supports registering, verifying, sending and receiving messages. 4 | To be able to link to an existing Signal-Android/signal-cli instance, signal-cli uses a [patched libsignal-service-java](https://github.com/AsamK/libsignal-service-java), because libsignal-service-java does not yet support [provisioning as a slave device](https://github.com/WhisperSystems/libsignal-service-java/pull/21). 5 | For registering you need a phone number where you can receive SMS or incoming calls. 6 | signal-cli is primarily intended to be used on servers to notify admins of important events. For this use-case, it has a dbus interface, that can be used to send messages from any programming language that has dbus bindings. 7 | 8 | ## Installation 9 | 10 | You can [build signal-cli](#building) yourself, or use the [provided binary files](https://github.com/AsamK/signal-cli/releases/latest), which should work on Linux, macOS and Windows. For Arch Linux there is also a [package in AUR](https://aur.archlinux.org/packages/signal-cli/). You need to have at least JRE 7 installed, to run signal-cli. 11 | 12 | ### Install system-wide on Linux 13 | See [latest version](https://github.com/AsamK/signal-cli/releases). 14 | ```sh 15 | export VERSION= 16 | wget https://github.com/AsamK/signal-cli/releases/download/v"${VERSION}"/signal-cli-"${VERSION}".tar.gz 17 | sudo tar xf signal-cli-"${VERSION}".tar.gz -C /opt 18 | sudo ln -sf /opt/signal-cli-"${VERSION}"/bin/signal-cli /usr/local/bin/ 19 | ``` 20 | 21 | ## Usage 22 | 23 | Important: The USERNAME (your phone number) must include the country calling code, i.e. the number must start with a "+" sign. (See [Wikipedia](https://en.wikipedia.org/wiki/List_of_country_calling_codes) for a list of all country codes. 24 | 25 | * Register a number (with SMS verification) 26 | 27 | signal-cli -u USERNAME register 28 | 29 | * Verify the number using the code received via SMS or voice 30 | 31 | signal-cli -u USERNAME verify CODE 32 | 33 | * Send a message 34 | 35 | signal-cli -u USERNAME send -m "This is a message" RECIPIENT 36 | 37 | * Pipe the message content from another process. 38 | 39 | uname -a | signal-cli -u USERNAME send RECIPIENT 40 | 41 | * Receive messages 42 | 43 | signal-cli -u USERNAME receive 44 | 45 | For more information read the [man page](https://github.com/AsamK/signal-cli/blob/master/man/signal-cli.1.adoc) and the [wiki](https://github.com/AsamK/signal-cli/wiki). 46 | 47 | ## Storage 48 | 49 | The password and cryptographic keys are created when registering and stored in the current users home directory: 50 | 51 | $HOME/.config/signal/data/ 52 | 53 | For legacy users, the old config directory is used as a fallback: 54 | 55 | $HOME/.config/textsecure/data/ 56 | 57 | ## Building 58 | 59 | This project uses [Gradle](http://gradle.org) for building and maintaining 60 | dependencies. If you have a recent gradle version installed, you can replace `./gradlew` with `gradle` in the following steps. 61 | 62 | 1. Checkout the source somewhere on your filesystem with 63 | 64 | git clone https://github.com/AsamK/signal-cli.git 65 | 66 | 2. Execute Gradle: 67 | 68 | ./gradlew build 69 | 70 | 3. Create shell wrapper in *build/install/signal-cli/bin*: 71 | 72 | ./gradlew installDist 73 | 74 | 4. Create tar file in *build/distributions*: 75 | 76 | ./gradlew distTar 77 | 78 | ## Troubleshooting 79 | If you use a version of the Oracle JRE and get an InvalidKeyException you need to enable unlimited strength crypto. See https://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters for instructions. 80 | 81 | ## License 82 | 83 | This project uses libsignal-service-java from Open Whisper Systems: 84 | 85 | https://github.com/WhisperSystems/libsignal-service-java 86 | 87 | Licensed under the GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 88 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'maven' 3 | 4 | buildscript { 5 | repositories { 6 | jcenter() 7 | google() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.0.0' 11 | } 12 | } 13 | 14 | repositories { 15 | jcenter() 16 | google() 17 | } 18 | 19 | version = '0.6.0' 20 | 21 | android { 22 | 23 | project.ext { 24 | appcompat='com.android.support:appcompat-v7:25.2.0' 25 | } 26 | 27 | compileSdkVersion 25 28 | buildToolsVersion '26.0.2' 29 | 30 | defaultConfig { 31 | minSdkVersion 16 32 | targetSdkVersion 25 33 | } 34 | 35 | buildTypes { 36 | release { 37 | minifyEnabled false 38 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 39 | } 40 | } 41 | 42 | dependencies { 43 | compile project.ext.appcompat 44 | } 45 | buildToolsVersion '26.0.2' 46 | } 47 | 48 | 49 | dependencies { 50 | compile 'com.github.turasa:signal-service-java:2.7.5_unofficial_1' 51 | compile 'org.bouncycastle:bcprov-jdk15on:1.59' 52 | compile 'net.sourceforge.argparse4j:argparse4j:0.8.1' 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /data/org.asamk.Signal.conf: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /data/org.asamk.Signal.service: -------------------------------------------------------------------------------- 1 | [D-BUS Service] 2 | Name=org.asamk.Signal 3 | Exec=/bin/false 4 | SystemdService=dbus-org.asamk.Signal.service 5 | -------------------------------------------------------------------------------- /data/signal-cli@.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Send secure messages to Signal clients 3 | Requires=dbus.socket 4 | After=dbus.socket 5 | Wants=network-online.target 6 | After=network-online.target 7 | 8 | [Service] 9 | Type=dbus 10 | Environment="SIGNAL_CLI_OPTS=-Xms2m" 11 | ExecStart=%dir%/bin/signal-cli -u %I --config /var/lib/signal-cli daemon --system 12 | User=signal-cli 13 | BusName=org.asamk.Signal 14 | 15 | [Install] 16 | WantedBy=multi-user.target 17 | -------------------------------------------------------------------------------- /data/signal.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Send secure messages to Signal clients 3 | Requires=dbus.socket 4 | After=dbus.socket 5 | Wants=network-online.target 6 | After=network-online.target 7 | 8 | [Service] 9 | Type=dbus 10 | Environment="SIGNAL_CLI_OPTS=-Xms2m" 11 | ExecStart=%dir%/bin/signal-cli -u %number% --config /var/lib/signal-cli daemon --system 12 | User=signal-cli 13 | BusName=org.asamk.Signal 14 | 15 | [Install] 16 | Alias=dbus-org.asamk.Signal.service 17 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guardianproject/signal-cli-android/d319e2feaf44dbb6a1c6a43d55a57f391e939ef4/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.7-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /man/Makefile: -------------------------------------------------------------------------------- 1 | A2X = a2x 2 | 3 | MANPAGESRC = signal-cli.1 4 | 5 | .PHONY: all 6 | all: $(MANPAGESRC) 7 | 8 | %: %.adoc 9 | @echo "Generating manpage for $@" 10 | $(A2X) --no-xmllint --doctype manpage --format manpage "$^" 11 | -------------------------------------------------------------------------------- /man/signal-cli.1.adoc: -------------------------------------------------------------------------------- 1 | ///// 2 | vim:set ts=4 sw=4 tw=82 noet: 3 | ///// 4 | :quotes.~: 5 | 6 | = signal-cli (1) 7 | 8 | Name 9 | ---- 10 | signal-cli - A commandline and dbus interface for the Signal messenger 11 | 12 | Synopsis 13 | -------- 14 | *signal-cli* [--config CONFIG] [-h | -v | -u USERNAME | --dbus | --dbus-system] command [command-options] 15 | 16 | Description 17 | ----------- 18 | 19 | signal-cli is a commandline interface for libsignal-service-java. It supports 20 | registering, verifying, sending and receiving messages. For registering you need a 21 | phone number where you can receive SMS or incoming calls. 22 | signal-cli was primarily developed to be used on servers to notify admins of 23 | important events. For this use-case, it has a dbus interface, that can be used to 24 | send messages from any programming language that has dbus bindings. 25 | 26 | Options 27 | ------- 28 | 29 | *-h*, *--help*:: 30 | Show help message and quit. 31 | 32 | *-v*, *--version*:: 33 | Print the version and quit. 34 | 35 | *--config* CONFIG:: 36 | Set the path, where to store the config. 37 | Make sure you have full read/write access to the given directory. 38 | (Default: $HOME/.config/signal) 39 | 40 | *-u* USERNAME, *--username* USERNAME:: 41 | Specify your phone number, that will be your identifier. 42 | The phone number must include the country calling code, i.e. the number must 43 | start with a "+" sign. 44 | 45 | *--dbus*:: 46 | Make request via user dbus. 47 | 48 | *--dbus-system*:: 49 | Make request via system dbus. 50 | 51 | Commands 52 | -------- 53 | 54 | register 55 | ~~~~~~~~ 56 | Register a phone number with SMS or voice verification. Use the verify command to 57 | complete the verification. 58 | 59 | *-v*, *--voice*:: 60 | The verification should be done over voice, not SMS. 61 | 62 | verify 63 | ~~~~~~ 64 | Verify the number using the code received via SMS or voice. 65 | 66 | VERIFICATIONCODE:: 67 | The verification code. 68 | 69 | *-p* PIN, *--pin* PIN:: 70 | The registration lock PIN, that was set by the user. Only required if a PIN was set. 71 | 72 | unregister 73 | ~~~~~~~~~~ 74 | Disable push support for this device, i.e. this device won't receive any more messages. 75 | If this is the master device, other users can't send messages to this number anymore. 76 | Use "updateAccount" to undo this. 77 | To remove a linked device, use "removeDevice" from the master device. 78 | 79 | updateAccount 80 | ~~~~~~~~~~~~~ 81 | Update the account attributes on the signal server. 82 | Can fix problems with receiving messages. 83 | 84 | setPin 85 | ~~~~~~ 86 | Set a registration lock pin, to prevent others from registering this number. 87 | 88 | REGISTRATION_LOCK_PIN:: 89 | The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity) 90 | 91 | removePin 92 | ~~~~~~ 93 | Remove the registration lock pin. 94 | 95 | link 96 | ~~~~ 97 | Link to an existing device, instead of registering a new number. This shows a 98 | "tsdevice:/…" URI. If you want to connect to another signal-cli instance, you can 99 | just use this URI. If you want to link to an Android/iOS device, create a QR code 100 | with the URI (e.g. with qrencode) and scan that in the Signal app. 101 | 102 | *-n* NAME, *--name* NAME:: 103 | Optionally specify a name to describe this new device. By default "cli" will 104 | be used. 105 | 106 | addDevice 107 | ~~~~~~~~~ 108 | Link another device to this device. Only works, if this is the master device. 109 | 110 | *--uri* URI:: 111 | Specify the uri contained in the QR code shown by the new device. 112 | 113 | listDevices 114 | ~~~~~~~~~~~ 115 | Show a list of connected devices. 116 | 117 | removeDevice 118 | ~~~~~~~~~~~~ 119 | Remove a connected device. Only works, if this is the master device. 120 | 121 | *-d* DEVICEID, *--deviceId* DEVICEID:: 122 | Specify the device you want to remove. Use listDevices to see the deviceIds. 123 | 124 | send 125 | ~~~~ 126 | Send a message to another user or group. 127 | 128 | RECIPIENT:: 129 | Specify the recipients’ phone number. 130 | 131 | *-g* GROUP, *--group* GROUP:: 132 | Specify the recipient group ID in base64 encoding. 133 | 134 | *-m* MESSAGE, *--message* MESSAGE:: 135 | Specify the message, if missing, standard input is used. 136 | 137 | *-a* [ATTACHMENT [ATTACHMENT ...]], *--attachment* [ATTACHMENT [ATTACHMENT ...]]:: 138 | Add one or more files as attachment. 139 | 140 | *-e*, *--endsession*:: 141 | Clear session state and send end session message. 142 | 143 | receive 144 | ~~~~~~~ 145 | Query the server for new messages. New messages are printed on standardoutput and 146 | attachments are downloaded to the config directory. 147 | 148 | *-t* TIMEOUT, *--timeout* TIMEOUT:: 149 | Number of seconds to wait for new messages (negative values disable timeout). 150 | Default is 5 seconds. 151 | *--ignore-attachments*:: 152 | Don’t download attachments of received messages. 153 | *--json*:: 154 | Output received messages in json format, one object per line. 155 | 156 | updateGroup 157 | ~~~~~~~~~~~ 158 | Create or update a group. 159 | 160 | *-g* GROUP, *--group* GROUP:: 161 | Specify the recipient group ID in base64 encoding. If not specified, a new 162 | group with a new random ID is generated. 163 | 164 | *-n* NAME, *--name* NAME:: 165 | Specify the new group name. 166 | 167 | *-a* AVATAR, *--avatar* AVATAR:: 168 | Specify a new group avatar image file. 169 | 170 | *-m* [MEMBER [MEMBER ...]], *--member* [MEMBER [MEMBER ...]]:: 171 | Specify one or more members to add to the group. 172 | 173 | quitGroup 174 | ~~~~~~~~~ 175 | Send a quit group message to all group members and remove self from member list. 176 | 177 | *-g* GROUP, *--group* GROUP:: 178 | Specify the recipient group ID in base64 encoding. 179 | 180 | listGroups 181 | ~~~~~~~~~~~ 182 | Show a list of known groups. 183 | 184 | *-d*, *--detailed*:: 185 | Include the list of members of each group. 186 | 187 | listIdentities 188 | ~~~~~~~~~~~~~~ 189 | List all known identity keys and their trust status, fingerprint and safety 190 | number. 191 | 192 | *-n* NUMBER, *--number* NUMBER:: 193 | Only show identity keys for the given phone number. 194 | 195 | trust 196 | ~~~~~ 197 | Set the trust level of a given number. The first time a key for a number is seen, 198 | it is trusted by default (TOFU). If the key changes, the new key must be trusted 199 | manually. 200 | 201 | number:: 202 | Specify the phone number, for which to set the trust. 203 | 204 | *-a*, *--trust-all-known-keys*:: 205 | Trust all known keys of this user, only use this for testing. 206 | 207 | *-v* VERIFIED_FINGERPRINT, *--verified-fingerprint* VERIFIED_FINGERPRINT:: 208 | Specify the safety number or fingerprint of the key, only use this option if you have verified 209 | the fingerprint. 210 | 211 | 212 | daemon 213 | ~~~~~~ 214 | signal-cli can run in daemon mode and provides an experimental dbus interface. For 215 | dbus support you need jni/unix-java.so installed on your system (Debian: 216 | libunixsocket-java ArchLinux: libmatthew-unix-java (AUR)). 217 | 218 | *--system*:: 219 | Use DBus system bus instead of user bus. 220 | *--ignore-attachments*:: 221 | Don’t download attachments of received messages. 222 | 223 | 224 | Examples 225 | -------- 226 | 227 | Register a number (with SMS verification):: 228 | signal-cli -u USERNAME register 229 | 230 | Verify the number using the code received via SMS or voice:: 231 | signal-cli -u USERNAME verify CODE 232 | 233 | Send a message to one or more recipients:: 234 | signal-cli -u USERNAME send -m "This is a message" [RECIPIENT [RECIPIENT ...]] [-a [ATTACHMENT [ATTACHMENT ...]]] 235 | 236 | Pipe the message content from another process:: 237 | uname -a | signal-cli -u USERNAME send [RECIPIENT [RECIPIENT ...]] 238 | 239 | Create a group:: 240 | signal-cli -u USERNAME updateGroup -n "Group name" -m [MEMBER [MEMBER ...]] 241 | 242 | Add member to a group:: 243 | signal-cli -u USERNAME updateGroup -g GROUP_ID -m "NEW_MEMBER" 244 | 245 | Leave a group:: 246 | signal-cli -u USERNAME quitGroup -g GROUP_ID 247 | 248 | Send a message to a group:: 249 | signal-cli -u USERNAME send -m "This is a message" -g GROUP_ID 250 | 251 | Trust new key, after having verified it:: 252 | signal-cli -u USERNAME trust -v FINGER_PRINT NUMBER 253 | 254 | Trust new key, without having verified it. Only use this if you don't care about security:: 255 | signal-cli -u USERNAME trust -a NUMBER 256 | 257 | Files 258 | ----- 259 | The password and cryptographic keys are created when registering and stored in the 260 | current users home directory, the directory can be changed with *--config*: 261 | 262 | $HOME/.config/signal/ 263 | 264 | For legacy users, the old config directory is used as a fallback: 265 | 266 | $HOME/.config/textsecure/ 267 | 268 | 269 | Authors 270 | ------- 271 | 272 | Maintained by AsamK , who is assisted by other open 273 | source contributors. For more information about signal-cli development, see 274 | . 275 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was auto generated by the Gradle buildInit task 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * In a single project build this file can be empty or even removed. 6 | * 7 | * Detailed information about configuring a multi-project build in Gradle can be found 8 | * in the user guide at http://gradle.org/docs/2.2.1/userguide/multi_project_builds.html 9 | */ 10 | 11 | /* 12 | // To declare projects as part of a multi-project build use the 'include' method 13 | include 'shared' 14 | include 'api' 15 | include 'services:webservice' 16 | */ 17 | 18 | rootProject.name = 'signal-cli' 19 | -------------------------------------------------------------------------------- /src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/Signal.java: -------------------------------------------------------------------------------- 1 | package org.asamk; 2 | 3 | import org.asamk.signal.AttachmentInvalidException; 4 | import org.asamk.signal.GroupNotFoundException; 5 | import org.asamk.signal.NotAGroupMemberException; 6 | import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions; 7 | 8 | import java.io.IOException; 9 | import java.util.List; 10 | 11 | public interface Signal { 12 | void sendMessage(String message, List attachments, String recipient) throws EncapsulatedExceptions, AttachmentInvalidException, IOException; 13 | 14 | void sendMessage(String message, List attachments, List recipients) throws EncapsulatedExceptions, AttachmentInvalidException, IOException; 15 | 16 | void sendEndSessionMessage(List recipients) throws IOException, EncapsulatedExceptions; 17 | 18 | void sendGroupMessage(String message, List attachments, byte[] groupId) throws EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException, IOException, NotAGroupMemberException; 19 | 20 | String getContactName(String number); 21 | 22 | void setContactName(String number, String name); 23 | 24 | List getGroupIds(); 25 | 26 | String getGroupName(byte[] groupId); 27 | 28 | List getGroupMembers(byte[] groupId); 29 | 30 | byte[] updateGroup(byte[] groupId, String name, List members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException; 31 | 32 | class MessageReceived { 33 | private long timestamp; 34 | private String sender; 35 | private byte[] groupId; 36 | private String message; 37 | private List attachments; 38 | 39 | public MessageReceived(String objectpath, long timestamp, String sender, byte[] groupId, String message, List attachments) throws Exception { 40 | this.timestamp = timestamp; 41 | this.sender = sender; 42 | this.groupId = groupId; 43 | this.message = message; 44 | this.attachments = attachments; 45 | } 46 | 47 | public long getTimestamp() { 48 | return timestamp; 49 | } 50 | 51 | public String getSender() { 52 | return sender; 53 | } 54 | 55 | public byte[] getGroupId() { 56 | return groupId; 57 | } 58 | 59 | public String getMessage() { 60 | return message; 61 | } 62 | 63 | public List getAttachments() { 64 | return attachments; 65 | } 66 | } 67 | 68 | class ReceiptReceived { 69 | private long timestamp; 70 | private String sender; 71 | 72 | public ReceiptReceived(String objectpath, long timestamp, String sender) throws Exception { 73 | this.timestamp = timestamp; 74 | this.sender = sender; 75 | } 76 | 77 | public long getTimestamp() { 78 | return timestamp; 79 | } 80 | 81 | public String getSender() { 82 | return sender; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/AttachmentInvalidException.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | 4 | public class AttachmentInvalidException extends Exception { 5 | public AttachmentInvalidException(String message) { 6 | super(message); 7 | } 8 | 9 | public AttachmentInvalidException(String attachment, Exception e) { 10 | super(attachment + ": " + e.getMessage()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/GroupNotFoundException.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.internal.util.Base64; 4 | 5 | public class GroupNotFoundException extends Exception { 6 | 7 | public GroupNotFoundException(String message) { 8 | super(message); 9 | } 10 | 11 | public GroupNotFoundException(byte[] groupId) { 12 | super("Group not found: " + Base64.encodeBytes(groupId)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonAttachment.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.SignalServiceAttachment; 4 | import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer; 5 | 6 | class JsonAttachment { 7 | String contentType; 8 | long id; 9 | int size; 10 | 11 | JsonAttachment(SignalServiceAttachment attachment) { 12 | this.contentType = attachment.getContentType(); 13 | final SignalServiceAttachmentPointer pointer = attachment.asPointer(); 14 | if (attachment.isPointer()) { 15 | this.id = pointer.getId(); 16 | if (pointer.getSize().isPresent()) { 17 | this.size = pointer.getSize().get(); 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonCallMessage.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.calls.*; 4 | 5 | import java.util.List; 6 | 7 | class JsonCallMessage { 8 | OfferMessage offerMessage; 9 | AnswerMessage answerMessage; 10 | BusyMessage busyMessage; 11 | HangupMessage hangupMessage; 12 | List iceUpdateMessages; 13 | 14 | JsonCallMessage(SignalServiceCallMessage callMessage) { 15 | if (callMessage.getOfferMessage().isPresent()) { 16 | this.offerMessage = callMessage.getOfferMessage().get(); 17 | } 18 | if (callMessage.getAnswerMessage().isPresent()) { 19 | this.answerMessage = callMessage.getAnswerMessage().get(); 20 | } 21 | if (callMessage.getBusyMessage().isPresent()) { 22 | this.busyMessage = callMessage.getBusyMessage().get(); 23 | } 24 | if (callMessage.getHangupMessage().isPresent()) { 25 | this.hangupMessage = callMessage.getHangupMessage().get(); 26 | } 27 | if (callMessage.getIceUpdateMessages().isPresent()) { 28 | this.iceUpdateMessages = callMessage.getIceUpdateMessages().get(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonDataMessage.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.SignalServiceAttachment; 4 | import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | class JsonDataMessage { 10 | long timestamp; 11 | String message; 12 | int expiresInSeconds; 13 | List attachments; 14 | JsonGroupInfo groupInfo; 15 | 16 | JsonDataMessage(SignalServiceDataMessage dataMessage) { 17 | this.timestamp = dataMessage.getTimestamp(); 18 | if (dataMessage.getGroupInfo().isPresent()) { 19 | this.groupInfo = new JsonGroupInfo(dataMessage.getGroupInfo().get()); 20 | } 21 | if (dataMessage.getBody().isPresent()) { 22 | this.message = dataMessage.getBody().get(); 23 | } 24 | this.expiresInSeconds = dataMessage.getExpiresInSeconds(); 25 | if (dataMessage.getAttachments().isPresent()) { 26 | this.attachments = new ArrayList<>(dataMessage.getAttachments().get().size()); 27 | for (SignalServiceAttachment attachment : dataMessage.getAttachments().get()) { 28 | this.attachments.add(new JsonAttachment(attachment)); 29 | } 30 | } else { 31 | this.attachments = new ArrayList<>(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonError.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | class JsonError { 4 | String message; 5 | 6 | JsonError(Throwable exception) { 7 | this.message = exception.getMessage(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonGroupInfo.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.SignalServiceGroup; 4 | import org.whispersystems.signalservice.internal.util.Base64; 5 | 6 | import java.util.List; 7 | 8 | class JsonGroupInfo { 9 | String groupId; 10 | List members; 11 | String name; 12 | String type; 13 | 14 | JsonGroupInfo(SignalServiceGroup groupInfo) { 15 | this.groupId = Base64.encodeBytes(groupInfo.getGroupId()); 16 | if (groupInfo.getMembers().isPresent()) { 17 | this.members = groupInfo.getMembers().get(); 18 | } 19 | if (groupInfo.getName().isPresent()) { 20 | this.name = groupInfo.getName().get(); 21 | } 22 | this.type = groupInfo.getType().toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonMessageEnvelope.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.SignalServiceContent; 4 | import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope; 5 | import org.whispersystems.signalservice.api.push.SignalServiceAddress; 6 | 7 | class JsonMessageEnvelope { 8 | String source; 9 | int sourceDevice; 10 | String relay; 11 | long timestamp; 12 | boolean isReceipt; 13 | JsonDataMessage dataMessage; 14 | JsonSyncMessage syncMessage; 15 | JsonCallMessage callMessage; 16 | 17 | public JsonMessageEnvelope(SignalServiceEnvelope envelope, SignalServiceContent content) { 18 | SignalServiceAddress source = envelope.getSourceAddress(); 19 | this.source = source.getNumber(); 20 | this.sourceDevice = envelope.getSourceDevice(); 21 | this.relay = source.getRelay().isPresent() ? source.getRelay().get() : null; 22 | this.timestamp = envelope.getTimestamp(); 23 | this.isReceipt = envelope.isReceipt(); 24 | if (content != null) { 25 | if (content.getDataMessage().isPresent()) { 26 | this.dataMessage = new JsonDataMessage(content.getDataMessage().get()); 27 | } 28 | if (content.getSyncMessage().isPresent()) { 29 | this.syncMessage = new JsonSyncMessage(content.getSyncMessage().get()); 30 | } 31 | if (content.getCallMessage().isPresent()) { 32 | this.callMessage = new JsonCallMessage(content.getCallMessage().get()); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/JsonSyncMessage.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.multidevice.ReadMessage; 4 | import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage; 5 | 6 | import java.util.List; 7 | 8 | class JsonSyncMessage { 9 | JsonDataMessage sentMessage; 10 | List blockedNumbers; 11 | List readMessages; 12 | 13 | JsonSyncMessage(SignalServiceSyncMessage syncMessage) { 14 | if (syncMessage.getSent().isPresent()) { 15 | this.sentMessage = new JsonDataMessage(syncMessage.getSent().get().getMessage()); 16 | } 17 | if (syncMessage.getBlockedList().isPresent()) { 18 | this.blockedNumbers = syncMessage.getBlockedList().get().getNumbers(); 19 | } 20 | if (syncMessage.getRead().isPresent()) { 21 | this.readMessages = syncMessage.getRead().get(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015 AsamK 3 | * 4 | * This program 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 | * This program 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 | package org.asamk.signal; 18 | 19 | import android.content.Context; 20 | 21 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 22 | import com.fasterxml.jackson.annotation.PropertyAccessor; 23 | import com.fasterxml.jackson.core.JsonGenerator; 24 | import com.fasterxml.jackson.databind.DeserializationFeature; 25 | import com.fasterxml.jackson.databind.ObjectMapper; 26 | import com.fasterxml.jackson.databind.SerializationFeature; 27 | import com.fasterxml.jackson.databind.node.ObjectNode; 28 | import net.sourceforge.argparse4j.ArgumentParsers; 29 | import net.sourceforge.argparse4j.impl.Arguments; 30 | import net.sourceforge.argparse4j.inf.*; 31 | import org.apache.http.util.TextUtils; 32 | import org.asamk.Signal; 33 | import org.asamk.signal.storage.contacts.ContactInfo; 34 | import org.asamk.signal.storage.groups.GroupInfo; 35 | import org.asamk.signal.storage.protocol.JsonIdentityKeyStore; 36 | import org.asamk.signal.util.Hex; 37 | import org.whispersystems.libsignal.InvalidKeyException; 38 | import org.whispersystems.libsignal.util.guava.Optional; 39 | import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; 40 | import org.whispersystems.signalservice.api.messages.*; 41 | import org.whispersystems.signalservice.api.messages.calls.*; 42 | import org.whispersystems.signalservice.api.messages.multidevice.*; 43 | import org.whispersystems.signalservice.api.push.SignalServiceAddress; 44 | import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions; 45 | import org.whispersystems.signalservice.api.push.exceptions.NetworkFailureException; 46 | import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException; 47 | import org.whispersystems.signalservice.api.util.PhoneNumberFormatter; 48 | import org.whispersystems.signalservice.internal.push.LockedException; 49 | import org.whispersystems.signalservice.internal.util.Base64; 50 | 51 | import java.io.File; 52 | import java.io.IOException; 53 | import java.io.InputStream; 54 | import java.io.StringWriter; 55 | import java.net.URI; 56 | import java.net.URISyntaxException; 57 | import java.nio.charset.Charset; 58 | import java.security.Security; 59 | import java.text.DateFormat; 60 | import java.text.SimpleDateFormat; 61 | import java.util.*; 62 | import java.util.concurrent.TimeUnit; 63 | import java.util.concurrent.TimeoutException; 64 | 65 | public class Main { 66 | 67 | private static final TimeZone tzUTC = TimeZone.getTimeZone("UTC"); 68 | 69 | private Context mContext; 70 | private File mFileHome; 71 | private Manager m; 72 | 73 | public Main (Context context) 74 | { 75 | // Workaround for BKS truststore 76 | Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1); 77 | 78 | mContext = context; 79 | mFileHome = new File(mContext.getFilesDir(),"Signal"); 80 | if (!mFileHome.exists()) 81 | mFileHome.mkdirs(); 82 | } 83 | 84 | public boolean userExists (String username) 85 | { 86 | String settingsPath = mFileHome.getPath(); 87 | if (m == null) 88 | m = new Manager(username, settingsPath); 89 | 90 | boolean result = m.userExists(); 91 | return result; 92 | } 93 | 94 | public boolean isRegistered (String username) 95 | { 96 | String settingsPath = mFileHome.getPath(); 97 | if (m == null) 98 | m = new Manager(username, settingsPath); 99 | 100 | boolean result = m.isRegistered(); 101 | return result; 102 | } 103 | 104 | public void resetUser () 105 | { 106 | deleteRecursive(mFileHome); 107 | } 108 | 109 | private void deleteRecursive(File fileOrDirectory) { 110 | if (fileOrDirectory.isDirectory()) 111 | for (File child : fileOrDirectory.listFiles()) 112 | deleteRecursive(child); 113 | 114 | fileOrDirectory.delete(); 115 | } 116 | 117 | public int handleCommands(Namespace ns) { 118 | final String username = ns.getString("username"); 119 | Signal ts; 120 | try { 121 | 122 | String settingsPath = mFileHome.getPath(); 123 | 124 | if (m == null) 125 | m = new Manager(username, settingsPath); 126 | 127 | ts = m; 128 | if (m.userExists()) { 129 | try { 130 | m.init(); 131 | } catch (Exception e) { 132 | System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage()); 133 | return 2; 134 | } 135 | } 136 | 137 | 138 | switch (ns.getString("command")) { 139 | case "register": 140 | if (!m.userHasKeys()) { 141 | m.createNewIdentity(); 142 | } 143 | try { 144 | m.register(ns.getBoolean("voice")); 145 | } catch (IOException e) { 146 | System.err.println("Request verify error: " + e.getMessage()); 147 | return 3; 148 | } 149 | break; 150 | case "unregister": 151 | if (!m.isRegistered()) { 152 | System.err.println("User is not registered."); 153 | return 1; 154 | } 155 | try { 156 | m.unregister(); 157 | } catch (IOException e) { 158 | System.err.println("Unregister error: " + e.getMessage()); 159 | return 3; 160 | } 161 | break; 162 | case "updateAccount": 163 | if (!m.isRegistered()) { 164 | System.err.println("User is not registered."); 165 | return 1; 166 | } 167 | try { 168 | m.updateAccountAttributes(); 169 | } catch (IOException e) { 170 | System.err.println("UpdateAccount error: " + e.getMessage()); 171 | return 3; 172 | } 173 | break; 174 | case "setPin": 175 | 176 | if (!m.isRegistered()) { 177 | System.err.println("User is not registered."); 178 | return 1; 179 | } 180 | try { 181 | String registrationLockPin = ns.getString("registrationLockPin"); 182 | m.setRegistrationLockPin(Optional.of(registrationLockPin)); 183 | } catch (IOException e) { 184 | System.err.println("Set pin error: " + e.getMessage()); 185 | return 3; 186 | } 187 | break; 188 | case "removePin": 189 | 190 | if (!m.isRegistered()) { 191 | System.err.println("User is not registered."); 192 | return 1; 193 | } 194 | try { 195 | m.setRegistrationLockPin(Optional.absent()); 196 | } catch (IOException e) { 197 | System.err.println("Remove pin error: " + e.getMessage()); 198 | return 3; 199 | } 200 | break; 201 | case "verify": 202 | if (!m.userHasKeys()) { 203 | System.err.println("User has no keys, first call register."); 204 | return 1; 205 | } 206 | if (m.isRegistered()) { 207 | System.err.println("User registration is already verified"); 208 | return 1; 209 | } 210 | try { 211 | String verificationCode = ns.getString("verificationCode"); 212 | String pin = ns.getString("pin"); 213 | m.verifyAccount(verificationCode, pin); 214 | } catch (LockedException e) { 215 | System.err.println("Verification failed! This number is locked with a pin. Hours remaining until reset: " + (e.getTimeRemaining() / 1000 / 60 / 60)); 216 | System.err.println("Use '--pin PIN_CODE' to specify the registration lock PIN"); 217 | return 3; 218 | } catch (IOException e) { 219 | System.err.println("Verify error: " + e.getMessage()); 220 | return 3; 221 | } 222 | break; 223 | case "link": 224 | 225 | // When linking, username is null and we always have to create keys 226 | m.createNewIdentity(); 227 | 228 | String deviceName = ns.getString("name"); 229 | if (deviceName == null) { 230 | deviceName = "cli"; 231 | } 232 | try { 233 | System.out.println(m.getDeviceLinkUri()); 234 | m.finishDeviceLink(deviceName); 235 | System.out.println("Associated with: " + m.getUsername()); 236 | } catch (TimeoutException e) { 237 | System.err.println("Link request timed out, please try again."); 238 | return 3; 239 | } catch (IOException e) { 240 | System.err.println("Link request error: " + e.getMessage()); 241 | return 3; 242 | } catch (AssertionError e) { 243 | handleAssertionError(e); 244 | return 1; 245 | } catch (InvalidKeyException e) { 246 | e.printStackTrace(); 247 | return 2; 248 | } catch (UserAlreadyExists e) { 249 | System.err.println("The user " + e.getUsername() + " already exists\nDelete \"" + e.getFileName() + "\" before trying again."); 250 | return 1; 251 | } 252 | break; 253 | case "addDevice": 254 | if (!m.isRegistered()) { 255 | System.err.println("User is not registered."); 256 | return 1; 257 | } 258 | try { 259 | m.addDeviceLink(new URI(ns.getString("uri"))); 260 | } catch (IOException e) { 261 | e.printStackTrace(); 262 | return 3; 263 | } catch (InvalidKeyException e) { 264 | e.printStackTrace(); 265 | return 2; 266 | } catch (AssertionError e) { 267 | handleAssertionError(e); 268 | return 1; 269 | } catch (URISyntaxException e) { 270 | e.printStackTrace(); 271 | return 2; 272 | } 273 | break; 274 | case "listDevices": 275 | if (!m.isRegistered()) { 276 | System.err.println("User is not registered."); 277 | return 1; 278 | } 279 | try { 280 | List devices = m.getLinkedDevices(); 281 | for (DeviceInfo d : devices) { 282 | System.out.println("Device " + d.getId() + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":"); 283 | System.out.println(" Name: " + d.getName()); 284 | System.out.println(" Created: " + formatTimestamp(d.getCreated())); 285 | System.out.println(" Last seen: " + formatTimestamp(d.getLastSeen())); 286 | } 287 | } catch (IOException e) { 288 | e.printStackTrace(); 289 | return 3; 290 | } 291 | break; 292 | case "removeDevice": 293 | if (!m.isRegistered()) { 294 | System.err.println("User is not registered."); 295 | return 1; 296 | } 297 | try { 298 | int deviceId = ns.getInt("deviceId"); 299 | m.removeLinkedDevices(deviceId); 300 | } catch (IOException e) { 301 | e.printStackTrace(); 302 | return 3; 303 | } 304 | break; 305 | case "send": 306 | 307 | if (ns.getBoolean("endsession")) { 308 | if (ns.getList("recipient") == null) { 309 | System.err.println("No recipients given"); 310 | System.err.println("Aborting sending."); 311 | return 1; 312 | } 313 | try { 314 | ts.sendEndSessionMessage(ns.getList("recipient")); 315 | } catch (IOException e) { 316 | handleIOException(e); 317 | return 3; 318 | } catch (EncapsulatedExceptions e) { 319 | handleEncapsulatedExceptions(e); 320 | return 3; 321 | } catch (AssertionError e) { 322 | handleAssertionError(e); 323 | return 1; 324 | } 325 | } else { 326 | String messageText = ns.getString("message"); 327 | if (messageText == null) { 328 | try { 329 | messageText = readAll(System.in); 330 | } catch (IOException e) { 331 | System.err.println("Failed to read message from stdin: " + e.getMessage()); 332 | System.err.println("Aborting sending."); 333 | return 1; 334 | } 335 | } 336 | 337 | try { 338 | List attachments = ns.getList("attachment"); 339 | if (attachments == null) { 340 | attachments = new ArrayList<>(); 341 | } 342 | if (ns.getString("group") != null) { 343 | byte[] groupId = decodeGroupId(ns.getString("group")); 344 | ts.sendGroupMessage(messageText, attachments, groupId); 345 | } else { 346 | ts.sendMessage(messageText, attachments, ns.getList("recipient")); 347 | } 348 | } catch (IOException e) { 349 | handleIOException(e); 350 | return 3; 351 | } catch (EncapsulatedExceptions e) { 352 | handleEncapsulatedExceptions(e); 353 | return 3; 354 | } catch (AssertionError e) { 355 | handleAssertionError(e); 356 | return 1; 357 | } catch (GroupNotFoundException e) { 358 | handleGroupNotFoundException(e); 359 | return 1; 360 | } catch (AttachmentInvalidException e) { 361 | System.err.println("Failed to add attachment: " + e.getMessage()); 362 | System.err.println("Aborting sending."); 363 | return 1; 364 | } catch (NotAGroupMemberException e) { 365 | e.printStackTrace(); 366 | } 367 | } 368 | 369 | break; 370 | case "receive": 371 | 372 | if (!m.isRegistered()) { 373 | System.err.println("User is not registered."); 374 | return 1; 375 | } 376 | double timeout = 5; 377 | if (ns.getDouble("timeout") != null) { 378 | timeout = ns.getDouble("timeout"); 379 | } 380 | boolean returnOnTimeout = true; 381 | if (timeout < 0) { 382 | returnOnTimeout = false; 383 | timeout = 3600; 384 | } 385 | boolean ignoreAttachments = ns.getBoolean("ignore_attachments"); 386 | try { 387 | final Manager.ReceiveMessageHandler handler = ns.getBoolean("json") ? new JsonReceiveMessageHandler(m) : new ReceiveMessageHandler(m); 388 | m.receiveMessages((long) (timeout * 1000), TimeUnit.MILLISECONDS, returnOnTimeout, ignoreAttachments, handler); 389 | } catch (IOException e) { 390 | System.err.println("Error while receiving messages: " + e.getMessage()); 391 | return 3; 392 | } catch (AssertionError e) { 393 | handleAssertionError(e); 394 | return 1; 395 | } 396 | break; 397 | case "quitGroup": 398 | 399 | if (!m.isRegistered()) { 400 | System.err.println("User is not registered."); 401 | return 1; 402 | } 403 | 404 | try { 405 | m.sendQuitGroupMessage(decodeGroupId(ns.getString("group"))); 406 | } catch (IOException e) { 407 | handleIOException(e); 408 | return 3; 409 | } catch (EncapsulatedExceptions e) { 410 | handleEncapsulatedExceptions(e); 411 | return 3; 412 | } catch (AssertionError e) { 413 | handleAssertionError(e); 414 | return 1; 415 | } catch (Exception e) { 416 | e.printStackTrace(); 417 | } 418 | break; 419 | case "updateGroup": 420 | 421 | 422 | try { 423 | byte[] groupId = null; 424 | if (ns.getString("group") != null) { 425 | groupId = decodeGroupId(ns.getString("group")); 426 | } 427 | if (groupId == null) { 428 | groupId = new byte[0]; 429 | } 430 | String groupName = ns.getString("name"); 431 | if (groupName == null) { 432 | groupName = ""; 433 | } 434 | List groupMembers = ns.getList("member"); 435 | if (groupMembers == null) { 436 | groupMembers = new ArrayList(); 437 | } 438 | String groupAvatar = ns.getString("avatar"); 439 | if (groupAvatar == null) { 440 | groupAvatar = ""; 441 | } 442 | byte[] newGroupId = ts.updateGroup(groupId, groupName, groupMembers, groupAvatar); 443 | if (groupId.length != newGroupId.length) { 444 | System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" …"); 445 | } 446 | } catch (IOException e) { 447 | handleIOException(e); 448 | return 3; 449 | } 450 | 451 | /**catch (AttachmentInvalidException e) { 452 | System.err.println("Failed to add avatar attachment for group\": " + e.getMessage()); 453 | System.err.println("Aborting sending."); 454 | return 1; 455 | } catch (GroupNotFoundException e) { 456 | handleGroupNotFoundException(e); 457 | return 1; 458 | } catch (NotAGroupMemberException e) { 459 | handleNotAGroupMemberException(e); 460 | return 1; 461 | **/ 462 | catch (EncapsulatedExceptions e) { 463 | handleEncapsulatedExceptions(e); 464 | return 3; 465 | } 466 | catch (Exception e) { 467 | e.printStackTrace(); 468 | return 3; 469 | } 470 | 471 | break; 472 | case "listGroups": 473 | 474 | if (!m.isRegistered()) { 475 | System.err.println("User is not registered."); 476 | return 1; 477 | } 478 | 479 | List groups = m.getGroups(); 480 | boolean detailed = ns.getBoolean("detailed"); 481 | 482 | for (GroupInfo group : groups) { 483 | printGroup(group, detailed); 484 | } 485 | break; 486 | case "listIdentities": 487 | 488 | if (!m.isRegistered()) { 489 | System.err.println("User is not registered."); 490 | return 1; 491 | } 492 | if (ns.get("number") == null) { 493 | for (Map.Entry> keys : m.getIdentities().entrySet()) { 494 | for (JsonIdentityKeyStore.Identity id : keys.getValue()) { 495 | printIdentityFingerprint(m, keys.getKey(), id); 496 | } 497 | } 498 | } else { 499 | String number = ns.getString("number"); 500 | for (JsonIdentityKeyStore.Identity id : m.getIdentities(number)) { 501 | printIdentityFingerprint(m, number, id); 502 | } 503 | } 504 | break; 505 | case "trust": 506 | 507 | if (!m.isRegistered()) { 508 | System.err.println("User is not registered."); 509 | return 1; 510 | } 511 | String number = ns.getString("number"); 512 | if (ns.getBoolean("trust_all_known_keys")) { 513 | boolean res = m.trustIdentityAllKeys(number); 514 | if (!res) { 515 | System.err.println("Failed to set the trust for this number, make sure the number is correct."); 516 | return 1; 517 | } 518 | } else { 519 | String fingerprint = ns.getString("verified_fingerprint"); 520 | if (fingerprint != null) { 521 | fingerprint = fingerprint.replaceAll(" ", ""); 522 | if (fingerprint.length() == 66) { 523 | byte[] fingerprintBytes; 524 | try { 525 | fingerprintBytes = Hex.toByteArray(fingerprint.toLowerCase(Locale.ROOT)); 526 | } catch (Exception e) { 527 | System.err.println("Failed to parse the fingerprint, make sure the fingerprint is a correctly encoded hex string without additional characters."); 528 | return 1; 529 | } 530 | boolean res = m.trustIdentityVerified(number, fingerprintBytes); 531 | if (!res) { 532 | System.err.println("Failed to set the trust for the fingerprint of this number, make sure the number and the fingerprint are correct."); 533 | return 1; 534 | } 535 | } else if (fingerprint.length() == 60) { 536 | boolean res = m.trustIdentityVerifiedSafetyNumber(number, fingerprint); 537 | if (!res) { 538 | System.err.println("Failed to set the trust for the safety number of this phone number, make sure the phone number and the safety number are correct."); 539 | return 1; 540 | } 541 | } else { 542 | System.err.println("Fingerprint has invalid format, either specify the old hex fingerprint or the new safety number"); 543 | return 1; 544 | } 545 | } else { 546 | System.err.println("You need to specify the fingerprint you have verified with -v FINGERPRINT"); 547 | return 1; 548 | } 549 | } 550 | break; 551 | 552 | } 553 | return 0; 554 | } finally { 555 | 556 | } 557 | } 558 | 559 | private static void printIdentityFingerprint(Manager m, String theirUsername, JsonIdentityKeyStore.Identity theirId) { 560 | String digits = formatSafetyNumber(m.computeSafetyNumber(theirUsername, theirId.getIdentityKey())); 561 | System.out.println(String.format("%s: %s Added: %s Fingerprint: %s Safety Number: %s", theirUsername, 562 | theirId.getTrustLevel(), theirId.getDateAdded(), Hex.toStringCondensed(theirId.getFingerprint()), digits)); 563 | } 564 | 565 | private static void printGroup(GroupInfo group, boolean detailed) { 566 | if (detailed) { 567 | System.out.println(String.format("Id: %s Name: %s Active: %s Members: %s", 568 | Base64.encodeBytes(group.groupId), group.name, group.active, group.members)); 569 | } else { 570 | System.out.println(String.format("Id: %s Name: %s Active: %s", Base64.encodeBytes(group.groupId), 571 | group.name, group.active)); 572 | } 573 | } 574 | 575 | private static String formatSafetyNumber(String digits) { 576 | final int partCount = 12; 577 | int partSize = digits.length() / partCount; 578 | StringBuilder f = new StringBuilder(digits.length() + partCount); 579 | for (int i = 0; i < partCount; i++) { 580 | f.append(digits.substring(i * partSize, (i * partSize) + partSize)).append(" "); 581 | } 582 | return f.toString(); 583 | } 584 | 585 | private static void handleGroupNotFoundException(GroupNotFoundException e) { 586 | System.err.println("Failed to send to group: " + e); 587 | System.err.println("Aborting sending."); 588 | } 589 | 590 | private static void handleNotAGroupMemberException(NotAGroupMemberException e) { 591 | System.err.println("Failed to send to group: " + e); 592 | System.err.println("Update the group on another device to readd the user to this group."); 593 | System.err.println("Aborting sending."); 594 | } 595 | 596 | 597 | 598 | private static byte[] decodeGroupId(String groupId) { 599 | try { 600 | return Base64.decode(groupId); 601 | } catch (IOException e) { 602 | System.err.println("Failed to decode groupId (must be base64) \"" + groupId + "\": " + e.getMessage()); 603 | System.err.println("Aborting sending."); 604 | System.exit(1); 605 | return null; 606 | } 607 | } 608 | 609 | private static Namespace parseArgs(String[] args) { 610 | ArgumentParser parser = ArgumentParsers.newFor("signal-cli") 611 | .build() 612 | .defaultHelp(true) 613 | .description("Commandline interface for Signal.") 614 | .version(Manager.PROJECT_NAME + " " + Manager.PROJECT_VERSION); 615 | 616 | parser.addArgument("-v", "--version") 617 | .help("Show package version.") 618 | .action(Arguments.version()); 619 | parser.addArgument("--config") 620 | .help("Set the path, where to store the config (Default: $HOME/.config/signal)."); 621 | 622 | MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup(); 623 | mut.addArgument("-u", "--username") 624 | .help("Specify your phone number, that will be used for verification."); 625 | mut.addArgument("--dbus") 626 | .help("Make request via user dbus.") 627 | .action(Arguments.storeTrue()); 628 | mut.addArgument("--dbus-system") 629 | .help("Make request via system dbus.") 630 | .action(Arguments.storeTrue()); 631 | 632 | Subparsers subparsers = parser.addSubparsers() 633 | .title("subcommands") 634 | .dest("command") 635 | .description("valid subcommands") 636 | .help("additional help"); 637 | 638 | Subparser parserLink = subparsers.addParser("link"); 639 | parserLink.addArgument("-n", "--name") 640 | .help("Specify a name to describe this new device."); 641 | 642 | Subparser parserAddDevice = subparsers.addParser("addDevice"); 643 | parserAddDevice.addArgument("--uri") 644 | .required(true) 645 | .help("Specify the uri contained in the QR code shown by the new device."); 646 | 647 | Subparser parserDevices = subparsers.addParser("listDevices"); 648 | 649 | Subparser parserRemoveDevice = subparsers.addParser("removeDevice"); 650 | parserRemoveDevice.addArgument("-d", "--deviceId") 651 | .type(int.class) 652 | .required(true) 653 | .help("Specify the device you want to remove. Use listDevices to see the deviceIds."); 654 | 655 | Subparser parserRegister = subparsers.addParser("register"); 656 | parserRegister.addArgument("-v", "--voice") 657 | .help("The verification should be done over voice, not sms.") 658 | .action(Arguments.storeTrue()); 659 | 660 | Subparser parserUnregister = subparsers.addParser("unregister"); 661 | parserUnregister.help("Unregister the current device from the signal server."); 662 | 663 | Subparser parserUpdateAccount = subparsers.addParser("updateAccount"); 664 | parserUpdateAccount.help("Update the account attributes on the signal server."); 665 | 666 | Subparser parserSetPin = subparsers.addParser("setPin"); 667 | parserSetPin.addArgument("registrationLockPin") 668 | .help("The registration lock PIN, that will be required for new registrations (resets after 7 days of inactivity)"); 669 | 670 | Subparser parserRemovePin = subparsers.addParser("removePin"); 671 | 672 | Subparser parserVerify = subparsers.addParser("verify"); 673 | parserVerify.addArgument("verificationCode") 674 | .help("The verification code you received via sms or voice call."); 675 | parserVerify.addArgument("-p", "--pin") 676 | .help("The registration lock PIN, that was set by the user (Optional)"); 677 | 678 | Subparser parserSend = subparsers.addParser("send"); 679 | parserSend.addArgument("-g", "--group") 680 | .help("Specify the recipient group ID."); 681 | parserSend.addArgument("recipient") 682 | .help("Specify the recipients' phone number.") 683 | .nargs("*"); 684 | parserSend.addArgument("-m", "--message") 685 | .help("Specify the message, if missing standard input is used."); 686 | parserSend.addArgument("-a", "--attachment") 687 | .nargs("*") 688 | .help("Add file as attachment"); 689 | parserSend.addArgument("-e", "--endsession") 690 | .help("Clear session state and send end session message.") 691 | .action(Arguments.storeTrue()); 692 | 693 | Subparser parserLeaveGroup = subparsers.addParser("quitGroup"); 694 | parserLeaveGroup.addArgument("-g", "--group") 695 | .required(true) 696 | .help("Specify the recipient group ID."); 697 | 698 | Subparser parserUpdateGroup = subparsers.addParser("updateGroup"); 699 | parserUpdateGroup.addArgument("-g", "--group") 700 | .help("Specify the recipient group ID."); 701 | parserUpdateGroup.addArgument("-n", "--name") 702 | .help("Specify the new group name."); 703 | parserUpdateGroup.addArgument("-a", "--avatar") 704 | .help("Specify a new group avatar image file"); 705 | parserUpdateGroup.addArgument("-m", "--member") 706 | .nargs("*") 707 | .help("Specify one or more members to add to the group"); 708 | 709 | Subparser parserListGroups = subparsers.addParser("listGroups"); 710 | parserListGroups.addArgument("-d", "--detailed").action(Arguments.storeTrue()) 711 | .help("List members of each group"); 712 | parserListGroups.help("List group name and ids"); 713 | 714 | Subparser parserListIdentities = subparsers.addParser("listIdentities"); 715 | parserListIdentities.addArgument("-n", "--number") 716 | .help("Only show identity keys for the given phone number."); 717 | 718 | Subparser parserTrust = subparsers.addParser("trust"); 719 | parserTrust.addArgument("number") 720 | .help("Specify the phone number, for which to set the trust.") 721 | .required(true); 722 | MutuallyExclusiveGroup mutTrust = parserTrust.addMutuallyExclusiveGroup(); 723 | mutTrust.addArgument("-a", "--trust-all-known-keys") 724 | .help("Trust all known keys of this user, only use this for testing.") 725 | .action(Arguments.storeTrue()); 726 | mutTrust.addArgument("-v", "--verified-fingerprint") 727 | .help("Specify the fingerprint of the key, only use this option if you have verified the fingerprint."); 728 | 729 | Subparser parserReceive = subparsers.addParser("receive"); 730 | parserReceive.addArgument("-t", "--timeout") 731 | .type(double.class) 732 | .help("Number of seconds to wait for new messages (negative values disable timeout)"); 733 | parserReceive.addArgument("--ignore-attachments") 734 | .help("Don’t download attachments of received messages.") 735 | .action(Arguments.storeTrue()); 736 | parserReceive.addArgument("--json") 737 | .help("Output received messages in json format, one json object per line.") 738 | .action(Arguments.storeTrue()); 739 | 740 | Subparser parserDaemon = subparsers.addParser("daemon"); 741 | parserDaemon.addArgument("--system") 742 | .action(Arguments.storeTrue()) 743 | .help("Use DBus system bus instead of user bus."); 744 | parserDaemon.addArgument("--ignore-attachments") 745 | .help("Don’t download attachments of received messages.") 746 | .action(Arguments.storeTrue()); 747 | parserDaemon.addArgument("--json") 748 | .help("Output received messages in json format, one json object per line.") 749 | .action(Arguments.storeTrue()); 750 | 751 | try { 752 | Namespace ns = parser.parseArgs(args); 753 | if ("link".equals(ns.getString("command"))) { 754 | if (ns.getString("username") != null) { 755 | parser.printUsage(); 756 | System.err.println("You cannot specify a username (phone number) when linking"); 757 | System.exit(2); 758 | } 759 | } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) { 760 | if (ns.getString("username") == null) { 761 | parser.printUsage(); 762 | System.err.println("You need to specify a username (phone number)"); 763 | System.exit(2); 764 | } 765 | if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"))) { 766 | System.err.println("Invalid username (phone number), make sure you include the country code."); 767 | System.exit(2); 768 | } 769 | } 770 | if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) { 771 | System.err.println("You cannot specify recipients by phone number and groups a the same time"); 772 | System.exit(2); 773 | } 774 | return ns; 775 | } catch (ArgumentParserException e) { 776 | parser.handleError(e); 777 | return null; 778 | } 779 | } 780 | 781 | private static void handleAssertionError(AssertionError e) { 782 | System.err.println("Failed to send/receive message (Assertion): " + e.getMessage()); 783 | e.printStackTrace(); 784 | System.err.println("If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); 785 | } 786 | 787 | private static void handleEncapsulatedExceptions(EncapsulatedExceptions e) { 788 | System.err.println("Failed to send (some) messages:"); 789 | for (NetworkFailureException n : e.getNetworkExceptions()) { 790 | System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage()); 791 | } 792 | for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) { 793 | System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage()); 794 | } 795 | for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) { 796 | System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage()); 797 | } 798 | } 799 | 800 | private static void handleIOException(IOException e) { 801 | System.err.println("Failed to send message: " + e.getMessage()); 802 | } 803 | 804 | private static String readAll(InputStream in) throws IOException { 805 | StringWriter output = new StringWriter(); 806 | byte[] buffer = new byte[4096]; 807 | long count = 0; 808 | int n; 809 | while (-1 != (n = System.in.read(buffer))) { 810 | output.write(new String(buffer, 0, n, Charset.defaultCharset())); 811 | count += n; 812 | } 813 | return output.toString(); 814 | } 815 | 816 | private static class ReceiveMessageHandler implements Manager.ReceiveMessageHandler { 817 | final Manager m; 818 | 819 | public ReceiveMessageHandler(Manager m) { 820 | this.m = m; 821 | } 822 | 823 | @Override 824 | public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) { 825 | SignalServiceAddress source = envelope.getSourceAddress(); 826 | ContactInfo sourceContact = m.getContact(source.getNumber()); 827 | System.out.println(String.format("Envelope from: %s (device: %d)", (sourceContact == null ? "" : "“" + sourceContact.name + "” ") + source.getNumber(), envelope.getSourceDevice())); 828 | if (source.getRelay().isPresent()) { 829 | System.out.println("Relayed by: " + source.getRelay().get()); 830 | } 831 | System.out.println("Timestamp: " + formatTimestamp(envelope.getTimestamp())); 832 | 833 | if (envelope.isReceipt()) { 834 | System.out.println("Got receipt."); 835 | } else if (envelope.isSignalMessage() | envelope.isPreKeySignalMessage()) { 836 | if (exception != null) { 837 | if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) { 838 | org.whispersystems.libsignal.UntrustedIdentityException e = (org.whispersystems.libsignal.UntrustedIdentityException) exception; 839 | System.out.println("The user’s key is untrusted, either the user has reinstalled Signal or a third party sent this message."); 840 | System.out.println("Use 'signal-cli -u " + m.getUsername() + " listIdentities -n " + e.getName() + "', verify the key and run 'signal-cli -u " + m.getUsername() + " trust -v \"FINGER_PRINT\" " + e.getName() + "' to mark it as trusted"); 841 | System.out.println("If you don't care about security, use 'signal-cli -u " + m.getUsername() + " trust -a " + e.getName() + "' to trust it without verification"); 842 | } else { 843 | System.out.println("Exception: " + exception.getMessage() + " (" + exception.getClass().getSimpleName() + ")"); 844 | } 845 | } 846 | if (content == null) { 847 | System.out.println("Failed to decrypt message."); 848 | } else { 849 | if (content.getDataMessage().isPresent()) { 850 | SignalServiceDataMessage message = content.getDataMessage().get(); 851 | handleSignalServiceDataMessage(message); 852 | } 853 | if (content.getSyncMessage().isPresent()) { 854 | System.out.println("Received a sync message"); 855 | SignalServiceSyncMessage syncMessage = content.getSyncMessage().get(); 856 | 857 | if (syncMessage.getContacts().isPresent()) { 858 | final ContactsMessage contactsMessage = syncMessage.getContacts().get(); 859 | if (contactsMessage.isComplete()) { 860 | System.out.println("Received complete sync contacts"); 861 | } else { 862 | System.out.println("Received sync contacts"); 863 | } 864 | printAttachment(contactsMessage.getContactsStream()); 865 | } 866 | if (syncMessage.getGroups().isPresent()) { 867 | System.out.println("Received sync groups"); 868 | printAttachment(syncMessage.getGroups().get()); 869 | } 870 | if (syncMessage.getRead().isPresent()) { 871 | System.out.println("Received sync read messages list"); 872 | for (ReadMessage rm : syncMessage.getRead().get()) { 873 | ContactInfo fromContact = m.getContact(rm.getSender()); 874 | System.out.println("From: " + (fromContact == null ? "" : "“" + fromContact.name + "” ") + rm.getSender() + " Message timestamp: " + formatTimestamp(rm.getTimestamp())); 875 | } 876 | } 877 | if (syncMessage.getRequest().isPresent()) { 878 | System.out.println("Received sync request"); 879 | if (syncMessage.getRequest().get().isContactsRequest()) { 880 | System.out.println(" - contacts request"); 881 | } 882 | if (syncMessage.getRequest().get().isGroupsRequest()) { 883 | System.out.println(" - groups request"); 884 | } 885 | } 886 | if (syncMessage.getSent().isPresent()) { 887 | System.out.println("Received sync sent message"); 888 | final SentTranscriptMessage sentTranscriptMessage = syncMessage.getSent().get(); 889 | String to; 890 | if (sentTranscriptMessage.getDestination().isPresent()) { 891 | String dest = sentTranscriptMessage.getDestination().get(); 892 | ContactInfo destContact = m.getContact(dest); 893 | to = (destContact == null ? "" : "“" + destContact.name + "” ") + dest; 894 | } else { 895 | to = "Unknown"; 896 | } 897 | System.out.println("To: " + to + " , Message timestamp: " + formatTimestamp(sentTranscriptMessage.getTimestamp())); 898 | if (sentTranscriptMessage.getExpirationStartTimestamp() > 0) { 899 | System.out.println("Expiration started at: " + formatTimestamp(sentTranscriptMessage.getExpirationStartTimestamp())); 900 | } 901 | SignalServiceDataMessage message = sentTranscriptMessage.getMessage(); 902 | handleSignalServiceDataMessage(message); 903 | } 904 | if (syncMessage.getBlockedList().isPresent()) { 905 | System.out.println("Received sync message with block list"); 906 | System.out.println("Blocked numbers:"); 907 | final BlockedListMessage blockedList = syncMessage.getBlockedList().get(); 908 | for (String number : blockedList.getNumbers()) { 909 | System.out.println(" - " + number); 910 | } 911 | } 912 | if (syncMessage.getVerified().isPresent()) { 913 | System.out.println("Received sync message with verified identities:"); 914 | final VerifiedMessage verifiedMessage = syncMessage.getVerified().get(); 915 | System.out.println(" - " + verifiedMessage.getDestination() + ": " + verifiedMessage.getVerified()); 916 | String safetyNumber = formatSafetyNumber(m.computeSafetyNumber(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey())); 917 | System.out.println(" " + safetyNumber); 918 | } 919 | if (syncMessage.getConfiguration().isPresent()) { 920 | System.out.println("Received sync message with configuration:"); 921 | final ConfigurationMessage configurationMessage = syncMessage.getConfiguration().get(); 922 | if (configurationMessage.getReadReceipts().isPresent()) { 923 | System.out.println(" - Read receipts: " + (configurationMessage.getReadReceipts().get() ? "enabled" : "disabled")); 924 | } 925 | } 926 | } 927 | if (content.getCallMessage().isPresent()) { 928 | System.out.println("Received a call message"); 929 | SignalServiceCallMessage callMessage = content.getCallMessage().get(); 930 | if (callMessage.getAnswerMessage().isPresent()) { 931 | AnswerMessage answerMessage = callMessage.getAnswerMessage().get(); 932 | System.out.println("Answer message: " + answerMessage.getId() + ": " + answerMessage.getDescription()); 933 | } 934 | if (callMessage.getBusyMessage().isPresent()) { 935 | BusyMessage busyMessage = callMessage.getBusyMessage().get(); 936 | System.out.println("Busy message: " + busyMessage.getId()); 937 | } 938 | if (callMessage.getHangupMessage().isPresent()) { 939 | HangupMessage hangupMessage = callMessage.getHangupMessage().get(); 940 | System.out.println("Hangup message: " + hangupMessage.getId()); 941 | } 942 | if (callMessage.getIceUpdateMessages().isPresent()) { 943 | List iceUpdateMessages = callMessage.getIceUpdateMessages().get(); 944 | for (IceUpdateMessage iceUpdateMessage : iceUpdateMessages) { 945 | System.out.println("Ice update message: " + iceUpdateMessage.getId() + ", sdp: " + iceUpdateMessage.getSdp()); 946 | } 947 | } 948 | if (callMessage.getOfferMessage().isPresent()) { 949 | OfferMessage offerMessage = callMessage.getOfferMessage().get(); 950 | System.out.println("Offer message: " + offerMessage.getId() + ": " + offerMessage.getDescription()); 951 | } 952 | } 953 | if (content.getReceiptMessage().isPresent()) { 954 | System.out.println("Received a receipt message"); 955 | SignalServiceReceiptMessage receiptMessage = content.getReceiptMessage().get(); 956 | System.out.println(" - When: " + formatTimestamp(receiptMessage.getWhen())); 957 | if (receiptMessage.isDeliveryReceipt()) { 958 | System.out.println(" - Is delivery receipt"); 959 | } 960 | if (receiptMessage.isReadReceipt()) { 961 | System.out.println(" - Is read receipt"); 962 | } 963 | System.out.println(" - Timestamps:"); 964 | for (long timestamp : receiptMessage.getTimestamps()) { 965 | System.out.println(" " + formatTimestamp(timestamp)); 966 | } 967 | } 968 | } 969 | } else { 970 | System.out.println("Unknown message received."); 971 | } 972 | System.out.println(); 973 | } 974 | 975 | private void handleSignalServiceDataMessage(SignalServiceDataMessage message) { 976 | System.out.println("Message timestamp: " + formatTimestamp(message.getTimestamp())); 977 | 978 | if (message.getBody().isPresent()) { 979 | System.out.println("Body: " + message.getBody().get()); 980 | } 981 | if (message.getGroupInfo().isPresent()) { 982 | SignalServiceGroup groupInfo = message.getGroupInfo().get(); 983 | System.out.println("Group info:"); 984 | System.out.println(" Id: " + Base64.encodeBytes(groupInfo.getGroupId())); 985 | if (groupInfo.getType() == SignalServiceGroup.Type.UPDATE && groupInfo.getName().isPresent()) { 986 | System.out.println(" Name: " + groupInfo.getName().get()); 987 | } else { 988 | GroupInfo group = m.getGroup(groupInfo.getGroupId()); 989 | if (group != null) { 990 | System.out.println(" Name: " + group.name); 991 | } else { 992 | System.out.println(" Name: "); 993 | } 994 | } 995 | System.out.println(" Type: " + groupInfo.getType()); 996 | if (groupInfo.getMembers().isPresent()) { 997 | for (String member : groupInfo.getMembers().get()) { 998 | System.out.println(" Member: " + member); 999 | } 1000 | } 1001 | if (groupInfo.getAvatar().isPresent()) { 1002 | System.out.println(" Avatar:"); 1003 | printAttachment(groupInfo.getAvatar().get()); 1004 | } 1005 | } 1006 | if (message.isEndSession()) { 1007 | System.out.println("Is end session"); 1008 | } 1009 | if (message.isExpirationUpdate()) { 1010 | System.out.println("Is Expiration update: " + message.isExpirationUpdate()); 1011 | } 1012 | if (message.getExpiresInSeconds() > 0) { 1013 | System.out.println("Expires in: " + message.getExpiresInSeconds() + " seconds"); 1014 | } 1015 | if (message.isProfileKeyUpdate() && message.getProfileKey().isPresent()) { 1016 | System.out.println("Profile key update, key length:" + message.getProfileKey().get().length); 1017 | } 1018 | 1019 | if (message.getQuote().isPresent()) { 1020 | SignalServiceDataMessage.Quote quote = message.getQuote().get(); 1021 | System.out.println("Quote: (" + quote.getId() + ")"); 1022 | System.out.println(" Author: " + quote.getAuthor().getNumber()); 1023 | System.out.println(" Text: " + quote.getText()); 1024 | if (quote.getAttachments().size() > 0) { 1025 | System.out.println(" Attachments: "); 1026 | for (SignalServiceDataMessage.Quote.QuotedAttachment attachment : quote.getAttachments()) { 1027 | System.out.println(" Filename: " + attachment.getFileName()); 1028 | System.out.println(" Type: " + attachment.getContentType()); 1029 | System.out.println(" Thumbnail:"); 1030 | printAttachment(attachment.getThumbnail()); 1031 | } 1032 | } 1033 | } 1034 | 1035 | if (message.getAttachments().isPresent()) { 1036 | System.out.println("Attachments: "); 1037 | for (SignalServiceAttachment attachment : message.getAttachments().get()) { 1038 | printAttachment(attachment); 1039 | } 1040 | } 1041 | } 1042 | 1043 | private void printAttachment(SignalServiceAttachment attachment) { 1044 | System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")"); 1045 | if (attachment.isPointer()) { 1046 | final SignalServiceAttachmentPointer pointer = attachment.asPointer(); 1047 | System.out.println(" Id: " + pointer.getId() + " Key length: " + pointer.getKey().length + (pointer.getRelay().isPresent() ? " Relay: " + pointer.getRelay().get() : "")); 1048 | System.out.println(" Filename: " + (pointer.getFileName().isPresent() ? pointer.getFileName().get() : "-")); 1049 | System.out.println(" Size: " + (pointer.getSize().isPresent() ? pointer.getSize().get() + " bytes" : "") + (pointer.getPreview().isPresent() ? " (Preview is available: " + pointer.getPreview().get().length + " bytes)" : "")); 1050 | System.out.println(" Voice note: " + (pointer.getVoiceNote() ? "yes" : "no")); 1051 | System.out.println(" Dimensions: " + pointer.getWidth() + "x" + pointer.getHeight()); 1052 | File file = m.getAttachmentFile(pointer.getId()); 1053 | if (file.exists()) { 1054 | System.out.println(" Stored plaintext in: " + file); 1055 | } 1056 | } 1057 | } 1058 | } 1059 | 1060 | 1061 | 1062 | private static class JsonReceiveMessageHandler implements Manager.ReceiveMessageHandler { 1063 | final Manager m; 1064 | final ObjectMapper jsonProcessor; 1065 | 1066 | public JsonReceiveMessageHandler(Manager m) { 1067 | this.m = m; 1068 | this.jsonProcessor = new ObjectMapper(); 1069 | jsonProcessor.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // disable autodetect 1070 | jsonProcessor.enable(SerializationFeature.WRITE_NULL_MAP_VALUES); 1071 | jsonProcessor.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 1072 | jsonProcessor.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); 1073 | } 1074 | 1075 | @Override 1076 | public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) { 1077 | ObjectNode result = jsonProcessor.createObjectNode(); 1078 | if (exception != null) { 1079 | result.putPOJO("error", new JsonError(exception)); 1080 | } 1081 | if (envelope != null) { 1082 | result.putPOJO("envelope", new JsonMessageEnvelope(envelope, content)); 1083 | } 1084 | try { 1085 | jsonProcessor.writeValue(System.out, result); 1086 | System.out.println(); 1087 | } catch (IOException e) { 1088 | e.printStackTrace(); 1089 | } 1090 | } 1091 | } 1092 | 1093 | private static String formatTimestamp(long timestamp) { 1094 | Date date = new Date(timestamp); 1095 | final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset 1096 | df.setTimeZone(tzUTC); 1097 | return timestamp + " (" + df.format(date) + ")"; 1098 | } 1099 | } 1100 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/NotAGroupMemberException.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.internal.util.Base64; 4 | 5 | public class NotAGroupMemberException extends Exception { 6 | 7 | public NotAGroupMemberException(String message) { 8 | super(message); 9 | } 10 | 11 | public NotAGroupMemberException(byte[] groupId, String groupName) { 12 | super("User is not a member in group: " + groupName + " (" + Base64.encodeBytes(groupId) + ")"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/TrustLevel.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage; 4 | 5 | public enum TrustLevel { 6 | UNTRUSTED, 7 | TRUSTED_UNVERIFIED, 8 | TRUSTED_VERIFIED; 9 | 10 | private static TrustLevel[] cachedValues = null; 11 | 12 | public static TrustLevel fromInt(int i) { 13 | if (TrustLevel.cachedValues == null) { 14 | TrustLevel.cachedValues = TrustLevel.values(); 15 | } 16 | return TrustLevel.cachedValues[i]; 17 | } 18 | 19 | public static TrustLevel fromVerifiedState(VerifiedMessage.VerifiedState verifiedState) { 20 | switch (verifiedState) { 21 | case DEFAULT: 22 | return TRUSTED_UNVERIFIED; 23 | case UNVERIFIED: 24 | return UNTRUSTED; 25 | case VERIFIED: 26 | return TRUSTED_VERIFIED; 27 | } 28 | throw new RuntimeException("Unknown verified state: " + verifiedState); 29 | } 30 | 31 | public VerifiedMessage.VerifiedState toVerifiedState() { 32 | switch (this) { 33 | case TRUSTED_UNVERIFIED: 34 | return VerifiedMessage.VerifiedState.DEFAULT; 35 | case UNTRUSTED: 36 | return VerifiedMessage.VerifiedState.UNVERIFIED; 37 | case TRUSTED_VERIFIED: 38 | return VerifiedMessage.VerifiedState.VERIFIED; 39 | } 40 | throw new RuntimeException("Unknown verified state: " + this); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/UserAlreadyExists.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | public class UserAlreadyExists extends Exception { 4 | private String username; 5 | private String fileName; 6 | 7 | public UserAlreadyExists(String username, String fileName) { 8 | this.username = username; 9 | this.fileName = fileName; 10 | } 11 | 12 | public String getUsername() { 13 | return username; 14 | } 15 | 16 | public String getFileName() { 17 | return fileName; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/WhisperTrustStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal; 2 | 3 | import org.whispersystems.signalservice.api.push.TrustStore; 4 | 5 | import java.io.InputStream; 6 | 7 | class WhisperTrustStore implements TrustStore { 8 | 9 | @Override 10 | public InputStream getKeyStoreInputStream() { 11 | return WhisperTrustStore.class.getResourceAsStream("whisper.store"); 12 | } 13 | 14 | @Override 15 | public String getKeyStorePassword() { 16 | return "whisper"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/contacts/ContactInfo.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.contacts; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public class ContactInfo { 6 | @JsonProperty 7 | public String name; 8 | 9 | @JsonProperty 10 | public String number; 11 | 12 | @JsonProperty 13 | public String color; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/contacts/JsonContactsStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.contacts; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.core.JsonGenerator; 5 | import com.fasterxml.jackson.core.JsonParser; 6 | import com.fasterxml.jackson.databind.*; 7 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 8 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 9 | 10 | import java.io.IOException; 11 | import java.util.ArrayList; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class JsonContactsStore { 17 | @JsonProperty("contacts") 18 | @JsonSerialize(using = JsonContactsStore.MapToListSerializer.class) 19 | @JsonDeserialize(using = ContactsDeserializer.class) 20 | private Map contacts = new HashMap<>(); 21 | 22 | private static final ObjectMapper jsonProcessor = new ObjectMapper(); 23 | 24 | public void updateContact(ContactInfo contact) { 25 | contacts.put(contact.number, contact); 26 | } 27 | 28 | public ContactInfo getContact(String number) { 29 | return contacts.get(number); 30 | } 31 | 32 | public List getContacts() { 33 | return new ArrayList<>(contacts.values()); 34 | } 35 | 36 | /** 37 | * Remove all contacts from the store 38 | */ 39 | public void clear() { 40 | contacts.clear(); 41 | } 42 | 43 | public static class MapToListSerializer extends JsonSerializer> { 44 | @Override 45 | public void serialize(final Map value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException { 46 | jgen.writeObject(value.values()); 47 | } 48 | } 49 | 50 | public static class ContactsDeserializer extends JsonDeserializer> { 51 | @Override 52 | public Map deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { 53 | Map contacts = new HashMap<>(); 54 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 55 | for (JsonNode n : node) { 56 | ContactInfo c = jsonProcessor.treeToValue(n, ContactInfo.class); 57 | contacts.put(c.number, c); 58 | } 59 | 60 | return contacts; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/groups/GroupInfo.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.groups; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | import java.util.Collection; 7 | import java.util.HashSet; 8 | import java.util.Set; 9 | 10 | public class GroupInfo { 11 | @JsonProperty 12 | public final byte[] groupId; 13 | 14 | @JsonProperty 15 | public String name; 16 | 17 | @JsonProperty 18 | public Set members = new HashSet<>(); 19 | 20 | private long avatarId; 21 | 22 | @JsonIgnore 23 | public long getAvatarId() { 24 | return avatarId; 25 | } 26 | 27 | @JsonProperty 28 | public boolean active; 29 | 30 | public GroupInfo(byte[] groupId) { 31 | this.groupId = groupId; 32 | } 33 | 34 | public GroupInfo(@JsonProperty("groupId") byte[] groupId, @JsonProperty("name") String name, @JsonProperty("members") Collection members, @JsonProperty("avatarId") long avatarId) { 35 | this.groupId = groupId; 36 | this.name = name; 37 | this.members.addAll(members); 38 | this.avatarId = avatarId; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/groups/JsonGroupStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.groups; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.core.JsonGenerator; 5 | import com.fasterxml.jackson.core.JsonParser; 6 | import com.fasterxml.jackson.databind.*; 7 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 8 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 9 | import org.whispersystems.signalservice.internal.util.Base64; 10 | 11 | import java.io.IOException; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | public class JsonGroupStore { 18 | @JsonProperty("groups") 19 | @JsonSerialize(using = JsonGroupStore.MapToListSerializer.class) 20 | @JsonDeserialize(using = JsonGroupStore.GroupsDeserializer.class) 21 | private Map groups = new HashMap<>(); 22 | 23 | public static List groupsWithLegacyAvatarId = new ArrayList<>(); 24 | 25 | private static final ObjectMapper jsonProcessor = new ObjectMapper(); 26 | 27 | public void updateGroup(GroupInfo group) { 28 | groups.put(Base64.encodeBytes(group.groupId), group); 29 | } 30 | 31 | public GroupInfo getGroup(byte[] groupId) { 32 | GroupInfo g = groups.get(Base64.encodeBytes(groupId)); 33 | return g; 34 | } 35 | 36 | public List getGroups() { 37 | return new ArrayList<>(groups.values()); 38 | } 39 | 40 | public static class MapToListSerializer extends JsonSerializer> { 41 | @Override 42 | public void serialize(final Map value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException { 43 | jgen.writeObject(value.values()); 44 | } 45 | } 46 | 47 | public static class GroupsDeserializer extends JsonDeserializer> { 48 | @Override 49 | public Map deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { 50 | Map groups = new HashMap<>(); 51 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 52 | for (JsonNode n : node) { 53 | GroupInfo g = jsonProcessor.treeToValue(n, GroupInfo.class); 54 | // Check if a legacy avatarId exists 55 | if (g.getAvatarId() != 0) { 56 | groupsWithLegacyAvatarId.add(g); 57 | } 58 | groups.put(Base64.encodeBytes(g.groupId), g); 59 | } 60 | 61 | return groups; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/protocol/JsonIdentityKeyStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.protocol; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.core.JsonParser; 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.*; 7 | import org.asamk.signal.TrustLevel; 8 | import org.whispersystems.libsignal.IdentityKey; 9 | import org.whispersystems.libsignal.IdentityKeyPair; 10 | import org.whispersystems.libsignal.InvalidKeyException; 11 | import org.whispersystems.libsignal.SignalProtocolAddress; 12 | import org.whispersystems.libsignal.state.IdentityKeyStore; 13 | import org.whispersystems.signalservice.internal.util.Base64; 14 | 15 | import java.io.IOException; 16 | import java.util.*; 17 | 18 | public class JsonIdentityKeyStore implements IdentityKeyStore { 19 | 20 | private final Map> trustedKeys = new HashMap<>(); 21 | 22 | private final IdentityKeyPair identityKeyPair; 23 | private final int localRegistrationId; 24 | 25 | 26 | public JsonIdentityKeyStore(IdentityKeyPair identityKeyPair, int localRegistrationId) { 27 | this.identityKeyPair = identityKeyPair; 28 | this.localRegistrationId = localRegistrationId; 29 | } 30 | 31 | @Override 32 | public IdentityKeyPair getIdentityKeyPair() { 33 | return identityKeyPair; 34 | } 35 | 36 | @Override 37 | public int getLocalRegistrationId() { 38 | return localRegistrationId; 39 | } 40 | 41 | @Override 42 | public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) { 43 | return saveIdentity(address.getName(), identityKey, TrustLevel.TRUSTED_UNVERIFIED, null); 44 | } 45 | 46 | /** 47 | * Adds or updates the given identityKey for the user name and sets the trustLevel and added timestamp. 48 | * 49 | * @param name User name, i.e. phone number 50 | * @param identityKey The user's public key 51 | * @param trustLevel 52 | * @param added Added timestamp, if null and the key is newly added, the current time is used. 53 | */ 54 | public boolean saveIdentity(String name, IdentityKey identityKey, TrustLevel trustLevel, Date added) { 55 | List identities = trustedKeys.get(name); 56 | if (identities == null) { 57 | identities = new ArrayList<>(); 58 | trustedKeys.put(name, identities); 59 | } else { 60 | for (Identity id : identities) { 61 | if (!id.identityKey.equals(identityKey)) 62 | continue; 63 | 64 | if (id.trustLevel.compareTo(trustLevel) < 0) { 65 | id.trustLevel = trustLevel; 66 | } 67 | if (added != null) { 68 | id.added = added; 69 | } 70 | return true; 71 | } 72 | } 73 | identities.add(new Identity(identityKey, trustLevel, added != null ? added : new Date())); 74 | return false; 75 | } 76 | 77 | @Override 78 | public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) { 79 | // TODO implement possibility for different handling of incoming/outgoing trust decisions 80 | List identities = trustedKeys.get(address.getName()); 81 | if (identities == null) { 82 | // Trust on first use 83 | return true; 84 | } 85 | 86 | for (Identity id : identities) { 87 | if (id.identityKey.equals(identityKey)) { 88 | return id.isTrusted(); 89 | } 90 | } 91 | 92 | return false; 93 | } 94 | 95 | public Map> getIdentities() { 96 | // TODO deep copy 97 | return trustedKeys; 98 | } 99 | 100 | public List getIdentities(String name) { 101 | // TODO deep copy 102 | return trustedKeys.get(name); 103 | } 104 | 105 | public static class JsonIdentityKeyStoreDeserializer extends JsonDeserializer { 106 | 107 | @Override 108 | public JsonIdentityKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { 109 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 110 | 111 | try { 112 | int localRegistrationId = node.get("registrationId").asInt(); 113 | IdentityKeyPair identityKeyPair = new IdentityKeyPair(Base64.decode(node.get("identityKey").asText())); 114 | 115 | 116 | JsonIdentityKeyStore keyStore = new JsonIdentityKeyStore(identityKeyPair, localRegistrationId); 117 | 118 | JsonNode trustedKeysNode = node.get("trustedKeys"); 119 | if (trustedKeysNode.isArray()) { 120 | for (JsonNode trustedKey : trustedKeysNode) { 121 | String trustedKeyName = trustedKey.get("name").asText(); 122 | try { 123 | IdentityKey id = new IdentityKey(Base64.decode(trustedKey.get("identityKey").asText()), 0); 124 | TrustLevel trustLevel = trustedKey.has("trustLevel") ? TrustLevel.fromInt(trustedKey.get("trustLevel").asInt()) : TrustLevel.TRUSTED_UNVERIFIED; 125 | Date added = trustedKey.has("addedTimestamp") ? new Date(trustedKey.get("addedTimestamp").asLong()) : new Date(); 126 | keyStore.saveIdentity(trustedKeyName, id, trustLevel, added); 127 | } catch (InvalidKeyException | IOException e) { 128 | System.out.println(String.format("Error while decoding key for: %s", trustedKeyName)); 129 | } 130 | } 131 | } 132 | 133 | return keyStore; 134 | } catch (InvalidKeyException e) { 135 | throw new IOException(e); 136 | } 137 | } 138 | } 139 | 140 | public static class JsonIdentityKeyStoreSerializer extends JsonSerializer { 141 | 142 | @Override 143 | public void serialize(JsonIdentityKeyStore jsonIdentityKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 144 | json.writeStartObject(); 145 | json.writeNumberField("registrationId", jsonIdentityKeyStore.getLocalRegistrationId()); 146 | json.writeStringField("identityKey", Base64.encodeBytes(jsonIdentityKeyStore.getIdentityKeyPair().serialize())); 147 | json.writeArrayFieldStart("trustedKeys"); 148 | for (Map.Entry> trustedKey : jsonIdentityKeyStore.trustedKeys.entrySet()) { 149 | for (Identity id : trustedKey.getValue()) { 150 | json.writeStartObject(); 151 | json.writeStringField("name", trustedKey.getKey()); 152 | json.writeStringField("identityKey", Base64.encodeBytes(id.identityKey.serialize())); 153 | json.writeNumberField("trustLevel", id.trustLevel.ordinal()); 154 | json.writeNumberField("addedTimestamp", id.added.getTime()); 155 | json.writeEndObject(); 156 | } 157 | } 158 | json.writeEndArray(); 159 | json.writeEndObject(); 160 | } 161 | } 162 | 163 | public class Identity { 164 | IdentityKey identityKey; 165 | TrustLevel trustLevel; 166 | Date added; 167 | 168 | public Identity(IdentityKey identityKey, TrustLevel trustLevel) { 169 | this.identityKey = identityKey; 170 | this.trustLevel = trustLevel; 171 | this.added = new Date(); 172 | } 173 | 174 | public Identity(IdentityKey identityKey, TrustLevel trustLevel, Date added) { 175 | this.identityKey = identityKey; 176 | this.trustLevel = trustLevel; 177 | this.added = added; 178 | } 179 | 180 | public boolean isTrusted() { 181 | return trustLevel == TrustLevel.TRUSTED_UNVERIFIED || 182 | trustLevel == TrustLevel.TRUSTED_VERIFIED; 183 | } 184 | 185 | public IdentityKey getIdentityKey() { 186 | return this.identityKey; 187 | } 188 | 189 | public TrustLevel getTrustLevel() { 190 | return this.trustLevel; 191 | } 192 | 193 | public Date getDateAdded() { 194 | return this.added; 195 | } 196 | 197 | public byte[] getFingerprint() { 198 | return identityKey.getPublicKey().serialize(); 199 | } 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/protocol/JsonPreKeyStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.protocol; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.core.JsonParser; 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.*; 7 | import org.whispersystems.libsignal.InvalidKeyIdException; 8 | import org.whispersystems.libsignal.state.PreKeyRecord; 9 | import org.whispersystems.libsignal.state.PreKeyStore; 10 | import org.whispersystems.signalservice.internal.util.Base64; 11 | 12 | import java.io.IOException; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | class JsonPreKeyStore implements PreKeyStore { 17 | 18 | private final Map store = new HashMap<>(); 19 | 20 | 21 | public JsonPreKeyStore() { 22 | 23 | } 24 | 25 | public void addPreKeys(Map preKeys) { 26 | store.putAll(preKeys); 27 | } 28 | 29 | @Override 30 | public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException { 31 | try { 32 | if (!store.containsKey(preKeyId)) { 33 | throw new InvalidKeyIdException("No such prekeyrecord!"); 34 | } 35 | 36 | return new PreKeyRecord(store.get(preKeyId)); 37 | } catch (IOException e) { 38 | throw new AssertionError(e); 39 | } 40 | } 41 | 42 | @Override 43 | public void storePreKey(int preKeyId, PreKeyRecord record) { 44 | store.put(preKeyId, record.serialize()); 45 | } 46 | 47 | @Override 48 | public boolean containsPreKey(int preKeyId) { 49 | return store.containsKey(preKeyId); 50 | } 51 | 52 | @Override 53 | public void removePreKey(int preKeyId) { 54 | store.remove(preKeyId); 55 | } 56 | 57 | public static class JsonPreKeyStoreDeserializer extends JsonDeserializer { 58 | 59 | @Override 60 | public JsonPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { 61 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 62 | 63 | 64 | Map preKeyMap = new HashMap<>(); 65 | if (node.isArray()) { 66 | for (JsonNode preKey : node) { 67 | Integer preKeyId = preKey.get("id").asInt(); 68 | try { 69 | preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText())); 70 | } catch (IOException e) { 71 | System.out.println(String.format("Error while decoding prekey for: %s", preKeyId)); 72 | } 73 | } 74 | } 75 | 76 | JsonPreKeyStore keyStore = new JsonPreKeyStore(); 77 | keyStore.addPreKeys(preKeyMap); 78 | 79 | return keyStore; 80 | 81 | } 82 | } 83 | 84 | public static class JsonPreKeyStoreSerializer extends JsonSerializer { 85 | 86 | @Override 87 | public void serialize(JsonPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 88 | json.writeStartArray(); 89 | for (Map.Entry preKey : jsonPreKeyStore.store.entrySet()) { 90 | json.writeStartObject(); 91 | json.writeNumberField("id", preKey.getKey()); 92 | json.writeStringField("record", Base64.encodeBytes(preKey.getValue())); 93 | json.writeEndObject(); 94 | } 95 | json.writeEndArray(); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/protocol/JsonSessionStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.protocol; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.core.JsonParser; 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.*; 7 | import org.whispersystems.libsignal.SignalProtocolAddress; 8 | import org.whispersystems.libsignal.state.SessionRecord; 9 | import org.whispersystems.libsignal.state.SessionStore; 10 | import org.whispersystems.signalservice.internal.util.Base64; 11 | 12 | import java.io.IOException; 13 | import java.util.*; 14 | 15 | class JsonSessionStore implements SessionStore { 16 | 17 | private final Map sessions = new HashMap<>(); 18 | 19 | public JsonSessionStore() { 20 | 21 | } 22 | 23 | public void addSessions(Map sessions) { 24 | this.sessions.putAll(sessions); 25 | } 26 | 27 | 28 | @Override 29 | public synchronized SessionRecord loadSession(SignalProtocolAddress remoteAddress) { 30 | try { 31 | if (containsSession(remoteAddress)) { 32 | return new SessionRecord(sessions.get(remoteAddress)); 33 | } else { 34 | return new SessionRecord(); 35 | } 36 | } catch (IOException e) { 37 | throw new AssertionError(e); 38 | } 39 | } 40 | 41 | @Override 42 | public synchronized List getSubDeviceSessions(String name) { 43 | List deviceIds = new LinkedList<>(); 44 | 45 | for (SignalProtocolAddress key : sessions.keySet()) { 46 | if (key.getName().equals(name) && 47 | key.getDeviceId() != 1) { 48 | deviceIds.add(key.getDeviceId()); 49 | } 50 | } 51 | 52 | return deviceIds; 53 | } 54 | 55 | @Override 56 | public synchronized void storeSession(SignalProtocolAddress address, SessionRecord record) { 57 | sessions.put(address, record.serialize()); 58 | } 59 | 60 | @Override 61 | public synchronized boolean containsSession(SignalProtocolAddress address) { 62 | return sessions.containsKey(address); 63 | } 64 | 65 | @Override 66 | public synchronized void deleteSession(SignalProtocolAddress address) { 67 | sessions.remove(address); 68 | } 69 | 70 | @Override 71 | public synchronized void deleteAllSessions(String name) { 72 | for (SignalProtocolAddress key : new ArrayList<>(sessions.keySet())) { 73 | if (key.getName().equals(name)) { 74 | sessions.remove(key); 75 | } 76 | } 77 | } 78 | 79 | public static class JsonSessionStoreDeserializer extends JsonDeserializer { 80 | 81 | @Override 82 | public JsonSessionStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { 83 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 84 | 85 | Map sessionMap = new HashMap<>(); 86 | if (node.isArray()) { 87 | for (JsonNode session : node) { 88 | String sessionName = session.get("name").asText(); 89 | try { 90 | sessionMap.put(new SignalProtocolAddress(sessionName, session.get("deviceId").asInt()), Base64.decode(session.get("record").asText())); 91 | } catch (IOException e) { 92 | System.out.println(String.format("Error while decoding session for: %s", sessionName)); 93 | } 94 | } 95 | } 96 | 97 | JsonSessionStore sessionStore = new JsonSessionStore(); 98 | sessionStore.addSessions(sessionMap); 99 | 100 | return sessionStore; 101 | 102 | } 103 | } 104 | 105 | public static class JsonPreKeyStoreSerializer extends JsonSerializer { 106 | 107 | @Override 108 | public void serialize(JsonSessionStore jsonSessionStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 109 | json.writeStartArray(); 110 | for (Map.Entry preKey : jsonSessionStore.sessions.entrySet()) { 111 | json.writeStartObject(); 112 | json.writeStringField("name", preKey.getKey().getName()); 113 | json.writeNumberField("deviceId", preKey.getKey().getDeviceId()); 114 | json.writeStringField("record", Base64.encodeBytes(preKey.getValue())); 115 | json.writeEndObject(); 116 | } 117 | json.writeEndArray(); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/protocol/JsonSignalProtocolStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.protocol; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 5 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 6 | import org.asamk.signal.TrustLevel; 7 | import org.whispersystems.libsignal.IdentityKey; 8 | import org.whispersystems.libsignal.IdentityKeyPair; 9 | import org.whispersystems.libsignal.InvalidKeyIdException; 10 | import org.whispersystems.libsignal.SignalProtocolAddress; 11 | import org.whispersystems.libsignal.state.PreKeyRecord; 12 | import org.whispersystems.libsignal.state.SessionRecord; 13 | import org.whispersystems.libsignal.state.SignalProtocolStore; 14 | import org.whispersystems.libsignal.state.SignedPreKeyRecord; 15 | 16 | import java.util.List; 17 | import java.util.Map; 18 | 19 | public class JsonSignalProtocolStore implements SignalProtocolStore { 20 | 21 | @JsonProperty("preKeys") 22 | @JsonDeserialize(using = JsonPreKeyStore.JsonPreKeyStoreDeserializer.class) 23 | @JsonSerialize(using = JsonPreKeyStore.JsonPreKeyStoreSerializer.class) 24 | protected JsonPreKeyStore preKeyStore; 25 | 26 | @JsonProperty("sessionStore") 27 | @JsonDeserialize(using = JsonSessionStore.JsonSessionStoreDeserializer.class) 28 | @JsonSerialize(using = JsonSessionStore.JsonPreKeyStoreSerializer.class) 29 | protected JsonSessionStore sessionStore; 30 | 31 | @JsonProperty("signedPreKeyStore") 32 | @JsonDeserialize(using = JsonSignedPreKeyStore.JsonSignedPreKeyStoreDeserializer.class) 33 | @JsonSerialize(using = JsonSignedPreKeyStore.JsonSignedPreKeyStoreSerializer.class) 34 | protected JsonSignedPreKeyStore signedPreKeyStore; 35 | 36 | @JsonProperty("identityKeyStore") 37 | @JsonDeserialize(using = JsonIdentityKeyStore.JsonIdentityKeyStoreDeserializer.class) 38 | @JsonSerialize(using = JsonIdentityKeyStore.JsonIdentityKeyStoreSerializer.class) 39 | protected JsonIdentityKeyStore identityKeyStore; 40 | 41 | public JsonSignalProtocolStore() { 42 | } 43 | 44 | public JsonSignalProtocolStore(JsonPreKeyStore preKeyStore, JsonSessionStore sessionStore, JsonSignedPreKeyStore signedPreKeyStore, JsonIdentityKeyStore identityKeyStore) { 45 | this.preKeyStore = preKeyStore; 46 | this.sessionStore = sessionStore; 47 | this.signedPreKeyStore = signedPreKeyStore; 48 | this.identityKeyStore = identityKeyStore; 49 | } 50 | 51 | public JsonSignalProtocolStore(IdentityKeyPair identityKeyPair, int registrationId) { 52 | preKeyStore = new JsonPreKeyStore(); 53 | sessionStore = new JsonSessionStore(); 54 | signedPreKeyStore = new JsonSignedPreKeyStore(); 55 | this.identityKeyStore = new JsonIdentityKeyStore(identityKeyPair, registrationId); 56 | } 57 | 58 | @Override 59 | public IdentityKeyPair getIdentityKeyPair() { 60 | return identityKeyStore.getIdentityKeyPair(); 61 | } 62 | 63 | @Override 64 | public int getLocalRegistrationId() { 65 | return identityKeyStore.getLocalRegistrationId(); 66 | } 67 | 68 | @Override 69 | public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) { 70 | return identityKeyStore.saveIdentity(address, identityKey); 71 | } 72 | 73 | public void saveIdentity(String name, IdentityKey identityKey, TrustLevel trustLevel) { 74 | identityKeyStore.saveIdentity(name, identityKey, trustLevel, null); 75 | } 76 | 77 | public Map> getIdentities() { 78 | return identityKeyStore.getIdentities(); 79 | } 80 | 81 | public List getIdentities(String name) { 82 | return identityKeyStore.getIdentities(name); 83 | } 84 | 85 | @Override 86 | public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) { 87 | return identityKeyStore.isTrustedIdentity(address, identityKey, direction); 88 | } 89 | 90 | @Override 91 | public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException { 92 | return preKeyStore.loadPreKey(preKeyId); 93 | } 94 | 95 | @Override 96 | public void storePreKey(int preKeyId, PreKeyRecord record) { 97 | preKeyStore.storePreKey(preKeyId, record); 98 | } 99 | 100 | @Override 101 | public boolean containsPreKey(int preKeyId) { 102 | return preKeyStore.containsPreKey(preKeyId); 103 | } 104 | 105 | @Override 106 | public void removePreKey(int preKeyId) { 107 | preKeyStore.removePreKey(preKeyId); 108 | } 109 | 110 | @Override 111 | public SessionRecord loadSession(SignalProtocolAddress address) { 112 | return sessionStore.loadSession(address); 113 | } 114 | 115 | @Override 116 | public List getSubDeviceSessions(String name) { 117 | return sessionStore.getSubDeviceSessions(name); 118 | } 119 | 120 | @Override 121 | public void storeSession(SignalProtocolAddress address, SessionRecord record) { 122 | sessionStore.storeSession(address, record); 123 | } 124 | 125 | @Override 126 | public boolean containsSession(SignalProtocolAddress address) { 127 | return sessionStore.containsSession(address); 128 | } 129 | 130 | @Override 131 | public void deleteSession(SignalProtocolAddress address) { 132 | sessionStore.deleteSession(address); 133 | } 134 | 135 | @Override 136 | public void deleteAllSessions(String name) { 137 | sessionStore.deleteAllSessions(name); 138 | } 139 | 140 | @Override 141 | public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException { 142 | return signedPreKeyStore.loadSignedPreKey(signedPreKeyId); 143 | } 144 | 145 | @Override 146 | public List loadSignedPreKeys() { 147 | return signedPreKeyStore.loadSignedPreKeys(); 148 | } 149 | 150 | @Override 151 | public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) { 152 | signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record); 153 | } 154 | 155 | @Override 156 | public boolean containsSignedPreKey(int signedPreKeyId) { 157 | return signedPreKeyStore.containsSignedPreKey(signedPreKeyId); 158 | } 159 | 160 | @Override 161 | public void removeSignedPreKey(int signedPreKeyId) { 162 | signedPreKeyStore.removeSignedPreKey(signedPreKeyId); 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/protocol/JsonSignedPreKeyStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.protocol; 2 | 3 | import com.fasterxml.jackson.core.JsonGenerator; 4 | import com.fasterxml.jackson.core.JsonParser; 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.*; 7 | import org.whispersystems.libsignal.InvalidKeyIdException; 8 | import org.whispersystems.libsignal.state.SignedPreKeyRecord; 9 | import org.whispersystems.libsignal.state.SignedPreKeyStore; 10 | import org.whispersystems.signalservice.internal.util.Base64; 11 | 12 | import java.io.IOException; 13 | import java.util.HashMap; 14 | import java.util.LinkedList; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | class JsonSignedPreKeyStore implements SignedPreKeyStore { 19 | 20 | private final Map store = new HashMap<>(); 21 | 22 | public JsonSignedPreKeyStore() { 23 | 24 | } 25 | 26 | 27 | public void addSignedPreKeys(Map preKeys) { 28 | store.putAll(preKeys); 29 | } 30 | 31 | @Override 32 | public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException { 33 | try { 34 | if (!store.containsKey(signedPreKeyId)) { 35 | throw new InvalidKeyIdException("No such signedprekeyrecord! " + signedPreKeyId); 36 | } 37 | 38 | return new SignedPreKeyRecord(store.get(signedPreKeyId)); 39 | } catch (IOException e) { 40 | throw new AssertionError(e); 41 | } 42 | } 43 | 44 | @Override 45 | public List loadSignedPreKeys() { 46 | try { 47 | List results = new LinkedList<>(); 48 | 49 | for (byte[] serialized : store.values()) { 50 | results.add(new SignedPreKeyRecord(serialized)); 51 | } 52 | 53 | return results; 54 | } catch (IOException e) { 55 | throw new AssertionError(e); 56 | } 57 | } 58 | 59 | @Override 60 | public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) { 61 | store.put(signedPreKeyId, record.serialize()); 62 | } 63 | 64 | @Override 65 | public boolean containsSignedPreKey(int signedPreKeyId) { 66 | return store.containsKey(signedPreKeyId); 67 | } 68 | 69 | @Override 70 | public void removeSignedPreKey(int signedPreKeyId) { 71 | store.remove(signedPreKeyId); 72 | } 73 | 74 | public static class JsonSignedPreKeyStoreDeserializer extends JsonDeserializer { 75 | 76 | @Override 77 | public JsonSignedPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { 78 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 79 | 80 | 81 | Map preKeyMap = new HashMap<>(); 82 | if (node.isArray()) { 83 | for (JsonNode preKey : node) { 84 | Integer preKeyId = preKey.get("id").asInt(); 85 | try { 86 | preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText())); 87 | } catch (IOException e) { 88 | System.out.println(String.format("Error while decoding prekey for: %s", preKeyId)); 89 | } 90 | } 91 | } 92 | 93 | JsonSignedPreKeyStore keyStore = new JsonSignedPreKeyStore(); 94 | keyStore.addSignedPreKeys(preKeyMap); 95 | 96 | return keyStore; 97 | 98 | } 99 | } 100 | 101 | public static class JsonSignedPreKeyStoreSerializer extends JsonSerializer { 102 | 103 | @Override 104 | public void serialize(JsonSignedPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 105 | json.writeStartArray(); 106 | for (Map.Entry signedPreKey : jsonPreKeyStore.store.entrySet()) { 107 | json.writeStartObject(); 108 | json.writeNumberField("id", signedPreKey.getKey()); 109 | json.writeStringField("record", Base64.encodeBytes(signedPreKey.getValue())); 110 | json.writeEndObject(); 111 | } 112 | json.writeEndArray(); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/threads/JsonThreadStore.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.threads; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import com.fasterxml.jackson.core.JsonGenerator; 5 | import com.fasterxml.jackson.core.JsonParser; 6 | import com.fasterxml.jackson.databind.*; 7 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 8 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 9 | 10 | import java.io.IOException; 11 | import java.util.ArrayList; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class JsonThreadStore { 17 | @JsonProperty("threads") 18 | @JsonSerialize(using = JsonThreadStore.MapToListSerializer.class) 19 | @JsonDeserialize(using = ThreadsDeserializer.class) 20 | private Map threads = new HashMap<>(); 21 | 22 | private static final ObjectMapper jsonProcessor = new ObjectMapper(); 23 | 24 | public void updateThread(ThreadInfo thread) { 25 | threads.put(thread.id, thread); 26 | } 27 | 28 | public ThreadInfo getThread(String id) { 29 | return threads.get(id); 30 | } 31 | 32 | public List getThreads() { 33 | return new ArrayList<>(threads.values()); 34 | } 35 | 36 | public static class MapToListSerializer extends JsonSerializer> { 37 | @Override 38 | public void serialize(final Map value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException { 39 | jgen.writeObject(value.values()); 40 | } 41 | } 42 | 43 | public static class ThreadsDeserializer extends JsonDeserializer> { 44 | @Override 45 | public Map deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { 46 | Map threads = new HashMap<>(); 47 | JsonNode node = jsonParser.getCodec().readTree(jsonParser); 48 | for (JsonNode n : node) { 49 | ThreadInfo t = jsonProcessor.treeToValue(n, ThreadInfo.class); 50 | threads.put(t.id, t); 51 | } 52 | 53 | return threads; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/storage/threads/ThreadInfo.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.storage.threads; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public class ThreadInfo { 6 | @JsonProperty 7 | public String id; 8 | 9 | @JsonProperty 10 | public int messageExpirationTime; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/util/Hex.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.util; 2 | 3 | public class Hex { 4 | 5 | private final static char[] HEX_DIGITS = { 6 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 7 | }; 8 | 9 | public static String toStringCondensed(byte[] bytes) { 10 | StringBuffer buf = new StringBuffer(); 11 | for (int i = 0; i < bytes.length; i++) { 12 | appendHexChar(buf, bytes[i]); 13 | } 14 | return buf.toString(); 15 | } 16 | 17 | private static void appendHexChar(StringBuffer buf, int b) { 18 | buf.append(HEX_DIGITS[(b >> 4) & 0xf]); 19 | buf.append(HEX_DIGITS[b & 0xf]); 20 | buf.append(" "); 21 | } 22 | 23 | public static byte[] toByteArray(String s) { 24 | int len = s.length(); 25 | byte[] data = new byte[len / 2]; 26 | for (int i = 0; i < len; i += 2) { 27 | data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); 28 | } 29 | return data; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/asamk/signal/util/Util.java: -------------------------------------------------------------------------------- 1 | package org.asamk.signal.util; 2 | 3 | import org.whispersystems.signalservice.internal.util.Base64; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.security.NoSuchAlgorithmException; 8 | import java.security.SecureRandom; 9 | 10 | public class Util { 11 | public static String getSecret(int size) { 12 | byte[] secret = getSecretBytes(size); 13 | return Base64.encodeBytes(secret); 14 | } 15 | 16 | public static byte[] getSecretBytes(int size) { 17 | byte[] secret = new byte[size]; 18 | getSecureRandom().nextBytes(secret); 19 | return secret; 20 | } 21 | 22 | private static SecureRandom getSecureRandom() { 23 | try { 24 | return SecureRandom.getInstance("SHA1PRNG"); 25 | } catch (NoSuchAlgorithmException e) { 26 | throw new AssertionError(e); 27 | } 28 | } 29 | 30 | public static File createTempFile() throws IOException { 31 | return File.createTempFile("signal_tmp_", ".tmp"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/resources/org/asamk/signal/whisper.store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guardianproject/signal-cli-android/d319e2feaf44dbb6a1c6a43d55a57f391e939ef4/src/main/resources/org/asamk/signal/whisper.store --------------------------------------------------------------------------------