pax_global_header00006660000000000000000000000064147450211530014514gustar00rootroot0000000000000052 comment=db846d5197288fc14c32694e77e613cbb1300ad8 go-sendxmpp-0.14.1/000077500000000000000000000000001474502115300140405ustar00rootroot00000000000000go-sendxmpp-0.14.1/.gitignore000066400000000000000000000004501474502115300160270ustar00rootroot00000000000000config.json .vscode # Binaries for programs and plugins *.exe *.dll *.so *.dylib # Test binary, build with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ go-sendxmpp-0.14.1/.gitlab-ci.yml000066400000000000000000000067011474502115300165000ustar00rootroot00000000000000# To contribute improvements to CI/CD templates, please follow the Development guide at: # https://docs.gitlab.com/ee/development/cicd/templates.html # This specific template is located at: # https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Go.gitlab-ci.yml image: golang:latest variables: # Please edit to your GitLab project REPO_NAME: salsa.debian.org/mdosch/go-sendxmpp # The problem is that to be able to use go get, one needs to put # the repository in the $GOPATH. So for example if your gitlab domain # is gitlab.com, and that your repository is namespace/project, and # the default GOPATH being /go, then you'd need to have your # repository in /go/src/gitlab.com/namespace/project # Thus, making a symbolic link corrects this. before_script: - mkdir -p $GOPATH/src/$(dirname $REPO_NAME) - ln -svf $CI_PROJECT_DIR $GOPATH/src/$REPO_NAME - cd $GOPATH/src/$REPO_NAME stages: - test - build - release format: # image: registry.gitlab.com/gitlab-org/gitlab-build-images:golangci-lint-alpine stage: test script: - go fmt $(go list ./... | grep -v /vendor/) - go vet $(go list ./... | grep -v /vendor/) - go test -race $(go list ./... | grep -v /vendor/) # Taken from https://gitlab.com/gitlab-org/gitlab/-/merge_requests/20404/diffs#diff-content-8071267ea32ba69f24a8bd50bcbddf972c295ce3 # Use default .golangci.yml file from the image if one is not present in the project root. #- '[ -e .golangci.yml ] || cp /golangci/.golangci.yml .' #- golangci-lint run #allow_failure: true artifacts: expire_in: 1 year compile: stage: build only: - tags before_script: - echo "deb https://deb.debian.org/debian/ bookworm-backports main" >> /etc/apt/sources.list - apt-get -qq update && apt-get -qq install -y upx-ucl script: - echo "${CI_JOB_ID}" > CI_JOB_ID.txt - env GOOS=linux GOARCH=amd64 go build -buildmode=pie -ldflags "-s -w -extldflags '-static'" -o $CI_PROJECT_DIR/linux-amd64/go-sendxmpp - upx $CI_PROJECT_DIR/linux-amd64/go-sendxmpp || true - env GOOS=linux GOARCH=arm64 go build -buildmode=pie -ldflags "-s -w -extldflags '-static'" -o $CI_PROJECT_DIR/linux-arm64/go-sendxmpp - upx $CI_PROJECT_DIR/linux-arm64/go-sendxmpp || true - env GOOS=windows GOARCH=amd64 go build -buildmode=pie -ldflags "-s -w -extldflags '-static'" -o $CI_PROJECT_DIR/win64/go-sendxmpp.exe - upx $CI_PROJECT_DIR/win64/go-sendxmpp.exe || true artifacts: paths: - linux-amd64/go-sendxmpp - linux-arm64/go-sendxmpp - win64/go-sendxmpp.exe - CI_JOB_ID.txt expire_in: 2 years release: stage: release image: registry.gitlab.com/gitlab-org/release-cli:latest only: - tags script: - | release-cli create --name "Release $CI_COMMIT_TAG" --tag-name $CI_COMMIT_TAG --description="`head -n $(expr "$(grep -nm2 "^## " CHANGELOG.md|awk '(NR>1) {print $1}'|cut -f1 -d:) - 2"|bc) CHANGELOG.md`" \ --assets-link "{\"name\":\"Linux amd64\",\"url\":\"https://salsa.debian.org/mdosch/go-sendxmpp/-/jobs/`cat CI_JOB_ID.txt`/artifacts/file/linux-amd64/go-sendxmpp\"}" \ --assets-link "{\"name\":\"Linux arm64\",\"url\":\"https://salsa.debian.org/mdosch/go-sendxmpp/-/jobs/`cat CI_JOB_ID.txt`/artifacts/file/linux-arm64/go-sendxmpp\"}" \ --assets-link "{\"name\":\"Windows amd64\",\"url\":\"https://salsa.debian.org/mdosch/go-sendxmpp/-/jobs/`cat CI_JOB_ID.txt`/artifacts/file/win64/go-sendxmpp.exe\"}" artifacts: expire_in: 2 years go-sendxmpp-0.14.1/CHANGELOG.md000066400000000000000000000235471474502115300156640ustar00rootroot00000000000000# Changelog ## [v0.14.1] 2024-01-24 ### Changed - Use prettier date format for error messages. - Update XEP-0474 to version 0.4.0 (requires go-xmpp >= 0.2.10). ## [v0.14.0] 2024-12-27 ### Added - Add `--fast-invalidate` to allow invalidating the FAST token. ### Changed - Don't create legacy Ox private key directory in `~/.local/share/go-sendxmpp/oxprivkeys`. - Delete legacy Ox private key directory if it's empty. - Show proper error if saved FAST mechanism isn't usable with current TLS version (requires go-xmpp >= 0.2.9). - Print debug output to stdout, not stderr (requires go-xmpp >= 0.2.9). - Show `RECV:` and `SEND:` prefix for debug output (requires go-xmpp >= 0.2.9). - Delete stored fast token if `--fast-invalidate` and `--fast-off` are set. - Show error when FAST creds are stored but non-FAST mechanism is requested. ## [v0.13.0] 2024-12-14 ### Added - Add `--anonymous` to support anonymous authentication (requires go-xmpp >= 0.2.8). - Add `XEP-0480: SASL Upgrade Tasks` support (requires go-xmpp >= 0.2.8). - Add support for `see-other-host` stream error (requires go-xmpp >= 0.2.8). ### Changed - Don't automatically try other auth mechanisms if FAST authentication fails. ## [v0.12.1] 2024-11-17 ### Changed - Print error instead of quitting if a message of type error is received. - Allow upload of multiple files. ### Added - Add flag `--suppress-root-warning` to suppress the warning when go-sendxmpp is used by the root user. ## [v0.12.0] 2024-11-03 ### Added - Add possibility to look up direct TLS connection endpoint via hostmeta2 (requires xmppsrv >= 0.3.3). - Add flag `--allow-plain` to allow PLAIN authentication (requires go-xmpp >= 0.2.5). ### Changed - Disable PLAIN authentication per default. - Disable PLAIN authentication after first use of a SCRAM auth mechanism (overrides `--allow-plain`) (requires go-xmpp >= 0.2.5). ## [v0.11.4] 2024-10-26 ### Changed - Fix bug in SCRAM-SHA-256-PLUS auth (via go-xmpp >= 0.2.4). ## [v0.11.3] 2024-10-25 ### Added - Add go-xmpp library version to `--version` output (requires go-xmpp >= 0.2.2). ### Changed - Fix XEP-0474: SASL SCRAM Downgrade Protection hash calculation bug (via go-xmpp >= 0.2.3). - [gocritic]: Improve code quality. ## [v0.11.2] 2024-09-17 ### Changed - Add Gopenpgp and Xmppsrv version to `--version` output (requires xmppsrv >= 0.3.2). - Improve selection between StartTLS and DirectTLS. ## [v0.11.1] 2024-07-11 ### Changed - Fix Ox encryption in interactive mode (do not add the same recipient key to the keyring over and over again). - Exit with error code if Ox encryption for one recipient fails. - Improved handling of perl sendxmpp config files. ## [v0.11.0] 2024-05-29 ### Changed - Move private Ox key into JID folder in ~/.local/share/go-sendxmpp. - Use `fmt.Errorf()` instead of `errors.New()` to create new error messages. ### Added - Add new parameter `--subject`. - Added flag `--fast-off` to disable XEP-0484: Fast Authentication Streamlining Tokens (requires go-xmpp >= 0.2.1). ## [v0.10.0] 2024-04-13 ### Changed - Fixed a race condition in receiving stanzas (requires go-xmpp >= v0.1.5). ### Added - Add support for SASL2 and BIND2 (via go-xmpp >= v0.2.0). - Add support for FAST authentication (via go-xmpp >= v0.2.0). - Add a warning when run by the user *root*. ## [v0.9.0] 2024-03-28 ### Changed - Properly close stream if `Ctrl+C` is pressed in interactive mode. - Properly close stream if `Ctrl+C` is pressed in listening mode. - Print OS, architecture and go version for flag `--version`. - Improve closing of connection (via go-xmpp v0.1.4). - Don't send stanzas that exceed the size limit provided by XEP-0478 (requires go-xmpp >= v0.1.4). - Fixed hanging forever in stream close if the server doesn't reply with a closing stream element (via go-xmpp >= v0.1.4). ### Added - New command line flag `ssdp-off` to disable XEP-0474: SASL SCRAM Downgrade Protection (requires go-xmpp >= v0.1.4). ## [v0.8.4] 2024-03-09 ### Changed - Properly handle lost connection. - Better compatibility with perl sendxmpp config files. - Improve file name for private Ox keys. - Improve fallback behavior if no SRV records are provided. - Remove 100ms sleep before closing the connection. This should be no more needed since go-xmpp commit 9684a8ff690f0d75e284f8845696c5057926d276. - Return an error if there is no answer to an IQ within 60s. - Check for errors after sending the auth message during SCRAM authentication (via go-xmpp v0.1.2). ## [v0.8.3] 2024-02-17 ### Changed - Use a human readable file name for private Ox keys. - Fix specifying a message via command line flag `-m`. ## [v0.8.2] 2024-01-19 ### Changed - Fix an issue in look up of SRV records (via xmppsrv v0.2.6). Thx mtp. ## [v0.8.1] 2024-01-16 ### Added - Add support for `tls-server-end-point` channel binding (via go-xmpp commit 3f0cbac30767faa562ad198ee69f36055f5924bc). - Add experimental support for SOCKS5 proxies using the `HTTP_PROXY` environment variable (requires go-xmpp commit 685570cbd85c31ea3b426bea34dd4af404aac8cf). ### Changed - http-upload: Improve error handling. ## [v0.8.0] 2024-01-09 ### Added - Add new parameter `--scram-mech-pinning`. ### Changed - Refuse to upload a file if upload slot doesn't provide https. - Use XEP-0474 instead of SCRAM mechanism pinning to prevent downgrade attacks (requires go-xmpp commit 39f5b80375b6f6f266df37b4a4adcbeb606ffec2). ## [v0.7.0] 2023-11-11 ### Added - Reply to XEP-0092 software version requests. - Add support for PLUS variants of SCRAM authentication mechanisms (requires go-xmpp commit 4c385a334c606e8bc387f0a3d4d84975802b3984). - Add pinning of last used authentication mechanism if a SCRAM mechanism was used. ### Changed - Print every stanza in a new line (requires go-xmpp commit 31c7eb6919b67b18e901dc45a8e5681040ea7f31). ## [v0.6.2] 2023-09-29 ### Changed - Properly close connection to server if ^C is pressed in interactive mode. - Replace invalid characters by UTF8 replacement char. - Add warning that there is no Ox support for messages of type headline. - Suppress warnings about reading from closed connection if go-sendxmpp closes the connection before exiting. - Remove unnecessary newlines after stanzas. - Fix segfault when authentication fails due to invalid username or password. ## Removed - Removed deprecated flag and config option `resource`. ## [v0.6.1] 2023-07-25 ### Changed - Properly close connection to server. ## [v0.6.0] 2023-07-02 ### Added - Add support for sending Out of Band Data (OOB). - Add SCRAM-SHA-1, SCRAM-SHA-256 and SCRAM-SHA512 support (via go-xmpp commit bef3e54). - Add support for messages of type headline. ### Changed - Print `--help` output to stdout instead of stderr. - Print sent stanzas when `--debug` is used (via go-xmpp commit 9129a110df1b). - Allow JIDs without localpart. - Use single quotes for attributes in stanzas created by github.com/beevik/etree (vial etree v1.1.4). - Fix SRV lookup when the domain has a CNAME (via xmppsrv v0.2.5). - Fall back to directTLS on port 5223 (instead of StartTLS on port 5222) if no SRV records are provided and `-t` is set. - Remove trailing newlines in interactive mode. ## [v0.5.6] 2022-11-11 ### Added - Add short option `-h` for http-upload. ### Changed - Fix Ox key generation. ## [v0.5.5] 2022-10-16 ### Changed - Improve interactive mode. ## [v0.5.4] 2022-09-30 ### Changed - Fix http-upload. ## [v0.5.3] 2022-09-29 ### Changed - Don't check for empty message when `--listen` is used. ## [v0.5.2] 2022-09-29 ### Added - Reply to `disco#info` queries. - Send `service-unavailable` errors for all other IQs of type `get` and `set`. - New config option and command line flag `alias` to uncouple MUC nickname/alias from resource. ### Changed - Ox: Improve error messages for failed key requests. - Ox: Do not encrypt empty messages. - Check for empty messages. - Always look up CNAME before doing SRV lookups (via xmppsrv v0.2.3). - Detect CNAME loops (max. 5 CNAMEs) (via xmppsrv >= v0.2.4). - Deprecate resource config option and command line flag. - Improve error handling in XML parsing. - Don't connect to the XMPP server if the message is empty. ## [v0.5.1] 2022-05-22 ### Changed - Improve listening mode for groupchats. - Fix nickname in MUCs if not manually set. ## [v0.5.0] 2022-05-05 ### Added - Add possibility to delete existing OpenPGP for XMPP nodes. ### Changed - Ox: Improve rpad generation. - Rework receiving of stanzas. - Ox: Improve private key import. ## [v0.4.0] 2022-04-30 ### Added - Experimental support for Ox (OpenPGP for XMPP) encryption. ### Changed - Shorter random ID for resource. - Changed to the more flexible "github.com/beevik/etree" instead of encoding/xml for creating and interpreting stanzas. - Changed to use message stamp, if provided, for printing the time stamp of received messages. ## [v0.3.0] 2022-03-21 ### Added - Added support for joining password protected MUCs. ### Changed - Removed invalid code points from input. - Fixed crash when reading a config with wrong syntax. - Fixed crash when a non-existing or non-readable config was supplied by `-f`. - Changed config file location from `~/.config/go-sendxmpp/sendxmpprc` to `~/.config/go-sendxmpp/config`. - Fixed blocking of go-sendxmpp if an IQ reply of type "error" is received (via go-xmpp v0.0.0-20220319135856-e773596ea0b0). ## [v0.2.0] 2022-02-12 ### Added - Added listening function. - Added flag to configure connection timeout. - Added flag to configure minimum TLS version. - Added flag to show version. ### Removed - Removed deprecated option `-x`. ## [v0.1.3] 2022-01-29 ### Changed - Rename files to use a limited character set (alpha numerical and some extra characters) file name before uploading. Workaround for https://github.com/mattn/go-xmpp/issues/132 ## [v0.1.2] 2021-11-18 ### Changed - Use xml.Marshal to safely build HTTP Upload request. - Use salsa.debian.org/mdosch/xmppsrv for SRV lookups. ## [v0.1.1] 2021-09-12 ### Changed - Xml-escape file name in http-upload. - Xml-escape mimetype in http-upload. ## [v0.1.0] 2021-09-11 ### Added - Initial release go-sendxmpp-0.14.1/LICENSE000066400000000000000000000024341474502115300150500ustar00rootroot00000000000000BSD 2-Clause License Copyright (c) Martin Dosch All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. go-sendxmpp-0.14.1/LICENSE-mellium000066400000000000000000000024271474502115300165140ustar00rootroot00000000000000Copyright © 2014 The Mellium Contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. go-sendxmpp-0.14.1/README.md000066400000000000000000000157501474502115300153270ustar00rootroot00000000000000# go-sendxmpp ## about A tool to send messages to an XMPP contact or MUC inspired by [sendxmpp](https://sendxmpp.hostname.sk/). You can find other sendxmpp alternatives in the [XSF wiki](https://wiki.xmpp.org/web/User:MDosch/Sendxmpp_incarnations). ## support You might join the [chat](https://join.jabber.network/#go-sendxmpp@chat.mdosch.de?join) if you have problems, want to contribute or just want to talk about the project. You might also talk about any of the other sendxmpp incarnations. :) [![Go-sendxmpp MUC badge](https://chat.mdosch.de/muc_badge/go-sendxmpp@chat.mdosch.de)](https://join.jabber.network/#go-sendxmpp@chat.mdosch.de?join) ## requirements * [go](https://golang.org/) >= 1.21 ## installation ### repositories including go-sendxmpp [![Packaging status](https://repology.org/badge/vertical-allrepos/go:sendxmpp.svg)](https://repology.org/project/go:sendxmpp/versions) ### manual installation Latest release: ```plain $ go install salsa.debian.org/mdosch/go-sendxmpp@latest ``` Current development version: ```plain $ go install salsa.debian.org/mdosch/go-sendxmpp@master ``` You will find the binary in `$GOPATH/bin` or, if set, `$GOBIN`. ### binaries There are some (automatically built and untested) binaries linked to the [release](https://salsa.debian.org/mdosch/go-sendxmpp/-/releases). ## usage You can either pipe a programs output to `go-sendxmpp`, write in your terminal (put \^D in a new line to finish) or send the input from a file (`-m` or `--message`). The account data is expected at `~/.config/go-sendxmpp/config` if no other configuration file location is specified with `-f` or `--file`. The configuration file is expected to be in the following format: ```plain username: password: ``` If this is not sufficient to connect you might also specify `jserver` and `port`. It is also possible to use a password manager. In this case the `password` setting should be replaced by the `eval_password` setting: ``` eval_password: ``` You can also configure the alias/nickname for MUCs via the `alias` setting: ``` alias: ``` If no configuration file is present or if the values should be overridden it is possible to define the account details via command line options: ```plain Usage: go-sendxmpp [-cdilnt] [-a value] [--allow-plain] [--anonymous] [--fast-invalidate] [--fast-off] [-f value] [--headline] [--help] [-h value] [-j value] [-m value] [--muc-password value] [--no-sasl-upgrade] [--oob-file value] [--ox] [--ox-delete-nodes] [--ox-genprivkey-rsa] [--ox-genprivkey-x25519] [--ox-import-privkey value] [--ox-passphrase value] [-p value] [--raw] [--scram-mech-pinning value] [--ssdp-off] [-s value] [--suppress-root-warning] [--timeout value] [--tls-version value] [-u value] [--version] [recipients…] -a, --alias=value Set alias/nicknamefor chatrooms. --allow-plain Allow PLAIN authentication. --anonymous Use anonymous authentication. -c, --chatroom Send message to a chatroom. -d, --debug Show debugging info. --fast-invalidate Invalidate XEP-0484: Fast Authentication Streamlining Tokens. --fast-off Disable XEP-0484: Fast Authentication Streamlining Tokens. -f, --file=value Set configuration file. (Default: ~/.config/go-sendxmpp/sendxmpprc) --headline Send message as type headline. --help Show help. -h, --http-upload=value Send a file via http-upload. Can be invoked several times to upload multiple files. -i, --interactive Interactive mode (for use with e.g. 'tail -f'). -j, --jserver=value XMPP server address. -l, --listen Listen for messages and print them to stdout. -m, --message=value Set file including the message. --muc-password=value Password for password protected MUCs. --no-sasl-upgrade Disable XEP-0480: SASL Upgrade Tasks. -n, --no-tls-verify Skip verification of TLS certificates (not recommended). --oob-file=value URL to send a file as out of band data. --ox Use "OpenPGP for XMPP" encryption (experimental). --ox-delete-nodes Delete existing OpenPGP nodes on the server. --ox-genprivkey-rsa Generate a private OpenPGP key (RSA 4096 bit) for the given JID and publish the corresponding public key. --ox-genprivkey-x25519 Generate a private OpenPGP key (x25519) for the given JID and publish the corresponding public key. --ox-import-privkey=value Import an existing private OpenPGP key. --ox-passphrase=value Passphrase for locking and unlocking the private OpenPGP key. -p, --password=value Password for XMPP account. --raw Send raw XML. --scram-mech-pinning=value Enforce the use of a certain SCRAM authentication mechanism. --ssdp-off Disable XEP-0474: SASL SCRAM Downgrade Protection. -s, --subject=value Set message subject. --suppress-root-warning Suppress warning when run as root. --timeout=value Connection timeout in seconds. [10] -t, --tls Use direct TLS. --tls-version=value Minimal TLS version. 10 (TLSv1.0), 11 (TLSv1.1), 12 (TLSv1.2) or 13 (TLSv1.3). [12] -u, --username=value Username for XMPP account. --version Show version information. ``` ### examples Send a message to two recipients using a configuration file. ```bash cat message.txt|go-sendxmpp -f ./sendxmpp recipient1@example.com recipient2@example.com ``` Send a message to two recipients directly defining account credentials. ```bash cat message.txt|go-sendxmpp -u bob@example.com -p swordfish recipient1@example.com recipient2@example.com ``` Send a message to two groupchats (`-c`) using a configuration file. ```bash cat message.txt|go-sendxmpp -cf ./sendxmpp chat1@conference.example.com chat2@conference.example.com ``` Send file changes to two groupchats (`-c`) using a configuration file. ```bash tail -f example.log|go-sendxmpp -cif ./sendxmpp chat1@conference.example.com chat2@conference.example.com ``` Send a notification if a long running process finishes. ```bash waitpid $(pidof -s rsync) && echo "Rsync finished."|go-sendxmpp recipient@example.com ``` ### shell completion There are no shell completions yet (contributions welcome) but for zsh it is possible to automatically create completions from `--help` and for fish it is possible to create completions from the man page. Those might work *good enough*. #### zsh Just place the following in your `~/.zshrc` or `~/.zshrc.local`: ``` bash compdef _gnu_generic go-sendxmpp ``` #### fish Fish can generate them from the man page with following command: ``` bash fish_update_completions ``` go-sendxmpp-0.14.1/authpinning.go000066400000000000000000000020311474502115300167070ustar00rootroot00000000000000package main import ( "fmt" "os" "strings" ) func findAuthPinFilePath(username string) (string, error) { dataPath, err := getDataPath(fsFriendlyJid(username), true) if err != nil { return strEmpty, fmt.Errorf("find auth pin file path: %v", err) } return fmt.Sprintf("%sauthpin", dataPath), nil } func parseAuthPinFile(username string) (bool, error) { // Find auth pin file. authPinFile, err := findAuthPinFilePath(username) if err != nil { return false, fmt.Errorf("parse auth pin file: %v", err) } // Read file. f, err := os.ReadFile(authPinFile) if err != nil { return false, fmt.Errorf("parse auth pin file: %v", err) } // Strip trailing newline. content := strings.TrimSuffix(string(f), "\n") noPLAIN := content == "noPLAIN" return noPLAIN, nil } func writeAuthPinFile(username string) error { // Find auth pin file. authPinFile, err := findAuthPinFilePath(username) if err != nil { return fmt.Errorf("write auth pin file: %v", err) } err = os.WriteFile(authPinFile, []byte("noPLAIN\n"), 0o400) return err } go-sendxmpp-0.14.1/connect.go000066400000000000000000000052211474502115300160200ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "fmt" "net" "os" "strings" "github.com/xmppo/go-xmpp" // BSD-3-Clause "salsa.debian.org/mdosch/xmppsrv" // BSD-2-Clause ) func connect(options xmpp.Options, directTLS bool, anon bool) (*xmpp.Client, error) { var server string proxy := os.Getenv("HTTP_PROXY") if !anon { server = options.User[strings.Index(options.User, "@")+1:] } else { server = options.User } // Look up SRV records or hostmeta2 if server is not specified manually // or if anon authentication is used. if options.Host == "" || anon { // Don't do SRV or hostmeta2 look ups if proxy is set. // TODO: 2024-10-30: Support hostmeta2 look ups using proxy. if proxy == "" { // Look up xmpp-client SRV records. srvMixed, err := xmppsrv.LookupClient(server) if len(srvMixed) > 0 && err == nil { for _, adr := range srvMixed { switch { case directTLS && adr.Type == "xmpp-client": continue case adr.Type == "xmpp-client": // Use StartTLS options.NoTLS = true options.StartTLS = true case adr.Type == "xmpps-client": // Use direct TLS options.NoTLS = false options.StartTLS = false default: continue } options.Host = net.JoinHostPort(adr.Target, fmt.Sprint(adr.Port)) // Connect to server client, err := options.NewClient() if err == nil { return client, nil } } } // Look up hostmeta2 file. hm2, httpStatus, err := xmppsrv.LookupHostmeta2(server) if httpStatus != 404 && err != nil { for _, link := range hm2.Links { if link.Rel == nsC2SdTLS { options.NoTLS = false options.StartTLS = false options.Host = net.JoinHostPort(link.Sni, fmt.Sprint(link.Port)) // Connect to server client, err := options.NewClient() if err == nil { return client, nil } } } } } } _, port, _ := net.SplitHostPort(options.Host) if port == "" { if options.Host == "" { options.Host = server } // Try port 5223 if directTLS is set and no port is provided. if directTLS { options.NoTLS = false options.StartTLS = false options.Host = net.JoinHostPort(options.Host, "5223") } else { // Try port 5222 if no port is provided and directTLS is not set. options.NoTLS = true options.StartTLS = true options.Host = net.JoinHostPort(options.Host, "5222") } } // Connect to server client, err := options.NewClient() if err == nil { return client, nil } return client, fmt.Errorf("connect: failed to connect to server: %w", err) } go-sendxmpp-0.14.1/const.go000066400000000000000000000031731474502115300155210ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main const ( version = "0.14.1" // defaults defaultBufferSize = 100 defaultConfigColumnSep = 2 defaultDirRights = 0o700 defaultFileRights = 0o600 defaultFileRightsWin = 0o200 defaultIDBytes = 12 defaultLenServerConf = 2 defaultRpadMultiple = 100 defaultRSABits = 4096 defaultShortIDBytes = 4 defaultTimeout = 10 defaultTLSMinVersion = 12 defaultTLS10 = 10 defaultTLS11 = 11 defaultTLS12 = 12 defaultTLS13 = 13 // namespace nsC2SdTLS = "urn:xmpp:alt-connections:tls" nsDiscoInfo = "http://jabber.org/protocol/disco#info" nsDiscoItems = "http://jabber.org/protocol/disco#items" nsEme = "urn:xmpp:eme:0" nsHints = "urn:xmpp:hints" nsHTTPUpload = "urn:xmpp:http:upload:0" nsJabberClient = "jabber:client" nsJabberData = "jabber:x:data" nsOx = "urn:xmpp:openpgp:0" nsOxPubKeys = "urn:xmpp:openpgp:0:public-keys" nsPubsub = "http://jabber.org/protocol/pubsub" nsPubsubOwner = "http://jabber.org/protocol/pubsub#owner" nsVersion = "jabber:iq:version" nsXMPPStanzas = "urn:ietf:params:xml:ns:xmpp-stanzas" // strings oxAltBody = "This message is encrypted (XEP-0373: OpenPGP for XMPP)." pubsubPubOptions = "http://jabber.org/protocol/pubsub#publish-options" strChat = "chat" strEmpty = "" strError = "error" strGroupchat = "groupchat" strHeadline = "headline" strResult = "result" ) go-sendxmpp-0.14.1/go.mod000066400000000000000000000013231474502115300151450ustar00rootroot00000000000000module salsa.debian.org/mdosch/go-sendxmpp go 1.22.0 toolchain go1.22.7 require ( github.com/ProtonMail/gopenpgp/v2 v2.8.2 github.com/beevik/etree v1.4.1 github.com/gabriel-vasile/mimetype v1.4.8 github.com/google/uuid v1.6.0 github.com/pborman/getopt/v2 v2.1.0 github.com/xmppo/go-xmpp v0.2.10 golang.org/x/crypto v0.32.0 salsa.debian.org/mdosch/xmppsrv v0.3.3 ) require ( github.com/ProtonMail/go-crypto v1.1.5 // indirect github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f // indirect github.com/cloudflare/circl v1.5.0 // indirect github.com/pkg/errors v0.9.1 // indirect golang.org/x/net v0.34.0 // indirect golang.org/x/sys v0.29.0 // indirect golang.org/x/text v0.21.0 // indirect ) go-sendxmpp-0.14.1/go.sum000066400000000000000000000142571474502115300152040ustar00rootroot00000000000000github.com/ProtonMail/go-crypto v1.1.5 h1:eoAQfK2dwL+tFSFpr7TbOaPNUbPiJj4fLYwwGE1FQO4= github.com/ProtonMail/go-crypto v1.1.5/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f h1:tCbYj7/299ekTTXpdwKYF8eBlsYsDVoggDAuAjoK66k= github.com/ProtonMail/go-mime v0.0.0-20230322103455-7d82a3887f2f/go.mod h1:gcr0kNtGBqin9zDW9GOHcVntrwnjrK+qdJ06mWYBybw= github.com/ProtonMail/gopenpgp/v2 v2.8.2 h1:fe/XagfxkHRCr+cLFMcoF7XwaASRGSmK/fmcmK8yo6o= github.com/ProtonMail/gopenpgp/v2 v2.8.2/go.mod h1:pPWZyRQWpQ7g8NWsdZmUynNZ1R09k4MdbSHvm+KooqM= github.com/beevik/etree v1.4.1 h1:PmQJDDYahBGNKDcpdX8uPy1xRCwoCGVUiW669MEirVI= github.com/beevik/etree v1.4.1/go.mod h1:gPNJNaBGVZ9AwsidazFZyygnd+0pAU38N4D+WemwKNs= github.com/cloudflare/circl v1.5.0 h1:hxIWksrX6XN5a1L2TI/h53AGPhNHoUBo+TD1ms9+pys= github.com/cloudflare/circl v1.5.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/pborman/getopt/v2 v2.1.0 h1:eNfR+r+dWLdWmV8g5OlpyrTYHkhVNxHBdN2cCrJmOEA= github.com/pborman/getopt/v2 v2.1.0/go.mod h1:4NtW75ny4eBw9fO1bhtNdYTlZKYX5/tBLtsOpwKIKd0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/xmppo/go-xmpp v0.2.10 h1:yxCWXuah73nrA30ffhyqzv1ab+VmvxCEdx8yFxIHQlA= github.com/xmppo/go-xmpp v0.2.10/go.mod h1:Vi5xYz5oKoRnf8iXNiAyKr3VKtvEmdTAnvJ8zDf+gkA= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= salsa.debian.org/mdosch/xmppsrv v0.3.3 h1:F8FGyw1Q1LkAs/UbIXd6Obd33q2CKWrIxxrzvuLSVuM= salsa.debian.org/mdosch/xmppsrv v0.3.3/go.mod h1:udWXnWFa9zkcyN9YSB/u44BCnnRDpeQ0eDy3MVLjHZQ= go-sendxmpp-0.14.1/helpers.go000066400000000000000000000167261474502115300160450ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/gob" "fmt" "log" "math/big" "net/url" "os" "regexp" "runtime" "strings" "time" "github.com/google/uuid" // BSD-3-Clause "github.com/xmppo/go-xmpp" // BSD-3-Clause "golang.org/x/crypto/scrypt" // BSD-3-Clause ) type prettyLogger struct{} func (pl prettyLogger) Write(bytes []byte) (int, error) { return fmt.Print(time.Now().Format("2006-01-02 15:04:05 ") + string(bytes)) } func validUTF8(s string) string { // Remove invalid code points. s = strings.ToValidUTF8(s, "�") reg := regexp.MustCompile(`[\x{0000}-\x{0008}\x{000B}\x{000C}\x{000E}-\x{001F}]`) s = reg.ReplaceAllString(s, "�") return s } func validURI(s string) (*url.URL, error) { // Check if URI is valid uri, err := url.ParseRequestURI(s) if err != nil { return uri, fmt.Errorf("valid uri: %w", err) } return uri, nil } func readFile(path string) (*bytes.Buffer, error) { file, err := os.Open(path) if err != nil { return nil, fmt.Errorf("read file: %w", err) } defer file.Close() buffer := new(bytes.Buffer) _, err = buffer.ReadFrom(file) if err != nil { return nil, fmt.Errorf("read file: %w", err) } return buffer, nil } func getFastData(jid string, password string) (xmpp.Fast, error) { folder := fsFriendlyJid(jid) var fast xmpp.Fast fastPath, err := getDataPath(folder, true) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache folder: %w", err) } fastFileLoc := fastPath + "fast.bin" buf, err := readFile(fastFileLoc) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err) } decBuf := bytes.NewBuffer(buf.Bytes()) decoder := gob.NewDecoder(decBuf) err = decoder.Decode(&fast) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err) } salt := make([]byte, 32) key, err := scrypt.Key([]byte(password), salt, 32768, 8, 1, 32) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to create aes key: %w", err) } c, err := aes.NewCipher([]byte(key)) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err) } gcm, err := cipher.NewGCM(c) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err) } nonceSize := gcm.NonceSize() cryptBuf := []byte(fast.Token) nonce, cryptBuf := cryptBuf[:nonceSize], cryptBuf[nonceSize:] tokenBuf, err := gcm.Open(nil, []byte(nonce), cryptBuf, nil) if err != nil { return xmpp.Fast{}, fmt.Errorf("get fast data: failed to read fast cache file: %w", err) } fast.Token = string(tokenBuf) return fast, nil } func deleteFastData(jid string) error { folder := fsFriendlyJid(jid) fastPath, err := getDataPath(folder, true) if err != nil { return fmt.Errorf("write fast data: failed to write fast cache file: %w", err) } fastFileLoc := fastPath + "fast.bin" return os.Remove(fastFileLoc) } func writeFastData(jid string, password string, fast xmpp.Fast) error { var encBuf bytes.Buffer folder := fsFriendlyJid(jid) fastPath, err := getDataPath(folder, true) if err != nil { return fmt.Errorf("write fast data: failed to write fast cache file: %w", err) } fastFileLoc := fastPath + "fast.bin" salt := make([]byte, 32) key, err := scrypt.Key([]byte(password), salt, 32768, 8, 1, 32) if err != nil { return fmt.Errorf("write fast data: failed to create aes cipher: %w", err) } c, err := aes.NewCipher(key) if err != nil { return fmt.Errorf("write fast data: failed to create aes cipher: %w", err) } gcm, err := cipher.NewGCM(c) if err != nil { return fmt.Errorf("write fast data: failed to create aes cipher: %w", err) } nonce := make([]byte, gcm.NonceSize()) _, err = rand.Read(nonce) if err != nil { return fmt.Errorf("write fast data: failed to create aes cipher: %w", err) } buf := gcm.Seal(nonce, nonce, []byte(fast.Token), nil) fast.Token = string(buf) encode := gob.NewEncoder(&encBuf) err = encode.Encode(fast) if err != nil { return fmt.Errorf("write fast data: failed to create fast token file: %w", err) } file, err := os.Create(fastFileLoc) if err != nil { return fmt.Errorf("write fast data: failed to create fast token file: %w", err) } defer file.Close() if runtime.GOOS != "windows" { _ = file.Chmod(os.FileMode(defaultFileRights)) } else { _ = file.Chmod(os.FileMode(defaultFileRightsWin)) } _, err = file.Write(encBuf.Bytes()) if err != nil { return fmt.Errorf("write fast data: failed to write fast token file: %w", err) } return nil } func getClientID(jid string) (string, error) { var clientID string folder := fsFriendlyJid(jid) clientIDLoc, err := getClientIDLoc(folder) if err != nil { return strError, err } buf, err := readFile(clientIDLoc) if err != nil { clientID = uuid.NewString() file, err := os.Create(clientIDLoc) if err != nil { return strEmpty, fmt.Errorf("get client id: failed to create clientid file: %w", err) } defer file.Close() if runtime.GOOS != "windows" { _ = file.Chmod(os.FileMode(defaultFileRights)) } else { _ = file.Chmod(os.FileMode(defaultFileRightsWin)) } _, err = file.Write([]byte(clientID)) if err != nil { return strEmpty, fmt.Errorf("get client id: failed to write client id file: %w", err) } } else { clientID = buf.String() } return clientID, nil } func getDataPath(folder string, create bool) (string, error) { var err error var homeDir, dataDir string switch { case os.Getenv("$XDG_DATA_HOME") != "": dataDir = os.Getenv("$XDG_DATA_HOME") case os.Getenv("$XDG_HOME") != "": homeDir = os.Getenv("$XDG_HOME") dataDir = homeDir + "/.local/share" case os.Getenv("$HOME") != "": homeDir = os.Getenv("$HOME") dataDir = homeDir + "/.local/share" default: homeDir, err = os.UserHomeDir() if err != nil { return strError, fmt.Errorf("get data path: failed to determine user dir: %w", err) } if homeDir == "" { return strError, fmt.Errorf("get data path: received empty string for home directory") } dataDir = homeDir + "/.local/share" } if folder != "" && !strings.HasSuffix(folder, "/") { folder = fmt.Sprintf("%s/", folder) } dataDir = fmt.Sprintf("%s/go-sendxmpp/%s", dataDir, folder) _, err = os.Stat(dataDir) if create && os.IsNotExist(err) { err = os.MkdirAll(dataDir, defaultDirRights) if err != nil { return strError, fmt.Errorf("get data path: could not create folder: %w", err) } } return dataDir, nil } func getClientIDLoc(folder string) (string, error) { dataDir, err := getDataPath(folder, true) if err != nil { return strError, fmt.Errorf("get client id location: %w", err) } dataFile := dataDir + "clientid" return dataFile, nil } func getRpad(messageLength int) string { rpadRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") length := defaultRpadMultiple - messageLength%defaultRpadMultiple max := big.NewInt(int64(len(rpadRunes))) rpad := make([]rune, length) for i := range rpad { randInt, err := rand.Int(rand.Reader, max) if err != nil { log.Fatal(err) } rpad[i] = rpadRunes[randInt.Int64()] } return string(rpad) } func getID() string { return uuid.NewString() } func getShortID() string { return uuid.NewString()[:6] } // Remove @ and dots func fsFriendlyJid(jid string) string { jid = strings.ReplaceAll(jid, "@", "_at_") return strings.ReplaceAll(jid, ".", "_") } go-sendxmpp-0.14.1/httpupload.go000066400000000000000000000173711474502115300165640ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "bytes" "encoding/xml" "fmt" "net/http" "net/url" "os" "path/filepath" "regexp" "strconv" "strings" "time" "github.com/beevik/etree" // BSD-2-clause "github.com/gabriel-vasile/mimetype" // MIT License "github.com/xmppo/go-xmpp" // BSD-3-Clause ) func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePaths []string, timeout time.Duration, ) (urls []string, err error) { var uploadComponent string var maxFileSize int64 var iqDiscoItemsXMLQuery, iqDiscoInfoXMLQuery *etree.Element // Query server for disco#items iqContent, err := sendIQ(client, iqc, jserver, "get", "") if err != nil { return urls, err } iqDiscoItemsXML := etree.NewDocument() err = iqDiscoItemsXML.ReadFromBytes(iqContent.Query) if err != nil { return urls, err } iqDiscoItemsXMLQuery = iqDiscoItemsXML.SelectElement("query") if iqDiscoItemsXMLQuery == nil { return urls, fmt.Errorf("http-upload: no query element in disco items reply") } iqDiscoItemsXMLItems := iqDiscoItemsXMLQuery.SelectElements("item") // Check the services reported by disco#items for the http upload service for _, r := range iqDiscoItemsXMLItems { jid := r.SelectAttr("jid") iqDiscoInfoReqXML := etree.NewDocument() iqDiscoInfoReqXML.WriteSettings.AttrSingleQuote = true iqDiscoInfoReqXMLQuery := iqDiscoInfoReqXML.CreateElement("query") iqDiscoInfoReqXMLQuery.CreateAttr("xmlns", nsDiscoInfo) iqdi, err := iqDiscoInfoReqXML.WriteToString() if err != nil { return urls, err } iqDiscoInfo, err := sendIQ(client, iqc, jid.Value, "get", iqdi) if err != nil { return urls, err } if iqDiscoInfo.Type != strResult { continue } iqDiscoInfoXML := etree.NewDocument() err = iqDiscoInfoXML.ReadFromBytes(iqDiscoInfo.Query) if err != nil { return urls, err } iqDiscoInfoXMLQuery = iqDiscoInfoXML.SelectElement("query") if iqDiscoInfoXMLQuery == nil { continue } iqDiscoInfoXMLIdentity := iqDiscoInfoXMLQuery.SelectElement("identity") if iqDiscoInfoXMLIdentity == nil { continue } iqDiscoInfoXMLType := iqDiscoInfoXMLIdentity.SelectAttr("type") if iqDiscoInfoXMLType == nil { continue } iqDiscoInfoXMLCategory := iqDiscoInfoXMLIdentity.SelectAttr("category") if iqDiscoInfoXMLCategory == nil { continue } if iqDiscoInfoXMLType.Value == "file" && iqDiscoInfoXMLCategory.Value == "store" { uploadComponent = jid.Value break } } if uploadComponent == "" { return urls, fmt.Errorf("http-upload: no http upload component found") } iqDiscoInfoXMLX := iqDiscoInfoXMLQuery.SelectElements("x") for _, r := range iqDiscoInfoXMLX { field := r.SelectElements("field") for i, t := range field { varAttr := t.SelectAttr("var") if varAttr == nil { continue } curFieldVal := t.SelectElement("value") if curFieldVal == nil { continue } if varAttr.Value == "max-file-size" { var prevFieldVal *etree.Element if i > 0 { prevFieldVal = field[i-1].SelectElement("value") if prevFieldVal == nil { continue } } if prevFieldVal.Text() == nsHTTPUpload { maxFileSize, err = strconv.ParseInt(curFieldVal.Text(), 10, 64) if err != nil { return urls, fmt.Errorf("http-upload: error while checking server maximum http upload file size") } } } } } for _, filePath := range filePaths { // Get file size fileInfo, err := os.Stat(filePath) if err != nil { return urls, err } fileSize := fileInfo.Size() // Read file buffer, err := readFile(filePath) if err != nil { return urls, err } // Get mime type mimeType := mimetype.Detect(buffer.Bytes()).String() var mimeTypeEscaped bytes.Buffer xml.Escape(&mimeTypeEscaped, []byte(mimeType)) // Get file name fileName := filepath.Base(filePath) // Just use alphanumerical and some special characters for now // to work around https://github.com/xmppo/go-xmpp/issues/132 reg := regexp.MustCompile(`[^a-zA-Z0-9\+\-\_\.]+`) fileNameEscaped := reg.ReplaceAllString(fileName, "_") // Check if the file size doesn't exceed the maximum file size of the http upload // component if a maximum file size is reported, if not just continue and hope for // the best. if maxFileSize != 0 { if fileSize > maxFileSize { return urls, fmt.Errorf("http-upload: file size %s MiB is larger than the maximum file size allowed (%s MiB)", strconv.FormatInt(fileSize/1024/1024, 10), strconv.FormatInt(maxFileSize/1024/1024, 10)) } } request := etree.NewDocument() request.WriteSettings.AttrSingleQuote = true requestReq := request.CreateElement("request") requestReq.CreateAttr("xmlns", nsHTTPUpload) requestReq.CreateAttr("filename", fileNameEscaped) requestReq.CreateAttr("size", fmt.Sprint(fileSize)) requestReq.CreateAttr("content-type", mimeType) r, err := request.WriteToString() if err != nil { return urls, err } // Request http upload slot uploadSlot, err := sendIQ(client, iqc, uploadComponent, "get", r) if err != nil { return urls, err } if uploadSlot.Type != strResult { return urls, fmt.Errorf("http-upload: error while requesting upload slot") } iqHTTPUploadSlotXML := etree.NewDocument() err = iqHTTPUploadSlotXML.ReadFromBytes(uploadSlot.Query) if err != nil { return urls, err } iqHTTPUploadSlotXMLSlot := iqHTTPUploadSlotXML.SelectElement("slot") if iqHTTPUploadSlotXMLSlot == nil { return urls, fmt.Errorf("http-upload: no slot element") } iqHTTPUploadSlotXMLPut := iqHTTPUploadSlotXMLSlot.SelectElement("put") if iqHTTPUploadSlotXMLPut == nil { return urls, fmt.Errorf("http-upload: no put element") } iqHTTPUploadSlotXMLPutURL := iqHTTPUploadSlotXMLPut.SelectAttr("url") if iqHTTPUploadSlotXMLPutURL == nil { return urls, fmt.Errorf("http-upload: no url attribute") } if !strings.HasPrefix(iqHTTPUploadSlotXMLPutURL.Value, "https://") { return urls, fmt.Errorf("http-upload: upload slot does not provide https") } // Upload file httpTransport := &http.Transport{ IdleConnTimeout: timeout, TLSHandshakeTimeout: timeout, } proxyEnv := os.Getenv("HTTP_PROXY") if proxyEnv != "" { proxyURL, err := url.Parse(proxyEnv) if err != nil { return urls, err } httpTransport.Proxy = http.ProxyURL(proxyURL) } httpClient := &http.Client{Transport: httpTransport} req, err := http.NewRequest(http.MethodPut, iqHTTPUploadSlotXMLPutURL.Value, buffer) if err != nil { return urls, err } req.Header.Set("Content-Type", mimeTypeEscaped.String()) iqHTTPUploadSlotXMLPutHeaders := iqHTTPUploadSlotXMLPut.SelectElements("header") for _, h := range iqHTTPUploadSlotXMLPutHeaders { name := h.SelectAttr("name") if name == nil { continue } switch name.Value { case "Authorization", "Cookie", "Expires": req.Header.Set(name.Value, h.Text()) } } resp, err := httpClient.Do(req) if err != nil { return urls, err } // Test for http status code "200 OK" or "201 Created" if resp.StatusCode != 200 && resp.StatusCode != 201 { return urls, fmt.Errorf("http-upload: upload failed") } // Return http link iqHTTPUploadSlotXMLGet := iqHTTPUploadSlotXMLSlot.SelectElement("get") if iqHTTPUploadSlotXMLGet == nil { return urls, fmt.Errorf("http-upload: no get element") } iqHTTPUploadSlotXMLGetURL := iqHTTPUploadSlotXMLGet.SelectAttr("url") if iqHTTPUploadSlotXMLGetURL == nil { return urls, fmt.Errorf("http-upload: no url attribute") } err = resp.Body.Close() if err != nil { fmt.Println("http-upload: error while closing http request body:", err) } urls = append(urls, iqHTTPUploadSlotXMLGetURL.Value) } return urls, nil } go-sendxmpp-0.14.1/jid.go000066400000000000000000000047671474502115300151530ustar00rootroot00000000000000// Copyright 2014 The Mellium Contributors. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE-mellium file. // Original taken from mellium.im/xmpp/jid (BSD-2-Clause) and adjusted for my needs. // Copyright Martin Dosch package main import ( "fmt" "strings" "unicode/utf8" ) // MarshalJID checks that JIDs include localpart and serverpart // and return it marshaled. Shamelessly stolen from // mellium.im/xmpp/jid func MarshalJID(input string) (string, error) { var ( err error localpart string domainpart string resourcepart string ) s := input // Remove any portion from the first '/' character to the end of the // string (if there is a '/' character present). sep := strings.Index(s, "/") if sep == -1 { resourcepart = "" } else { // If the resource part exists, make sure it isn't empty. if sep == len(s)-1 { return input, fmt.Errorf("invalid jid %s: the resourcepart must be larger than 0 bytes", input) } resourcepart = s[sep+1:] s = s[:sep] } // Remove any portion from the beginning of the string to the first // '@' character (if there is an '@' character present). sep = strings.Index(s, "@") switch { case sep == -1: // There is no @ sign, and therefore no localpart. domainpart = s case sep == 0: // The JID starts with an @ sign (invalid empty localpart) err = fmt.Errorf("invalid jid: %s", input) return input, err default: domainpart = s[sep+1:] localpart = s[:sep] } // We'll throw out any trailing dots on domainparts, since they're ignored: // // If the domainpart includes a final character considered to be a label // separator (dot) by [RFC1034], this character MUST be stripped from // the domainpart before the JID of which it is a part is used for the // purpose of routing an XML stanza, comparing against another JID, or // constructing an XMPP URI or IRI [RFC5122]. In particular, such a // character MUST be stripped before any other canonicalization steps // are taken. domainpart = strings.TrimSuffix(domainpart, ".") var jid string if !utf8.ValidString(localpart) || !utf8.ValidString(domainpart) || !utf8.ValidString(resourcepart) { return input, fmt.Errorf("invalid jid: %s", input) } if domainpart == "" { return input, fmt.Errorf("invalid jid: %s", input) } if localpart == "" { jid = domainpart } else { jid = localpart + "@" + domainpart } if resourcepart == "" { return jid, err } return jid + "/" + resourcepart, err } go-sendxmpp-0.14.1/main.go000066400000000000000000000574121474502115300153240ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "bufio" "context" "crypto/tls" "fmt" "io" "log" "net" "os" "os/signal" osUser "os/user" "runtime" "strings" "time" gopenpgpConst "github.com/ProtonMail/gopenpgp/v2/constants" // MIT License "github.com/ProtonMail/gopenpgp/v2/crypto" // MIT License "github.com/pborman/getopt/v2" // BSD-3-Clause "github.com/xmppo/go-xmpp" // BSD-3-Clause "salsa.debian.org/mdosch/xmppsrv" // BSD-2-Clause ) type configuration struct { username string jserver string port string password string alias string } func closeAndExit(client *xmpp.Client, err error) { client.Close() if err != nil { log.Fatal(err) } os.Exit(0) } func readMessage(messageFilePath string) (string, error) { var ( output string err error ) // Check that message file is existing. _, err = os.Stat(messageFilePath) if err != nil { return output, fmt.Errorf("read message: %w", err) } // Open message file. file, err := os.Open(messageFilePath) if err != nil { return output, fmt.Errorf("read message: %w", err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) for scanner.Scan() { if output == "" { output = scanner.Text() } else { output = output + "\n" + scanner.Text() } } if err = scanner.Err(); err != nil { if err != io.EOF { return "", fmt.Errorf("read message: %w", err) } } return output, nil } func main() { type recipientsType struct { Jid string OxKeyRing *crypto.KeyRing } var ( err error message, user, server, password, alias string oxPrivKey *crypto.Key recipients []recipientsType fast xmpp.Fast // There are some errors that we ignore as we do not want to // stop the execution. Failure is used to track those to exit // with a non-success return value. failure error ) log.SetFlags(0) log.SetOutput(new(prettyLogger)) // Define command line flags. flagHelp := getopt.BoolLong("help", 0, "Show help.") flagHTTPUpload := getopt.ListLong("http-upload", 'h', "Send a file via http-upload. Can be invoked several times to upload multiple files.") flagDebug := getopt.BoolLong("debug", 'd', "Show debugging info.") flagServer := getopt.StringLong("jserver", 'j', "", "XMPP server address.") flagUser := getopt.StringLong("username", 'u', "", "Username for XMPP account.") flagPassword := getopt.StringLong("password", 'p', "", "Password for XMPP account.") flagChatroom := getopt.BoolLong("chatroom", 'c', "Send message to a chatroom.") flagDirectTLS := getopt.BoolLong("tls", 't', "Use direct TLS.") flagAlias := getopt.StringLong("alias", 'a', "", "Set alias/nickname"+ "for chatrooms.") flagFile := getopt.StringLong("file", 'f', "", "Set configuration file. (Default: "+ "~/.config/go-sendxmpp/sendxmpprc)") flagMessageFile := getopt.StringLong("message", 'm', "", "Set file including the message.") flagInteractive := getopt.BoolLong("interactive", 'i', "Interactive mode (for use with e.g. 'tail -f').") flagSkipVerify := getopt.BoolLong("no-tls-verify", 'n', "Skip verification of TLS certificates (not recommended).") flagRaw := getopt.BoolLong("raw", 0, "Send raw XML.") flagListen := getopt.BoolLong("listen", 'l', "Listen for messages and print them to stdout.") flagTimeout := getopt.IntLong("timeout", 0, defaultTimeout, "Connection timeout in seconds.") flagTLSMinVersion := getopt.IntLong("tls-version", 0, defaultTLSMinVersion, "Minimal TLS version. 10 (TLSv1.0), 11 (TLSv1.1), 12 (TLSv1.2) or 13 (TLSv1.3).") flagVersion := getopt.BoolLong("version", 0, "Show version information.") flagMUCPassword := getopt.StringLong("muc-password", 0, "", "Password for password protected MUCs.") flagOx := getopt.BoolLong("ox", 0, "Use \"OpenPGP for XMPP\" encryption (experimental).") flagOxGenPrivKeyRSA := getopt.BoolLong("ox-genprivkey-rsa", 0, "Generate a private OpenPGP key (RSA 4096 bit) for the given JID and publish the "+ "corresponding public key.") flagOxGenPrivKeyX25519 := getopt.BoolLong("ox-genprivkey-x25519", 0, "Generate a private OpenPGP key (x25519) for the given JID and publish the "+ "corresponding public key.") flagOxPassphrase := getopt.StringLong("ox-passphrase", 0, "", "Passphrase for locking and unlocking the private OpenPGP key.") flagOxImportPrivKey := getopt.StringLong("ox-import-privkey", 0, "", "Import an existing private OpenPGP key.") flagOxDeleteNodes := getopt.BoolLong("ox-delete-nodes", 0, "Delete existing OpenPGP nodes on the server.") flagOOBFile := getopt.StringLong("oob-file", 0, "", "URL to send a file as out of band data.") flagHeadline := getopt.BoolLong("headline", 0, "Send message as type headline.") flagSCRAMPinning := getopt.StringLong("scram-mech-pinning", 0, "", "Enforce the use of a certain SCRAM authentication mechanism.") flagSSDPOff := getopt.BoolLong("ssdp-off", 0, "Disable XEP-0474: SASL SCRAM Downgrade Protection.") flagSubject := getopt.StringLong("subject", 's', "", "Set message subject.") flagFastOff := getopt.BoolLong("fast-off", 0, "Disable XEP-0484: Fast Authentication Streamlining Tokens.") flagFastInvalidate := getopt.BoolLong("fast-invalidate", 0, "Invalidate XEP-0484: Fast Authentication Streamlining Tokens.") flagPLAINAllow := getopt.BoolLong("allow-plain", 0, "Allow PLAIN authentication.") flagNoRootWarning := getopt.BoolLong("suppress-root-warning", 0, "Suppress warning when run as root.") flagAnon := getopt.BoolLong("anonymous", 0, "Use anonymous authentication (specify the target anon service as username.") flagNoSASLUpgrade := getopt.BoolLong("no-sasl-upgrade", 0, "Disable XEP-0480: SASL Upgrade Tasks.") // Parse command line flags. getopt.Parse() switch { case *flagHelp: // If requested, show help and quit. getopt.PrintUsage(os.Stdout) os.Exit(0) case *flagVersion: // If requested, show version and quit. fmt.Println("Go-sendxmpp", version) fmt.Println("Go-xmpp library version:", xmpp.Version) fmt.Println("Xmppsrv library version:", xmppsrv.Version) fmt.Println("Gopenpgp library version:", gopenpgpConst.Version) system := runtime.GOOS + "/" + runtime.GOARCH fmt.Println("System:", system, runtime.Version()) fmt.Println("License: BSD-2-clause") os.Exit(0) // Quit if Ox (OpenPGP for XMPP) is requested for unsupported operations like // groupchat, http-upload or listening. case *flagOx && len(*flagHTTPUpload) != 0: log.Fatal("No Ox support for http-upload available.") case *flagOx && *flagChatroom: log.Fatal("No Ox support for chat rooms available.") case len(*flagHTTPUpload) != 0 && *flagInteractive: log.Fatal("Interactive mode and http upload can't" + " be used at the same time.") case len(*flagHTTPUpload) != 0 && *flagMessageFile != "": log.Fatal("You can't send a message while using" + " http upload.") case *flagOx && *flagOOBFile != "": log.Fatal("No encryption possible for OOB data.") case *flagOx && *flagHeadline: log.Fatal("No Ox support for headline messages.") case *flagHeadline && *flagChatroom: log.Fatal("Can't use message type headline for groupchat messages.") case *flagAnon && *flagUser == "": log.Fatal("Specifying a username is required when using anonymous authentication.") } // Print a warning if go-sendxmpp is run by the user root on non-windows systems. if runtime.GOOS != "windows" && !*flagNoRootWarning { // Get the current user. currUser, err := osUser.Current() if err != nil { log.Fatal("Failed to get current user: ", err) } if currUser.Username == "root" { fmt.Println("WARNING: It seems you are running go-sendxmpp as root user.\n" + "This is is not recommended as go-sendxmpp does not require root " + "privileges. Please consider using a less privileged user. For an " + "example how to do this with sudo please consult the manpage chapter " + "TIPS.") } } switch *flagSCRAMPinning { case "", "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS", "SCRAM-SHA-512", "SCRAM-SHA-512-PLUS": default: log.Fatal("Unknown SCRAM mechanism: ", *flagSCRAMPinning) } // Read recipients from command line and quit if none are specified. // For listening or sending raw XML it's not required to specify a recipient except // when sending raw messages to MUCs (go-sendxmpp will join the MUC automatically). recipientsList := getopt.Args() if (len(recipientsList) == 0 && !*flagRaw && !*flagListen && !*flagOxGenPrivKeyX25519 && !*flagOxGenPrivKeyRSA && *flagOxImportPrivKey == "" && !*flagFastInvalidate) && !*flagOxDeleteNodes || (len(recipientsList) == 0 && *flagChatroom) { log.Fatal("No recipient specified.") } // Read configuration file if no user or password is specified and anonymous // authentication is not used. if (*flagUser == "" || *flagPassword == "") && !*flagAnon { // Read configuration from file. config, err := parseConfig(*flagFile) if err != nil { log.Fatal("Error parsing ", *flagFile, ": ", err) } // Set connection options according to config. user = config.username server = config.jserver password = config.password alias = config.alias if config.port != "" { server = net.JoinHostPort(server, fmt.Sprint(config.port)) } } // Overwrite user if specified via command line flag. if *flagUser != "" { user = *flagUser } // Overwrite server if specified via command line flag. if *flagServer != "" { server = *flagServer } // Overwrite password if specified via command line flag. if *flagPassword != "" && !*flagAnon { password = *flagPassword } // If no server part is specified in the username but a server is specified // just assume the server is identical to the server part and hope for the // best. This is for compatibility with the old perl sendxmpp config files. var serverpart string if !strings.Contains(user, "@") && server != "" && !*flagAnon { // Remove port if server contains it. if strings.Contains(server, ":") { serverpart, _, err = net.SplitHostPort(server) if err != nil { log.Fatal(err) } } else { serverpart = server } user = user + "@" + serverpart } switch { // Use "go-sendxmpp" if no nick is specified via config or command line flag. case alias == "" && *flagAlias == "": alias = "go-sendxmpp" // Overwrite configured alias if a nick is specified via command line flag. case *flagAlias != "": alias = *flagAlias } // Timeout timeout := time.Duration(*flagTimeout) * time.Second clientID, err := getClientID(user) if err != nil { fmt.Println(err) } if !*flagFastOff { fast, _ = getFastData(user, password) // Reset FAST token and mechanism if expired or // FastInvalidate is set. if time.Now().After(fast.Expiry) || *flagFastInvalidate { fast.Token = "" fast.Mechanism = "" } } if fast.Mechanism != "" && *flagSCRAMPinning != "" { log.Fatalf(("FAST: %s is requested, but we have a token for %s."), *flagSCRAMPinning, fast.Mechanism) } // Use ALPN var tlsConfig tls.Config if !*flagAnon { tlsConfig.ServerName = user[strings.Index(user, "@")+1:] } else { tlsConfig.ServerName = *flagUser *flagSCRAMPinning = "ANONYMOUS" } tlsConfig.NextProtos = append(tlsConfig.NextProtos, "xmpp-client") tlsConfig.InsecureSkipVerify = *flagSkipVerify tlsConfig.Renegotiation = tls.RenegotiateNever switch *flagTLSMinVersion { case defaultTLS10: tlsConfig.MinVersion = tls.VersionTLS10 case defaultTLS11: tlsConfig.MinVersion = tls.VersionTLS11 case defaultTLS12: tlsConfig.MinVersion = tls.VersionTLS12 case defaultTLS13: tlsConfig.MinVersion = tls.VersionTLS13 default: fmt.Println("Unknown TLS version.") os.Exit(0) } resource := "go-sendxmpp." + getShortID() // Check whether PLAIN authentication is disabled. pinNoPLAIN, _ := parseAuthPinFile(user) noPLAIN := pinNoPLAIN || !*flagPLAINAllow // Set XMPP connection options. options := xmpp.Options{ Host: server, User: user, DialTimeout: timeout, Resource: resource, Password: password, // NoTLS doesn't mean that no TLS is used at all but that instead // of using an encrypted connection to the server (direct TLS) // an unencrypted connection is established. As StartTLS is // set when NoTLS is set go-sendxmpp won't use unencrypted // client-to-server connections. // See https://pkg.go.dev/github.com/xmppo/go-xmpp#Options NoTLS: !*flagDirectTLS, StartTLS: !*flagDirectTLS, Debug: *flagDebug, DebugWriter: os.Stdout, TLSConfig: &tlsConfig, Mechanism: *flagSCRAMPinning, SSDP: !*flagSSDPOff, UserAgentSW: resource, UserAgentID: clientID, Fast: !*flagFastOff, FastToken: fast.Token, FastMechanism: fast.Mechanism, FastInvalidate: *flagFastInvalidate, NoPLAIN: noPLAIN, NoSASLUpgrade: *flagNoSASLUpgrade, } // Read message from file. if *flagMessageFile != "" { message, err = readMessage(*flagMessageFile) if err != nil { log.Fatal(err) } } // Skip reading message if '-i' or '--interactive' is set to work with e.g. 'tail -f'. // Also for listening mode and Ox key handling. if !*flagInteractive && !*flagListen && len(*flagHTTPUpload) == 0 && !*flagOxDeleteNodes && *flagOxImportPrivKey == "" && !*flagOxGenPrivKeyX25519 && !*flagOxGenPrivKeyRSA && *flagOOBFile == "" && !*flagFastInvalidate && message == "" { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { if message == "" { message = scanner.Text() } else { message = message + "\n" + scanner.Text() } } if err := scanner.Err(); err != nil { if err != io.EOF { log.Fatal(err) } } } // Remove invalid code points. message = validUTF8(message) // Exit if message is empty. if message == "" && !*flagInteractive && !*flagListen && !*flagOxGenPrivKeyRSA && !*flagOxGenPrivKeyX25519 && *flagOxImportPrivKey == "" && !*flagOxDeleteNodes && len(*flagHTTPUpload) == 0 && *flagOOBFile == "" && !*flagFastInvalidate { os.Exit(0) } // Connect to server. client, err := connect(options, *flagDirectTLS, *flagAnon) if err != nil { if fast.Token != "" { log.Fatal(fmt.Errorf("could not connect using FAST authentication: %v", err)) } else { log.Fatal(err) } } // Update fast token if a new one is received or expiry time is reduced. if (client.Fast.Token != "" && client.Fast.Token != fast.Token) || (client.Fast.Expiry.Before(fast.Expiry) && !client.Fast.Expiry.IsZero()) { fast.Token = client.Fast.Token fast.Mechanism = client.Fast.Mechanism fast.Expiry = client.Fast.Expiry err := writeFastData(user, password, fast) if err != nil { fmt.Println(err) } } // Delete stored fast data when FastInvalidate is set. if *flagFastInvalidate && *flagFastOff { err := deleteFastData(user) if err != nil { fmt.Println(err) } } // If authentication is not yet pinned to not use PLAIN and a SCRAM mechanism is // used, write the auth pin file. if !pinNoPLAIN && (strings.HasPrefix(client.Mechanism, "SCRAM") || strings.HasPrefix(client.Mechanism, "HT")) { err = writeAuthPinFile(user) if err != nil { log.Println("could not write authentication mechanism pin file:", err) } } iqc := make(chan xmpp.IQ, defaultBufferSize) msgc := make(chan xmpp.Chat, defaultBufferSize) ctx, cancel := context.WithCancel(context.Background()) go rcvStanzas(client, ctx, iqc, msgc) for _, r := range getopt.Args() { var re recipientsType re.Jid = r if *flagOx { re.OxKeyRing, err = oxGetPublicKeyRing(client, iqc, r) if err != nil { re.OxKeyRing = nil fmt.Printf("ox: error fetching key for %s: %v\n", r, err) failure = err } } recipients = append(recipients, re) } // Check that all recipient JIDs are valid. for i, recipient := range recipients { validatedJid, err := MarshalJID(recipient.Jid) if err != nil { cancel() closeAndExit(client, err) } recipients[i].Jid = validatedJid } switch { case *flagOxGenPrivKeyX25519: validatedOwnJid, err := MarshalJID(user) if err != nil { cancel() closeAndExit(client, err) } err = oxGenPrivKey(validatedOwnJid, client, iqc, *flagOxPassphrase, "x25519") if err != nil { cancel() closeAndExit(client, err) } os.Exit(0) case *flagOxGenPrivKeyRSA: validatedOwnJid, err := MarshalJID(user) if err != nil { cancel() closeAndExit(client, err) } err = oxGenPrivKey(validatedOwnJid, client, iqc, *flagOxPassphrase, "rsa") if err != nil { cancel() closeAndExit(client, err) } os.Exit(0) case *flagOxImportPrivKey != "": validatedOwnJid, err := MarshalJID(user) if err != nil { cancel() closeAndExit(client, err) } err = oxImportPrivKey(validatedOwnJid, *flagOxImportPrivKey, client, iqc) if err != nil { cancel() closeAndExit(client, err) } os.Exit(0) case *flagOxDeleteNodes: validatedOwnJid, err := MarshalJID(user) if err != nil { cancel() closeAndExit(client, err) } err = oxDeleteNodes(validatedOwnJid, client, iqc) if err != nil { cancel() closeAndExit(client, err) } os.Exit(0) case *flagOx: validatedOwnJid, err := MarshalJID(user) if err != nil { cancel() closeAndExit(client, err) } oxPrivKey, err = oxGetPrivKey(validatedOwnJid, *flagOxPassphrase) if err != nil { cancel() closeAndExit(client, err) } } var uploadMessages []string if len(*flagHTTPUpload) != 0 { uploadMessages, err = httpUpload(client, iqc, tlsConfig.ServerName, *flagHTTPUpload, timeout) if err != nil { cancel() closeAndExit(client, err) } } if *flagOOBFile != "" { // Remove invalid UTF8 code points. message = validUTF8(*flagOOBFile) // Check if the URI is valid. uri, err := validURI(message) if err != nil { cancel() closeAndExit(client, err) } message = uri.String() } var msgType string if *flagHeadline { msgType = strHeadline } else { msgType = strChat } if *flagChatroom { msgType = strGroupchat // Join the MUCs. for _, recipient := range recipients { if *flagMUCPassword != "" { dummyTime := time.Now() _, err = client.JoinProtectedMUC(recipient.Jid, alias, *flagMUCPassword, xmpp.NoHistory, 0, &dummyTime) } else { _, err = client.JoinMUCNoHistory(recipient.Jid, alias) } if err != nil { cancel() closeAndExit(client, err) } } } switch { case *flagRaw: if message == "" { break } // Send raw XML _, err = client.SendOrg(message) if err != nil { cancel() closeAndExit(client, err) } case *flagInteractive: // Send in endless loop (for usage with e.g. "tail -f"). reader := bufio.NewReader(os.Stdin) // Quit if ^C is pressed. c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { for range c { cancel() if failure != nil { closeAndExit(client, failure) } closeAndExit(client, nil) } }() for { message, err = reader.ReadString('\n') if err != nil { select { case <-ctx.Done(): return default: if err != nil { cancel() closeAndExit(client, fmt.Errorf("failed to read from stdin")) } } } message = strings.TrimSuffix(message, "\n") // Remove invalid code points. message = validUTF8(message) if message == "" { continue } for _, recipient := range recipients { switch { case *flagOx: if recipient.OxKeyRing == nil { continue } oxMessage, err := oxEncrypt(client, oxPrivKey, recipient.Jid, *recipient.OxKeyRing, message, *flagSubject) if err != nil { fmt.Printf("ox: couldn't encrypt to %s: %v\n", recipient.Jid, err) failure = err continue } _, err = client.SendOrg(oxMessage) if err != nil { cancel() closeAndExit(client, err) } default: _, err = client.Send(xmpp.Chat{ Remote: recipient.Jid, Type: msgType, Text: message, Subject: *flagSubject, }) if err != nil { cancel() closeAndExit(client, err) } } } } case *flagListen: tz := time.Now().Location() // Quit if ^C is pressed. c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { for range c { cancel() if failure != nil { closeAndExit(client, failure) } closeAndExit(client, nil) } }() for { v := <-msgc switch { case isOxMsg(v) && *flagOx: msg, t, err := oxDecrypt(v, client, iqc, user, oxPrivKey) if err != nil { log.Println(err) continue } if msg == "" { continue } var bareFrom string switch v.Type { case strChat: bareFrom = strings.Split(v.Remote, "/")[0] case strGroupchat: bareFrom = v.Remote default: bareFrom = strings.Split(v.Remote, "/")[0] } // Print any messages if no recipients are specified if len(recipients) == 0 { fmt.Println(t.In(tz).Format(time.RFC3339), "[OX]", bareFrom+":", msg) } else { for _, recipient := range recipients { if strings.Split(v.Remote, "/")[0] == strings.ToLower(recipient.Jid) { fmt.Println(t.In(tz).Format(time.RFC3339), "[OX]", bareFrom+":", msg) } } } default: var t time.Time if v.Text == "" { continue } if v.Stamp.IsZero() { t = time.Now() } else { t = v.Stamp } var bareFrom string switch v.Type { case strChat: bareFrom = strings.Split(v.Remote, "/")[0] case strGroupchat: bareFrom = v.Remote default: bareFrom = strings.Split(v.Remote, "/")[0] } // Print any messages if no recipients are specified if len(recipients) == 0 { fmt.Println(t.In(tz).Format(time.RFC3339), bareFrom+":", v.Text) } else { for _, recipient := range recipients { if strings.Split(v.Remote, "/")[0] == strings.ToLower(recipient.Jid) { fmt.Println(t.In(tz).Format(time.RFC3339), bareFrom+":", v.Text) } } } } } default: for _, recipient := range recipients { if message == "" && len(uploadMessages) == 0 { break } switch { case len(*flagHTTPUpload) != 0: for _, message = range uploadMessages { _, err = client.Send(xmpp.Chat{ Remote: recipient.Jid, Type: msgType, Ooburl: message, Text: message, Subject: *flagSubject, }) if err != nil { fmt.Println("Couldn't send message to", recipient.Jid) } } // (Hopefully) temporary workaround due to go-xmpp choking on URL encoding. // Once this is fixed in the lib the http-upload case above can be reused. case *flagOOBFile != "": var msg string if *flagSubject != "" { msg = fmt.Sprintf("%s%s%s", recipient.Jid, msgType, *flagSubject, message, message) } else { msg = fmt.Sprintf("%s%s", recipient.Jid, msgType, message, message) } _, err = client.SendOrg(msg) if err != nil { fmt.Println("Couldn't send message to", recipient.Jid) } case *flagOx: if recipient.OxKeyRing == nil { continue } oxMessage, err := oxEncrypt(client, oxPrivKey, recipient.Jid, *recipient.OxKeyRing, message, *flagSubject) if err != nil { fmt.Printf("ox: couldn't encrypt to %s: %v\n", recipient.Jid, err) failure = err continue } _, err = client.SendOrg(oxMessage) if err != nil { cancel() closeAndExit(client, err) } default: _, err = client.Send(xmpp.Chat{ Remote: recipient.Jid, Type: msgType, Text: message, Subject: *flagSubject, }) if err != nil { cancel() closeAndExit(client, err) } } } } cancel() if failure != nil { closeAndExit(client, failure) } closeAndExit(client, nil) } go-sendxmpp-0.14.1/man/000077500000000000000000000000001474502115300146135ustar00rootroot00000000000000go-sendxmpp-0.14.1/man/go-sendxmpp.1000066400000000000000000000220261474502115300171400ustar00rootroot00000000000000.\" generated with Ronn-NG/v0.9.1 .\" http://github.com/apjanke/ronn-ng/tree/0.9.1 .TH "GO\-SENDXMPP" "1" "December 2024" "" .SH "NAME" \fBgo\-sendxmpp\fR \- A tool to send messages to an XMPP contact or MUC\. .SH "SYNOPSIS" \fBgo\-sendxmpp [\-cdilnt] [\-a value] [\-\-allow\-plain] [\-\-anonymous] [\-\-fast\-invalidate] [\-\-fast\-off] [\-f value] [\-\-headline] [\-\-help] [\-h value] [\-j value] [\-m value] [\-\-muc\-password value] [\-\-no\-sasl\-upgrade] [\-\-oob\-file value] [\-\-ox] [\-\-ox\-delete\-nodes] [\-\-ox\-genprivkey\-rsa] [\-\-ox\-genprivkey\-x25519] [\-\-ox\-import\-privkey value] [\-\-ox\-passphrase value] [\-p value] [\-\-raw] [\-\-scram\-mech\-pinning value] [\-\-ssdp\-off] [\-s value] [\-\-suppress\-root\-warning] [\-\-timeout value] [\-\-tls\-version value] [\-u value] [\-\-version] [recipients…]\fR .SH "DESCRIPTION" A tool to send messages to an XMPP contact or MUC inspired by \fBsendxmpp\fR\. .br You can either pipe a programs output to \fBgo\-sendxmpp\fR, write in your terminal (put \fB^D\fR in a new line to finish) or send the input from a file (\fB\-m\fR or \fB\-\-message\fR)\. The account data is expected at \fB~/\.config/go\-sendxmpp/config\fR (preferred), \fB~/\.config/go\-sendxmpp/sendxmpprc\fR (deprecated) \fB~/\.sendxmpprc\fR (for compatibility with the original perl sendxmpp) if no other configuration file location is specified with \fB\-f\fR or \fB\-\-file\fR\. .SH "OPTIONS" .TP \fB\-a\fR, \fB\-\-alias\fR=[\fIvalue\fR] Set alias/nickname for chatrooms\. .TP \fB\-\-allow\-plain\fR Allow PLAIN authentication\. Note that this setting has no effect if there was a successful connection using a SCRAM authentication mechanism before\. In that case PLAIN is not allowed to prevent downgrades by a man\-in\-the\-middle attack\. .TP \fB\-\-anonymous\fR Use anonymous authentication\. Specify the the target server by using the flag \fB\-u\fR or \fB\-\-username\fR\. Username is used to specify the server to be able to override the server by using \fB\-j\fR or \fB\-\-jserver\fR in cases where the service (e\.g\. anon\.example\.org) is served by another server (e\.g\. xmpp\.example\.org) but no SRV records are set up\. .TP \fB\-c\fR, \fB\-\-chatroom\fR=[\fIvalue\fR] Send message to a chatroom\. .TP \fB\-d\fR, \fB\-\-debug\fR Show debugging info\. .TP \fB\-\-fast\-invalidate\fR Invalidate XEP\-0484: Fast Authentication Streamlining Tokens\. The current FAST token will be invalidated and a new one will be requested\. If used together with \fB\-\-fast\-off\fR the FAST token will be invalidated and the stored FAST token deleted\. .TP \fB\-\-fast\-off\fR Disable XEP\-0484: Fast Authentication Streamlining Tokens\. Deletes the stored FAST token when used together with \fB\-\-fast\-invalidate\fR\. .TP \fB\-f\fR, \fB\-\-file\fR=[\fIvalue\fR] Set configuration file\. (Default: ~/\.config/go\-sendxmpp/config) .TP \fB\-\-headline\fR Send message as type headline\. .TP \fB\-\-help\fR Show help\. .TP \fB\-h\fR, \fB\-\-http\-upload=\fR[\fIvalue\fR] Send a file via http\-upload\. Can be invoked several times to upload multiple files\. .TP \fB\-i\fR, \fB\-\-interactive\fR Interactive mode (for use with e\.g\. \fBtail \-f\fR)\. .TP \fB\-j\fR, \fB\-\-jserver\fR=[\fIvalue\fR] XMPP server address\. .TP \fB\-l\fR, \fB\-\-listen\fR Listen for messages and print them to stdout\. If JIDs are specified only messages from those contacts are shown\. If no JIDs are specified all received messages will be shown\. .TP \fB\-m\fR, \fB\-\-message\fR=[\fIvalue\fR] Set file including the message\. .TP \fB\-\-muc\-password\fR=[\fIvalue\fR] Password for password protected MUCs\. .TP \fB\-\-no\-sasl\-upgrade\fR Disable XEP\-0480: SASL Upgrade Tasks\. .TP \fB\-n\fR, \fB\-\-no\-tls\-verify\fR Skip verification of TLS certificates (not recommended)\. .TP \fB\-\-oob\-file\fR=[\fIvalue\fR] URL to send a file as out of band data\. .TP \fB\-\-ox\fR Use "OpenPGP for XMPP" encryption (experimental)\. .br Ox in go\-sendxmpp only supports sending encrypted 1\-1 messages\. Sending to groupchats and sending encrypted files is not supported\. There is no check whether the recipients key is trusted as there is no local keyring used\. Go\-sendxmpp just uses the most recent key that is provided via pubsub and checks that it is not expired\. As a user facing client a notification would be shown that a new key is available and ask the user whether to use the new key or stick to the old one\. As go\-sendxmpp is usually used in scripts it just accepts the new key to prevent the user from missing a new notification due to changed keys\. .TP \fB\-\-ox\-delete\-nodes\fR Delete existing OpenPGP nodes on the server\. .TP \fB\-\-ox\-genprivkey\-rsa\fR Generate a private OpenPGP key (RSA 4096 bit) for the configured account (via config file or \fB\-u\fR and \fB\-p\fR) and publish the corresponding public key\. Go\-sendxmpp will save the key in \fB$XDG_DATA_HOME/go\-sendxmpp/oxprivkeys\fR or \fB$HOME/\.local/share/go\-sendxmpp/oxprivkeys\fR\. To protect the key a passphrase might be set using \fB\-\-ox\-passphrase\fR while generating the key\. .br If there is an existing private key for "OpenPGP for XMPP" created by another client (e\.g\. profanity) it might be imported using \fB\-\-ox\-import\-privkey\fR\. .TP \fB\-\-ox\-genprivkey\-x25519\fR Generate a private OpenPGP key (X25519) for the configured account (via config file or \fB\-u\fR and \fB\-p\fR) and publish the corresponding public key\. Go\-sendxmpp will save the key in \fB$XDG_DATA_HOME/go\-sendxmpp/oxprivkeys\fR or \fB$HOME/\.local/share/go\-sendxmpp/oxprivkeys\fR\. To protect the key a passphrase might be set using \fB\-\-ox\-passphrase\fR while generating the key\. .br If there is an existing private key for "OpenPGP for XMPP" created by another client (e\.g\. profanity) it might be imported using \fB\-\-ox\-import\-privkey\fR\. .TP \fB\-\-ox\-import\-privkey\fR=[\fIvalue\fR] Import an existing private OpenPGP key\. .TP \fB\-\-ox\-passphrase\fR=[\fIvalue\fR] Passphrase for locking and unlocking the private OpenPGP key\. .TP \fB\-p\fR, \fB\-\-password\fR=[\fIvalue\fR] Password for XMPP account\. .TP \fB\-\-raw\fR Send raw XML\. To send raw XML to a contact as normal chat message no contact must be specified\. To send raw XML to a MUC you have to specify the MUC via \fB\-c\fR and go\-sendxmpp will join the MUC\. .TP \fB\-\-scram\-mech\-pinning=[]\fR Enforce the use of a certain SCRAM authentication mechanism\. Currently go\-sendxmpp supports \fBSCRAM\-SHA\-1\fR, \fBSCRAM\-SHA\-1\-PLUS\fR, \fBSCRAM\-SHA\-256\fR, \fBSCRAM\-SHA\-256\-PLUS\fR, \fBSCRAM\-SHA\-512\fR and \fBSCRAM\-SHA\-512\-PLUS\fR\. You should know what you are doing when using this setting and make sure the chosen mechanism is supported by the server\. If not set, go\-sendxmpp will use XEP\-0474 to prevent downgrade attacks (needs server support and requires a SCRAM authentication mechanism)\. .TP \fB\-\-ssdp\-off\fR Disable XEP\-0474: SASL SCRAM Downgrade Protection\. .TP \fB\-s\fR, \fB\-\-subject\fR=[\fIvalue\fR] Set message subject\. .TP \fB\-\-suppress\-root\-warning\fR Suppress warning when run as root\. .TP \fB\-\-timeout=\fR[\fIvalue\fR] Connection timeout in seconds\. (Default: 10) .TP \fB\-t\fR, \fB\-\-tls\fR Use direct TLS\. .TP \fB\-\-tls\-version\fR=[\fIvalue\fR] Minimal TLS version\. 10 (TLSv1\.0), 11 (TLSv1\.1), 12 (TLSv1\.2), 13 (TLSv1\.3) (Default: 12) .TP \fB\-u\fR, \fB\-\-username\fR=[\fIvalue\fR] Username for XMPP account (JID)\. .TP \fB\-\-version\fR Show version information\. .SH "ENVIRONMENT VARIABLES" .SS "HTTP_PROXY" A SOCKS5 proxy can be used by setting the environment variable \fBHTTP_PROXY\fR\. This feature is considered experimental and there is no guarantee that there won't be any connections not using the proxy although it didn't happen during testing\. .P \fBHTTP_PROXY="socks5://127\.0\.0\.1:9050" go\-sendxmpp \-\-http\-upload file\.txt user@example\.org\fR .SH "TIPS" .SS "USAGE BY ROOT" In general it's a good advice to only perform commands as root when it is strictly necessary\. To be able to send the output from commands, that need to be performed as root, with go\-sendxmpp without invoking go\-sendxmpp by root sudo can be used\. .P In this example there is a user \fBsendxmpp\fR with a go\-sendxmpp config in its \fB$HOME\fR: .P \fB# command\-that\-requires\-root|sudo \-H \-u sendxmpp go\-sendxmpp me@example\.org\fR .SH "SHELL COMPLETIONS" .SS "ZSH" There are no shell completions yet (contributions welcome) but for zsh it is possible to automatically create completions from \fB\-\-help\fR which might work good enough\. .P Just place the following in your \fB~/\.zshrc\fR or \fB~/\.zshrc\.local\fR: .P \fBcompdef _gnu_generic go\-sendxmpp\fR .SS "FISH" There are no shell completions yet, but FISH can generate them from the man page with following command: .P \fBfish_update_completions\fR .SH "CHAT" Feel free to join \fIhttps://join\.jabber\.network/#go\-sendxmpp@chat\.mdosch\.de?join\fR\. .SH "AUTHOR" Written by Martin Dosch\. .SH "REPORTING BUGS" Report bugs at \fIhttps://salsa\.debian\.org/mdosch/go\-sendxmpp/issues\fR\. .SH "COPYRIGHT" Copyright (c) Martin Dosch License: BSD 2\-clause License .SH "SEE ALSO" go\-sendxmpp(5), xmppc(1), sendxmpp(1) go-sendxmpp-0.14.1/man/go-sendxmpp.1.html000066400000000000000000000334671474502115300201160ustar00rootroot00000000000000 go-sendxmpp(1) - A tool to send messages to an XMPP contact or MUC.
  1. go-sendxmpp(1)
  2. go-sendxmpp(1)

NAME

go-sendxmpp - A tool to send messages to an XMPP contact or MUC.

SYNOPSIS

go-sendxmpp [-cdilnt] [-a value] [--allow-plain] [--anonymous] [--fast-invalidate] [--fast-off] [-f value] [--headline] [--help] [-h value] [-j value] [-m value] [--muc-password value] [--no-sasl-upgrade] [--oob-file value] [--ox] [--ox-delete-nodes] [--ox-genprivkey-rsa] [--ox-genprivkey-x25519] [--ox-import-privkey value] [--ox-passphrase value] [-p value] [--raw] [--scram-mech-pinning value] [--ssdp-off] [-s value] [--suppress-root-warning] [--timeout value] [--tls-version value] [-u value] [--version] [recipients…]

DESCRIPTION

A tool to send messages to an XMPP contact or MUC inspired by sendxmpp.
You can either pipe a programs output to go-sendxmpp, write in your terminal (put ^D in a new line to finish) or send the input from a file (-m or --message). The account data is expected at ~/.config/go-sendxmpp/config (preferred), ~/.config/go-sendxmpp/sendxmpprc (deprecated) ~/.sendxmpprc (for compatibility with the original perl sendxmpp) if no other configuration file location is specified with -f or --file.

OPTIONS

-a, --alias=[value]
Set alias/nickname for chatrooms.
--allow-plain
Allow PLAIN authentication. Note that this setting has no effect if there was a successful connection using a SCRAM authentication mechanism before. In that case PLAIN is not allowed to prevent downgrades by a man-in-the-middle attack.
--anonymous
Use anonymous authentication. Specify the the target server by using the flag -u or --username. Username is used to specify the server to be able to override the server by using -j or --jserver in cases where the service (e.g. anon.example.org) is served by another server (e.g. xmpp.example.org) but no SRV records are set up.
-c, --chatroom=[value]
Send message to a chatroom.
-d, --debug
Show debugging info.
--fast-invalidate
Invalidate XEP-0484: Fast Authentication Streamlining Tokens. The current FAST token will be invalidated and a new one will be requested. If used together with --fast-off the FAST token will be invalidated and the stored FAST token deleted.
--fast-off
Disable XEP-0484: Fast Authentication Streamlining Tokens. Deletes the stored FAST token when used together with --fast-invalidate.
-f, --file=[value]
Set configuration file. (Default: ~/.config/go-sendxmpp/config)
--headline
Send message as type headline.
--help
Show help.
-h, --http-upload=[value]
Send a file via http-upload. Can be invoked several times to upload multiple files.
-i, --interactive
Interactive mode (for use with e.g. tail -f).
-j, --jserver=[value]
XMPP server address.
-l, --listen
Listen for messages and print them to stdout. If JIDs are specified only messages from those contacts are shown. If no JIDs are specified all received messages will be shown.
-m, --message=[value]
Set file including the message.
--muc-password=[value]
Password for password protected MUCs.
--no-sasl-upgrade
Disable XEP-0480: SASL Upgrade Tasks.
-n, --no-tls-verify
Skip verification of TLS certificates (not recommended).
--oob-file=[value]
URL to send a file as out of band data.
--ox
Use "OpenPGP for XMPP" encryption (experimental).
Ox in go-sendxmpp only supports sending encrypted 1-1 messages. Sending to groupchats and sending encrypted files is not supported. There is no check whether the recipients key is trusted as there is no local keyring used. Go-sendxmpp just uses the most recent key that is provided via pubsub and checks that it is not expired. As a user facing client a notification would be shown that a new key is available and ask the user whether to use the new key or stick to the old one. As go-sendxmpp is usually used in scripts it just accepts the new key to prevent the user from missing a new notification due to changed keys.
--ox-delete-nodes
Delete existing OpenPGP nodes on the server.
--ox-genprivkey-rsa
Generate a private OpenPGP key (RSA 4096 bit) for the configured account (via config file or -u and -p) and publish the corresponding public key. Go-sendxmpp will save the key in $XDG_DATA_HOME/go-sendxmpp/oxprivkeys or $HOME/.local/share/go-sendxmpp/oxprivkeys. To protect the key a passphrase might be set using --ox-passphrase while generating the key.
If there is an existing private key for "OpenPGP for XMPP" created by another client (e.g. profanity) it might be imported using --ox-import-privkey.
--ox-genprivkey-x25519
Generate a private OpenPGP key (X25519) for the configured account (via config file or -u and -p) and publish the corresponding public key. Go-sendxmpp will save the key in $XDG_DATA_HOME/go-sendxmpp/oxprivkeys or $HOME/.local/share/go-sendxmpp/oxprivkeys. To protect the key a passphrase might be set using --ox-passphrase while generating the key.
If there is an existing private key for "OpenPGP for XMPP" created by another client (e.g. profanity) it might be imported using --ox-import-privkey.
--ox-import-privkey=[value]
Import an existing private OpenPGP key.
--ox-passphrase=[value]
Passphrase for locking and unlocking the private OpenPGP key.
-p, --password=[value]
Password for XMPP account.
--raw
Send raw XML. To send raw XML to a contact as normal chat message no contact must be specified. To send raw XML to a MUC you have to specify the MUC via -c and go-sendxmpp will join the MUC.
--scram-mech-pinning=[<value>]
Enforce the use of a certain SCRAM authentication mechanism. Currently go-sendxmpp supports SCRAM-SHA-1, SCRAM-SHA-1-PLUS, SCRAM-SHA-256, SCRAM-SHA-256-PLUS, SCRAM-SHA-512 and SCRAM-SHA-512-PLUS. You should know what you are doing when using this setting and make sure the chosen mechanism is supported by the server. If not set, go-sendxmpp will use XEP-0474 to prevent downgrade attacks (needs server support and requires a SCRAM authentication mechanism).
--ssdp-off
Disable XEP-0474: SASL SCRAM Downgrade Protection.
-s, --subject=[value]
Set message subject.
--suppress-root-warning
Suppress warning when run as root.
--timeout=[value]
Connection timeout in seconds. (Default: 10)
-t, --tls
Use direct TLS.
--tls-version=[value]
Minimal TLS version. 10 (TLSv1.0), 11 (TLSv1.1), 12 (TLSv1.2), 13 (TLSv1.3) (Default: 12)
-u, --username=[value]
Username for XMPP account (JID).
--version
Show version information.

ENVIRONMENT VARIABLES

HTTP_PROXY

A SOCKS5 proxy can be used by setting the environment variable HTTP_PROXY. This feature is considered experimental and there is no guarantee that there won't be any connections not using the proxy although it didn't happen during testing.

HTTP_PROXY="socks5://127.0.0.1:9050" go-sendxmpp --http-upload file.txt user@example.org

TIPS

USAGE BY ROOT

In general it's a good advice to only perform commands as root when it is strictly necessary. To be able to send the output from commands, that need to be performed as root, with go-sendxmpp without invoking go-sendxmpp by root sudo can be used.

In this example there is a user sendxmpp with a go-sendxmpp config in its $HOME:

# command-that-requires-root|sudo -H -u sendxmpp go-sendxmpp me@example.org

SHELL COMPLETIONS

ZSH

There are no shell completions yet (contributions welcome) but for zsh it is possible to automatically create completions from --help which might work good enough.

Just place the following in your ~/.zshrc or ~/.zshrc.local:

compdef _gnu_generic go-sendxmpp

FISH

There are no shell completions yet, but FISH can generate them from the man page with following command:

fish_update_completions

CHAT

Feel free to join https://join.jabber.network/#go-sendxmpp@chat.mdosch.de?join.

AUTHOR

Written by Martin Dosch.

REPORTING BUGS

Report bugs at https://salsa.debian.org/mdosch/go-sendxmpp/issues.

Copyright (c) Martin Dosch License: BSD 2-clause License

SEE ALSO

go-sendxmpp(5), xmppc(1), sendxmpp(1)

  1. December 2024
  2. go-sendxmpp(1)
go-sendxmpp-0.14.1/man/go-sendxmpp.1.ronn000066400000000000000000000202711474502115300201130ustar00rootroot00000000000000go-sendxmpp(1) -- A tool to send messages to an XMPP contact or MUC. ==== ## SYNOPSIS `go-sendxmpp [-cdilnt] [-a value] [--allow-plain] [--anonymous] [--fast-invalidate] [--fast-off] [-f value] [--headline] [--help] [-h value] [-j value] [-m value] [--muc-password value] [--no-sasl-upgrade] [--oob-file value] [--ox] [--ox-delete-nodes] [--ox-genprivkey-rsa] [--ox-genprivkey-x25519] [--ox-import-privkey value] [--ox-passphrase value] [-p value] [--raw] [--scram-mech-pinning value] [--ssdp-off] [-s value] [--suppress-root-warning] [--timeout value] [--tls-version value] [-u value] [--version] [recipients…]` ## DESCRIPTION A tool to send messages to an XMPP contact or MUC inspired by `sendxmpp`. You can either pipe a programs output to `go-sendxmpp`, write in your terminal (put `^D` in a new line to finish) or send the input from a file (`-m` or `--message`). The account data is expected at `~/.config/go-sendxmpp/config` (preferred), `~/.config/go-sendxmpp/sendxmpprc` (deprecated) `~/.sendxmpprc` (for compatibility with the original perl sendxmpp) if no other configuration file location is specified with `-f` or `--file`. ## OPTIONS * `-a`, `--alias`=[]: Set alias/nickname for chatrooms. * `--allow-plain`: Allow PLAIN authentication. Note that this setting has no effect if there was a successful connection using a SCRAM authentication mechanism before. In that case PLAIN is not allowed to prevent downgrades by a man-in-the-middle attack. * `--anonymous`: Use anonymous authentication. Specify the the target server by using the flag `-u` or `--username`. Username is used to specify the server to be able to override the server by using `-j` or `--jserver` in cases where the service (e.g. anon.example.org) is served by another server (e.g. xmpp.example.org) but no SRV records are set up. * `-c`, `--chatroom`=[]: Send message to a chatroom. * `-d`, `--debug`: Show debugging info. * `--fast-invalidate`: Invalidate XEP-0484: Fast Authentication Streamlining Tokens. The current FAST token will be invalidated and a new one will be requested. If used together with `--fast-off` the FAST token will be invalidated and the stored FAST token deleted. * `--fast-off`: Disable XEP-0484: Fast Authentication Streamlining Tokens. Deletes the stored FAST token when used together with `--fast-invalidate`. * `-f`, `--file`=[]: Set configuration file. (Default: ~/.config/go-sendxmpp/config) * `--headline`: Send message as type headline. * `--help`: Show help. * `-h`, `--http-upload=`[]: Send a file via http-upload. Can be invoked several times to upload multiple files. * `-i`, `--interactive`: Interactive mode (for use with e.g. `tail -f`). * `-j`, `--jserver`=[]: XMPP server address. * `-l`, `--listen`: Listen for messages and print them to stdout. If JIDs are specified only messages from those contacts are shown. If no JIDs are specified all received messages will be shown. * `-m`, `--message`=[]: Set file including the message. * `--muc-password`=[]: Password for password protected MUCs. * `--no-sasl-upgrade`: Disable XEP-0480: SASL Upgrade Tasks. * `-n`, `--no-tls-verify`: Skip verification of TLS certificates (not recommended). * `--oob-file`=[]: URL to send a file as out of band data. * `--ox`: Use "OpenPGP for XMPP" encryption (experimental). Ox in go-sendxmpp only supports sending encrypted 1-1 messages. Sending to groupchats and sending encrypted files is not supported. There is no check whether the recipients key is trusted as there is no local keyring used. Go-sendxmpp just uses the most recent key that is provided via pubsub and checks that it is not expired. As a user facing client a notification would be shown that a new key is available and ask the user whether to use the new key or stick to the old one. As go-sendxmpp is usually used in scripts it just accepts the new key to prevent the user from missing a new notification due to changed keys. * `--ox-delete-nodes`: Delete existing OpenPGP nodes on the server. * `--ox-genprivkey-rsa`: Generate a private OpenPGP key (RSA 4096 bit) for the configured account (via config file or `-u` and `-p`) and publish the corresponding public key. Go-sendxmpp will save the key in `$XDG_DATA_HOME/go-sendxmpp/oxprivkeys` or `$HOME/.local/share/go-sendxmpp/oxprivkeys`. To protect the key a passphrase might be set using `--ox-passphrase` while generating the key. If there is an existing private key for "OpenPGP for XMPP" created by another client (e.g. profanity) it might be imported using `--ox-import-privkey`. * `--ox-genprivkey-x25519`: Generate a private OpenPGP key (X25519) for the configured account (via config file or `-u` and `-p`) and publish the corresponding public key. Go-sendxmpp will save the key in `$XDG_DATA_HOME/go-sendxmpp/oxprivkeys` or `$HOME/.local/share/go-sendxmpp/oxprivkeys`. To protect the key a passphrase might be set using `--ox-passphrase` while generating the key. If there is an existing private key for "OpenPGP for XMPP" created by another client (e.g. profanity) it might be imported using `--ox-import-privkey`. * `--ox-import-privkey`=[]: Import an existing private OpenPGP key. * `--ox-passphrase`=[]: Passphrase for locking and unlocking the private OpenPGP key. * `-p`, `--password`=[]: Password for XMPP account. * `--raw`: Send raw XML. To send raw XML to a contact as normal chat message no contact must be specified. To send raw XML to a MUC you have to specify the MUC via `-c` and go-sendxmpp will join the MUC. * `--scram-mech-pinning=[]`: Enforce the use of a certain SCRAM authentication mechanism. Currently go-sendxmpp supports **SCRAM-SHA-1**, **SCRAM-SHA-1-PLUS**, **SCRAM-SHA-256**, **SCRAM-SHA-256-PLUS**, **SCRAM-SHA-512** and **SCRAM-SHA-512-PLUS**. You should know what you are doing when using this setting and make sure the chosen mechanism is supported by the server. If not set, go-sendxmpp will use XEP-0474 to prevent downgrade attacks (needs server support and requires a SCRAM authentication mechanism). * `--ssdp-off`: Disable XEP-0474: SASL SCRAM Downgrade Protection. * `-s`, `--subject`=[]: Set message subject. * `--suppress-root-warning`: Suppress warning when run as root. * `--timeout=`[]: Connection timeout in seconds. (Default: 10) * `-t`, `--tls`: Use direct TLS. * `--tls-version`=[]: Minimal TLS version. 10 (TLSv1.0), 11 (TLSv1.1), 12 (TLSv1.2), 13 (TLSv1.3) (Default: 12) * `-u`, `--username`=[]: Username for XMPP account (JID). * `--version`: Show version information. ## ENVIRONMENT VARIABLES ### HTTP_PROXY A SOCKS5 proxy can be used by setting the environment variable `HTTP_PROXY`. This feature is considered experimental and there is no guarantee that there won't be any connections not using the proxy although it didn't happen during testing. ``` HTTP_PROXY="socks5://127.0.0.1:9050" go-sendxmpp --http-upload file.txt user@example.org ``` ## TIPS ### USAGE BY ROOT In general it's a good advice to only perform commands as root when it is strictly necessary. To be able to send the output from commands, that need to be performed as root, with go-sendxmpp without invoking go-sendxmpp by root sudo can be used. In this example there is a user **sendxmpp** with a go-sendxmpp config in its `$HOME`: ``` # command-that-requires-root|sudo -H -u sendxmpp go-sendxmpp me@example.org ``` ## SHELL COMPLETIONS ### ZSH There are no shell completions yet (contributions welcome) but for zsh it is possible to automatically create completions from `--help` which might work good enough. Just place the following in your `~/.zshrc` or `~/.zshrc.local`: ``` compdef _gnu_generic go-sendxmpp ``` ### FISH There are no shell completions yet, but FISH can generate them from the man page with following command: ``` fish_update_completions ``` ## CHAT Feel free to join [https://join.jabber.network/#go-sendxmpp@chat.mdosch.de?join](https://join.jabber.network/#go-sendxmpp@chat.mdosch.de?join). ## AUTHOR Written by Martin Dosch. ## REPORTING BUGS Report bugs at [https://salsa.debian.org/mdosch/go-sendxmpp/issues](https://salsa.debian.org/mdosch/go-sendxmpp/issues). ## COPYRIGHT Copyright (c) Martin Dosch License: BSD 2-clause License ## SEE ALSO go-sendxmpp(5), xmppc(1), sendxmpp(1) go-sendxmpp-0.14.1/man/go-sendxmpp.5000066400000000000000000000030041474502115300171370ustar00rootroot00000000000000.\" generated with Ronn-NG/v0.9.1 .\" http://github.com/apjanke/ronn-ng/tree/0.9.1 .TH "GO\-SENDXMPP" "5" "November 2024" "" .SH "NAME" \fBgo\-sendxmpp\fR \- A tool to send messages to an XMPP contact or MUC\. .SH "LOCATION" The account data is expected at \fB~/\.config/go\-sendxmpp/config\fR (preferred), \fB~/\.config/go\-sendxmpp/sendxmpprc\fR (deprecated) or \fB~/\.sendxmpprc\fR (for compatibility with the original perl sendxmpp) if no other configuration file location is specified with \-f or \-\-file\. The configuration file is expected to be in the following format: .SH "FORMAT" username: [\fIyour_jid\fR] .br jserver: [\fIjabber_server\fR] .br port: [\fIjabber_port\fR] .br password: [\fIyour_jabber_password\fR] .br eval_password: [\fIcommand_to_unlock_your_password\fR] .br alias: [\fIyour_alias\fR] .SH "REQUIRED SETTINGS" If all necessary settings are supplied as command line arguments no config file is needed at all\. Setting \fBjserver\fR and \fBport\fR might not be necessary depending on the used server\. .br You should either use a password manager and the setting \fBeval_password\fR or add your password in plaintext to the config file with the setting \fBpassword\fR\. Please be careful with \fBeval_password\fR as any command put there will be executed\. .SH "AUTHOR" Written by Martin Dosch\. .SH "REPORTING BUGS" Report bugs at \fIhttps://salsa\.debian\.org/mdosch/go\-sendxmpp/issues\fR\. .SH "COPYRIGHT" Copyright (c) Martin Dosch License: BSD 2\-clause License .SH "SEE ALSO" go\-sendxmpp(1), sendxmpp(1) go-sendxmpp-0.14.1/man/go-sendxmpp.5.html000066400000000000000000000116631474502115300201140ustar00rootroot00000000000000 go-sendxmpp(5) - A tool to send messages to an XMPP contact or MUC.
  1. go-sendxmpp(5)
  2. go-sendxmpp(5)

NAME

go-sendxmpp - A tool to send messages to an XMPP contact or MUC.

LOCATION

The account data is expected at ~/.config/go-sendxmpp/config (preferred), ~/.config/go-sendxmpp/sendxmpprc (deprecated) or ~/.sendxmpprc (for compatibility with the original perl sendxmpp) if no other configuration file location is specified with -f or --file. The configuration file is expected to be in the following format:

FORMAT

username: [your_jid]
jserver: [jabber_server]
port: [jabber_port]
password: [your_jabber_password]
eval_password: [command_to_unlock_your_password]
alias: [your_alias]

REQUIRED SETTINGS

If all necessary settings are supplied as command line arguments no config file is needed at all. Setting jserver and port might not be necessary depending on the used server.
You should either use a password manager and the setting eval_password or add your password in plaintext to the config file with the setting password. Please be careful with eval_password as any command put there will be executed.

AUTHOR

Written by Martin Dosch.

REPORTING BUGS

Report bugs at https://salsa.debian.org/mdosch/go-sendxmpp/issues.

Copyright (c) Martin Dosch License: BSD 2-clause License

SEE ALSO

go-sendxmpp(1), sendxmpp(1)

  1. November 2024
  2. go-sendxmpp(5)
go-sendxmpp-0.14.1/man/go-sendxmpp.5.ronn000066400000000000000000000025321474502115300201170ustar00rootroot00000000000000go-sendxmpp(5) -- A tool to send messages to an XMPP contact or MUC. ==== ## LOCATION The account data is expected at `~/.config/go-sendxmpp/config` (preferred), `~/.config/go-sendxmpp/sendxmpprc` (deprecated) or `~/.sendxmpprc` (for compatibility with the original perl sendxmpp) if no other configuration file location is specified with -f or --file. The configuration file is expected to be in the following format: ## FORMAT username: [] jserver: [] port: [] password: [] eval_password: [] alias: [] ## REQUIRED SETTINGS If all necessary settings are supplied as command line arguments no config file is needed at all. Setting `jserver` and `port` might not be necessary depending on the used server. You should either use a password manager and the setting `eval_password` or add your password in plaintext to the config file with the setting `password`. Please be careful with `eval_password` as any command put there will be executed. ## AUTHOR Written by Martin Dosch. ## REPORTING BUGS Report bugs at [https://salsa.debian.org/mdosch/go-sendxmpp/issues](https://salsa.debian.org/mdosch/go-sendxmpp/issues). ## COPYRIGHT Copyright (c) Martin Dosch License: BSD 2-clause License ## SEE ALSO go-sendxmpp(1), sendxmpp(1) go-sendxmpp-0.14.1/ox.go000066400000000000000000000620121474502115300150160ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "encoding/base64" "fmt" "io" "log" "os" "runtime" "strings" "time" "github.com/ProtonMail/gopenpgp/v2/crypto" // MIT License "github.com/beevik/etree" // BSD-2-clause "github.com/xmppo/go-xmpp" // BSD-3-Clause ) func oxDeleteNodes(jid string, client *xmpp.Client, iqc chan xmpp.IQ) error { nodeListRequest := etree.NewDocument() nodeListRequest.WriteSettings.AttrSingleQuote = true query := nodeListRequest.CreateElement("query") query.CreateAttr("xmlns", nsDiscoItems) nlr, err := nodeListRequest.WriteToString() if err != nil { return fmt.Errorf("ox: delete nodes: failed to create node list request %w", err) } iqReply, err := sendIQ(client, iqc, jid, "get", nlr) if err != nil { return fmt.Errorf("ox: delete nodes: failure with node list request iq: %w", err) } nodeListReply := etree.NewDocument() err = nodeListReply.ReadFromBytes(iqReply.Query) if err != nil { return fmt.Errorf("ox: delete nodes: failed to read node list reply iq: %w", err) } query = nodeListReply.SelectElement("query") if query == nil { return fmt.Errorf("ox: error parsing iq reply") } items := query.SelectElements("item") if items == nil { return fmt.Errorf("ox: error parsing iq reply") } for _, item := range items { node := item.SelectAttr("node") if node == nil { continue } if !strings.Contains(node.Value, nsOx) { continue } deleteNodeRequest := etree.NewDocument() deleteNodeRequest.WriteSettings.AttrSingleQuote = true pubsub := deleteNodeRequest.CreateElement("pubsub") pubsub.CreateAttr("xmlns", nsPubsubOwner) del := pubsub.CreateElement("delete") del.CreateAttr("node", node.Value) dnr, err := deleteNodeRequest.WriteToString() if err != nil { continue } _, err = sendIQ(client, iqc, jid, "set", dnr) if err != nil { continue } } return nil } func oxDecrypt(m xmpp.Chat, client *xmpp.Client, iqc chan xmpp.IQ, user string, oxPrivKey *crypto.Key) (string, time.Time, error) { var cryptMsgByte []byte var err error sender := strings.Split(m.Remote, "/")[0] for _, r := range m.OtherElem { if r.XMLName.Space == nsOx { cryptMsgByte, err = base64.StdEncoding.DecodeString(r.InnerXML) if err != nil { return strError, time.Now(), err } break } } oxMsg := crypto.NewPGPMessage(cryptMsgByte) keyRing, err := crypto.NewKeyRing(oxPrivKey) if err != nil { return strError, time.Now(), err } senderKeyRing, err := oxGetPublicKeyRing(client, iqc, sender) if err != nil { return strError, time.Now(), err } decryptMsg, err := keyRing.Decrypt(oxMsg, senderKeyRing, crypto.GetUnixTime()) if err != nil { return strError, time.Now(), err } // Remove invalid code points. message := validUTF8(string(decryptMsg.Data)) doc := etree.NewDocument() err = doc.ReadFromString(message) if err != nil { return strError, time.Now(), err } signcrypt := doc.SelectElement("signcrypt") if signcrypt == nil { return strError, time.Now(), fmt.Errorf("ox: no signcrypt element") } to := signcrypt.SelectElement("to") if to == nil { return strError, time.Now(), fmt.Errorf("ox: no to element") } jid := to.SelectAttr("jid") if jid == nil { return strError, time.Now(), fmt.Errorf("ox: no jid attribute") } if strings.Split(jid.Value, "/")[0] != user { return strError, time.Now(), fmt.Errorf("ox: encrypted for wrong user") } timestamp := signcrypt.SelectElement("time") if timestamp == nil { return strError, time.Now(), fmt.Errorf("ox: no time element") } stamp := timestamp.SelectAttr("stamp") if stamp == nil { return strError, time.Now(), fmt.Errorf("ox: no stamp attribute") } msgStamp, err := time.Parse("2006-01-02T15:04:05Z0700", stamp.Value) if err != nil { return strError, time.Now(), err } payload := signcrypt.SelectElement("payload") if payload == nil { return strError, time.Now(), fmt.Errorf("ox: no payload element") } body := payload.SelectElement("body") if body == nil { return "", time.Now(), nil } return body.Text(), msgStamp, nil } func isOxMsg(m xmpp.Chat) bool { for _, r := range m.OtherElem { if r.XMLName.Space == nsOx { return true } } return false } func oxImportPrivKey(jid string, privKeyLocation string, client *xmpp.Client, iqc chan xmpp.IQ) error { xmppURI := "xmpp:" + jid buffer, err := readFile(privKeyLocation) if err != nil { return err } key, err := crypto.NewKey(buffer.Bytes()) if err != nil { key, err = crypto.NewKeyFromArmored(buffer.String()) if err != nil { keyDecoded, err := base64.StdEncoding.DecodeString(buffer.String()) if err != nil { return fmt.Errorf("ox: import privkey: failed to import private key: %w", err) } key, err = crypto.NewKey(keyDecoded) if err != nil { return fmt.Errorf("ox: import privkey: failed to import private key: %w", err) } } } entity := key.GetEntity() if entity.Identities[xmppURI] == nil { return fmt.Errorf("ox: key identity is not %s", xmppURI) } pk, err := key.GetPublicKey() if err != nil { return fmt.Errorf("ox: import privkey: failed to get public key associated to private key: %w", err) } pubKey, err := crypto.NewKey(pk) if err != nil { return fmt.Errorf("ox: import privkey: failed to get public key associated to private key: %w", err) } fingerprint := strings.ToUpper(pubKey.GetFingerprint()) _, err = oxRecvPublicKeys(client, iqc, jid, fingerprint) if err != nil { err = oxPublishPubKey(jid, client, iqc, pubKey) if err != nil { return fmt.Errorf("ox: import privkey: failed to publish public key: %w", err) } } location, err := oxGetPrivKeyLoc(jid) if err != nil { return fmt.Errorf("ox: import privkey: failed to determine private key location: %w", err) } keySerialized, err := key.Serialize() if err != nil { return fmt.Errorf("ox: import privkey: failed to serialize private key: %w", err) } err = oxStoreKey(location, base64.StdEncoding.EncodeToString(keySerialized)) if err != nil { log.Fatal(err) } pubKeyRing, err := oxGetPublicKeyRing(client, iqc, jid) if err == nil { pubKeys := pubKeyRing.GetKeys() for _, r := range pubKeys { if strings.ToUpper(r.GetFingerprint()) == fingerprint { return nil } } } err = oxPublishPubKey(jid, client, iqc, pubKey) if err != nil { return fmt.Errorf("ox: import privkey: failed to publish public key: %w", err) } return nil } func oxPublishPubKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, pubKey *crypto.Key) error { keyCreated := time.Now().UTC().Format("2006-01-02T15:04:05Z") fingerprint := strings.ToUpper(pubKey.GetFingerprint()) keySerialized, err := pubKey.Serialize() if err != nil { return fmt.Errorf("ox: publish pubkey: failed to serialize pubkey: %w", err) } pubKeyBase64 := base64.StdEncoding.EncodeToString(keySerialized) root := etree.NewDocument() root.WriteSettings.AttrSingleQuote = true pubsub := root.CreateElement("pubsub") pubsub.CreateAttr("xmlns", nsPubsub) publish := pubsub.CreateElement("publish") publish.CreateAttr("node", nsOxPubKeys+":"+fingerprint) item := publish.CreateElement("item") item.CreateAttr("id", keyCreated) pubkey := item.CreateElement("pubkey") pubkey.CreateAttr("xmlns", nsOx) data := pubkey.CreateElement("data") data.CreateText(pubKeyBase64) publishoptions := pubsub.CreateElement("publish-options") x := publishoptions.CreateElement("x") x.CreateAttr("xmlns", nsJabberData) x.CreateAttr("type", "submit") field := x.CreateElement("field") field.CreateAttr("var", "FORM_TYPE") field.CreateAttr("type", "hidden") value := field.CreateElement("value") value.CreateText(pubsubPubOptions) field = x.CreateElement("field") field.CreateAttr("var", "pubsub#access_model") value = field.CreateElement("value") value.CreateText("open") xmlstring, err := root.WriteToString() if err != nil { return fmt.Errorf("ox: publish pubkey: failed to create publish public key iq xml: %w", err) } iqReply, err := sendIQ(client, iqc, jid, "set", xmlstring) if err != nil { return fmt.Errorf("ox: publish pubkey: iq failure publishing public key: %w", err) } if iqReply.Type != strResult { return fmt.Errorf("ox: error while publishing public key") } ownPubKeyRingFromPubsub, err := oxRecvPublicKeys(client, iqc, jid, fingerprint) if err != nil { return fmt.Errorf("ox: couldn't successfully verify public key upload") } ownPubKeyFromPubsub := ownPubKeyRingFromPubsub.GetKeys()[0] ownPubKeyFromPubsubSerialized, err := ownPubKeyFromPubsub.Serialize() if err != nil { return fmt.Errorf("ox: couldn't successfully verify public key upload") } if pubKeyBase64 != base64.StdEncoding.EncodeToString(ownPubKeyFromPubsubSerialized) { return fmt.Errorf("ox: couldn't successfully verify public key upload") } root = etree.NewDocument() root.WriteSettings.AttrSingleQuote = true pubsub = root.CreateElement("pubsub") pubsub.CreateAttr("xmlns", nsPubsub) publish = pubsub.CreateElement("publish") publish.CreateAttr("node", nsOxPubKeys) item = publish.CreateElement("item") pubkeyslist := item.CreateElement("public-keys-list") pubkeyslist.CreateAttr("xmlns", nsOx) pubkeymeta := pubkeyslist.CreateElement("pubkey-metadata") pubkeymeta.CreateAttr("v4-fingerprint", fingerprint) pubkeymeta.CreateAttr("date", keyCreated) publishoptions = pubsub.CreateElement("publish-options") x = publishoptions.CreateElement("x") x.CreateAttr("xmlns", nsJabberData) x.CreateAttr("type", "submit") field = x.CreateElement("field") field.CreateAttr("var", "FORM_TYPE") field.CreateAttr("type", "hidden") value = field.CreateElement("value") value.CreateText(pubsubPubOptions) field = x.CreateElement("field") field.CreateAttr("var", "pubsub#access_model") value = field.CreateElement("value") value.CreateText("open") xmlstring, err = root.WriteToString() if err != nil { return fmt.Errorf("ox: publish pubkey: failed to create xml for iq to publish public key list: %w", err) } iqReply, err = sendIQ(client, iqc, jid, "set", xmlstring) if err != nil { return fmt.Errorf("ox: publish pubkey: iq failure publishing public key list: %w", err) } if iqReply.Type != strResult { return fmt.Errorf("ox: couldn't publish public key list") } return nil } func oxGetPrivKeyLoc(jid string) (string, error) { dataDir, err := getDataPath(fsFriendlyJid(jid), true) if err != nil { return strError, fmt.Errorf("ox: get privkey location: %w", err) } oldDataDir, err := getDataPath("oxprivkeys/", false) if err != nil { return strError, fmt.Errorf("ox: get privkey location: %w", err) } // TODO: Remove handling of oldDataFile in a later version when it's very likely that there are no // more versions in use using the oldDataFile (<0.8.3). oldDataFile := oldDataDir + base64.StdEncoding.EncodeToString([]byte(jid)) oldDataFile2 := oldDataDir + strings.ReplaceAll(jid, "@", "_at_") oldDataFile3 := oldDataDir + fsFriendlyJid(jid) dataFile := dataDir + "oxprivkey" if _, err := os.Stat(oldDataFile); err == nil { err := os.Rename(oldDataFile, dataFile) if err != nil { return dataFile, err } } if _, err := os.Stat(oldDataFile2); err == nil { err := os.Rename(oldDataFile2, dataFile) if err != nil { return dataFile, err } } if _, err := os.Stat(oldDataFile3); err == nil { err := os.Rename(oldDataFile3, dataFile) if err != nil { return dataFile, err } } dir, err := os.Open(oldDataDir) if err == nil { _, err = dir.ReadDir(1) // Delete old data dir if empty. if err == io.EOF { err = os.Remove(oldDataDir) if err != nil { fmt.Printf("oxGetPrivKeyLoc: failed to delete old private key location: %v\n", err) } } } return dataFile, nil } func oxGetPubKeyLoc(fingerprint string) (string, error) { dataDir, err := getDataPath("oxpubkeys/", true) if err != nil { return strError, fmt.Errorf("ox: get pubkey location: %w", err) } dataFile := dataDir + fingerprint return dataFile, nil } func oxGetPrivKey(jid string, passphrase string) (*crypto.Key, error) { dataFile, err := oxGetPrivKeyLoc(jid) if err != nil { log.Fatal(err) } keyBuffer, err := readFile(dataFile) if err != nil { log.Fatal(err) } keyString := keyBuffer.String() decodedPrivKey, err := base64.StdEncoding.DecodeString(keyString) if err != nil { return nil, fmt.Errorf("ox: get privkey: failed to decode private key: %w", err) } key, err := crypto.NewKey(decodedPrivKey) if err != nil { return nil, fmt.Errorf("ox: get privkey: failed to decode private key: %w", err) } if passphrase != "" { key, err = key.Unlock([]byte(passphrase)) if err != nil { log.Fatal("ox: couldn't unlock private key.") } } isLocked, err := key.IsLocked() if err != nil { return nil, fmt.Errorf("ox: get privkey: failed to check whether private key is locked: %w", err) } if isLocked { log.Fatal("ox: private key is locked.") } if key.IsExpired() { return nil, fmt.Errorf("ox: private key is expired: %s", key.GetFingerprint()) } return key, nil } func oxStoreKey(location string, key string) error { var file *os.File file, err := os.Create(location) if err != nil { return fmt.Errorf("ox: store key: failed to create key location: %w", err) } if runtime.GOOS != "windows" { _ = file.Chmod(os.FileMode(defaultFileRights)) } else { _ = file.Chmod(os.FileMode(defaultFileRightsWin)) } _, err = file.Write([]byte(key)) if err != nil { return fmt.Errorf("ox: store key: failed to write key to file: %w", err) } err = file.Close() if err != nil { fmt.Println("error while closing file:", err) } return nil } func oxGenPrivKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, passphrase string, keyType string, ) error { xmppURI := "xmpp:" + jid key, err := crypto.GenerateKey(xmppURI, "", keyType, defaultRSABits) if err != nil { return fmt.Errorf("ox: generate privkey: failed to generate private key: %w", err) } if passphrase != "" { key, err = key.Lock([]byte(passphrase)) if err != nil { return fmt.Errorf("ox: generate privkey: failed to lock key with passphrase: %w", err) } } keySerialized, err := key.Serialize() if err != nil { return fmt.Errorf("ox: generate privkey: failed to serialize private key: %w", err) } location, err := oxGetPrivKeyLoc(jid) if err != nil { return fmt.Errorf("ox: generate privkey: failed to get private key location: %w", err) } err = oxStoreKey(location, base64.StdEncoding.EncodeToString(keySerialized)) if err != nil { log.Fatal(err) } decodedPubKey, err := key.GetPublicKey() if err != nil { return fmt.Errorf("ox: generate privkey: failed to decode public key: %w", err) } pubKey, err := crypto.NewKey(decodedPubKey) if err != nil { return fmt.Errorf("ox: generate privkey: failed to decode public key: %w", err) } err = oxPublishPubKey(jid, client, iqc, pubKey) if err != nil { return fmt.Errorf("ox: generate privkey: failed to publish public key: %w", err) } return nil } func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, fingerprint string) (*crypto.KeyRing, error) { opkr := etree.NewDocument() opkr.WriteSettings.AttrSingleQuote = true opkrPs := opkr.CreateElement("pubsub") opkrPs.CreateAttr("xmlns", nsPubsub) opkrPsItems := opkrPs.CreateElement("items") opkrPsItems.CreateAttr("node", nsOxPubKeys+":"+fingerprint) opkrPsItems.CreateAttr("max_items", "1") opkrString, err := opkr.WriteToString() if err != nil { return nil, fmt.Errorf("ox: receive public keys: failed to generate xml for public key request: %w", err) } oxPublicKey, err := sendIQ(client, iqc, recipient, "get", opkrString) if err != nil { return nil, fmt.Errorf("ox: receive public keys: iq error requesting public keys: %w", err) } if oxPublicKey.Type != strResult { return nil, fmt.Errorf("ox: error while requesting public key for %s", recipient) } oxPublicKeyXML := etree.NewDocument() err = oxPublicKeyXML.ReadFromBytes(oxPublicKey.Query) if err != nil { return nil, fmt.Errorf("ox: receive public keys: failed parsing iq reply to public key request: %w", err) } keyring, err := crypto.NewKeyRing(nil) if err != nil { return nil, fmt.Errorf("ox: receive public keys: failed reading public key: %w", err) } oxPublicKeyXMLPubsub := oxPublicKeyXML.SelectElement("pubsub") if oxPublicKeyXMLPubsub == nil { return nil, fmt.Errorf("ox: no pubsub element in reply to public key request") } oxPublicKeyXMLItems := oxPublicKeyXMLPubsub.SelectElement("items") if oxPublicKeyXMLItems == nil { return nil, fmt.Errorf("ox: no items element in reply to public key request") } oxPublicKeyXMLItem := oxPublicKeyXMLItems.SelectElement("item") if oxPublicKeyXMLItem == nil { return nil, fmt.Errorf("ox: no item element in reply to public key request") } oxPublicKeyXMLPubkeys := oxPublicKeyXMLItem.SelectElements("pubkey") for _, r := range oxPublicKeyXMLPubkeys { data := r.SelectElement("data") if data == nil { continue } decodedPubKey, err := base64.StdEncoding.DecodeString(data.Text()) if err != nil { return nil, fmt.Errorf("ox: receive public keys: failed to decode public key: %w", err) } key, err := crypto.NewKey(decodedPubKey) if err != nil { return nil, fmt.Errorf("ox: receive public keys: failed to decode public key: %w", err) } if key.IsExpired() { return nil, fmt.Errorf("ox: key is expired: %s", fingerprint) } err = keyring.AddKey(key) if err != nil { return nil, fmt.Errorf("ox: receive public keys: failed adding public key to keyring: %w", err) } } return keyring, nil } func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string) (*crypto.KeyRing, error) { publicKeyRing, err := crypto.NewKeyRing(nil) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to create a new keyring: %w", err) } oxPubKeyListReq := etree.NewDocument() oxPubKeyListReq.WriteSettings.AttrSingleQuote = true oxPubKeyListReqPs := oxPubKeyListReq.CreateElement("pubsub") oxPubKeyListReqPs.CreateAttr("xmlns", nsPubsub) oxPubKeyListReqPsItems := oxPubKeyListReqPs.CreateElement("items") oxPubKeyListReqPsItems.CreateAttr("node", nsOxPubKeys) oxPubKeyListReqPsItems.CreateAttr("max_items", "1") opkl, err := oxPubKeyListReq.WriteToString() if err != nil { log.Fatal(err) } oxPublicKeyList, err := sendIQ(client, iqc, recipient, "get", opkl) if err != nil { log.Fatal(err) } if oxPublicKeyList.Type != strResult { return nil, fmt.Errorf("ox: error while requesting public openpgp keys for %s", recipient) } oxPubKeyListXML := etree.NewDocument() err = oxPubKeyListXML.ReadFromBytes(oxPublicKeyList.Query) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to parse answer to public key list request: %w", err) } pubKeyRingID := "none" newestKey, err := time.Parse(time.RFC3339, "1900-01-01T00:00:00Z") if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to set time for newest key to 1900-01-01: %w", err) } oxPubKeyListXMLPubsub := oxPubKeyListXML.SelectElement("pubsub") if oxPubKeyListXMLPubsub == nil { return nil, fmt.Errorf("ox: no pubsub element in public key list") } oxPubKeyListXMLPubsubItems := oxPubKeyListXMLPubsub.SelectElement("items") if oxPubKeyListXMLPubsubItems == nil { return nil, fmt.Errorf("ox: no items element in public key list") } oxPubKeyListXMLPubsubItemsItem := oxPubKeyListXMLPubsubItems.SelectElement("item") if oxPubKeyListXMLPubsubItemsItem == nil { return nil, fmt.Errorf("ox: no item element in public key list") } oxPubKeyListXMLPubsubItemsItemPkl := oxPubKeyListXMLPubsubItemsItem.SelectElement("public-keys-list") if oxPubKeyListXMLPubsubItemsItemPkl == nil { return nil, fmt.Errorf("ox: no public-keys-list element") } oxPubKeyListXMLPubsubItemsItemPklPm := oxPubKeyListXMLPubsubItemsItemPkl.SelectElements("pubkey-metadata") for _, r := range oxPubKeyListXMLPubsubItemsItemPklPm { date := r.SelectAttr("date") if date == nil { continue } fingerprint := r.SelectAttr("v4-fingerprint") if fingerprint == nil { continue } keyDate, err := time.Parse(time.RFC3339, date.Value) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to parse time stamp for key: %w", err) } if keyDate.After(newestKey) { newestKey = keyDate pubKeyRingID = fingerprint.Value } } if pubKeyRingID == "none" { return nil, fmt.Errorf("ox: server didn't provide public key fingerprints for %s", recipient) } pubKeyRingLocation, err := oxGetPubKeyLoc(pubKeyRingID) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to get public key ring location: %w", err) } pubKeyReadXML := etree.NewDocument() err = pubKeyReadXML.ReadFromFile(pubKeyRingLocation) if err == nil { date := pubKeyReadXML.SelectElement("date") if date != nil { savedKeysDate, err := time.Parse(time.RFC3339, date.Text()) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to parse time for saved key: %w", err) } if !savedKeysDate.Before(newestKey) { pubKeys := pubKeyReadXML.SelectElements("pubkey") if pubKeys == nil { return nil, fmt.Errorf("ox: couldn't read public keys from cache") } for _, r := range pubKeys { keyByte, err := base64.StdEncoding.DecodeString(r.Text()) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to decode saved key: %w", err) } key, err := crypto.NewKey(keyByte) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to parse saved key: %w", err) } if !key.IsExpired() { err = publicKeyRing.AddKey(key) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to add key to public keyring: %w", err) } } } if publicKeyRing.CanEncrypt() { return publicKeyRing, nil } } } } pubKeyRing, err := oxRecvPublicKeys(client, iqc, recipient, pubKeyRingID) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to get public keyring: %w", err) } pubKeySaveXML := etree.NewDocument() date := pubKeySaveXML.CreateElement("date") date.SetText(newestKey.Format(time.RFC3339)) for _, key := range pubKeyRing.GetKeys() { keySerialized, err := key.Serialize() if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to serialize key: %w", err) } saveKey := pubKeySaveXML.CreateElement("pubkey") saveKey.SetText(base64.StdEncoding.EncodeToString(keySerialized)) } err = pubKeySaveXML.WriteToFile(pubKeyRingLocation) if err != nil { return nil, fmt.Errorf("ox: get public keyring: failed to create xml for saving public key: %w", err) } return pubKeyRing, nil } func oxEncrypt(client *xmpp.Client, oxPrivKey *crypto.Key, recipient string, keyRing crypto.KeyRing, message string, subject string) (string, error) { if message == "" { return "", nil } privKeyRing, err := crypto.NewKeyRing(oxPrivKey) if err != nil { return strError, fmt.Errorf("ox: encrypt: failed to create private keyring: %w", err) } ownJid := strings.Split(client.JID(), "/")[0] if recipient != ownJid { opk, err := oxPrivKey.GetPublicKey() if err == nil { ownKey, _ := crypto.NewKey(opk) _ = keyRing.AddKey(ownKey) } } oxCryptMessage := etree.NewDocument() oxCryptMessage.WriteSettings.AttrSingleQuote = true oxCryptMessageSc := oxCryptMessage.CreateElement("signcrypt") oxCryptMessageSc.CreateAttr("xmlns", nsOx) oxCryptMessageScTo := oxCryptMessageSc.CreateElement("to") oxCryptMessageScTo.CreateAttr("jid", recipient) oxCryptMessageScTime := oxCryptMessageSc.CreateElement("time") oxCryptMessageScTime.CreateAttr("stamp", time.Now().UTC().Format("2006-01-02T15:04:05Z")) oxCryptMessageScRpad := oxCryptMessageSc.CreateElement("rpad") oxCryptMessageScRpad.CreateText(getRpad(len(message))) oxCryptMessageScPayload := oxCryptMessageSc.CreateElement("payload") if subject != "" { oxCryptMessageScPayloadSub := oxCryptMessageScPayload.CreateElement("subject") oxCryptMessageScPayloadSub.CreateText(subject) } oxCryptMessageScPayloadBody := oxCryptMessageScPayload.CreateElement("body") oxCryptMessageScPayloadBody.CreateAttr("xmlns", nsJabberClient) oxCryptMessageScPayloadBody.CreateText(message) ocm, err := oxCryptMessage.WriteToString() if err != nil { return strError, fmt.Errorf("ox: encrypt: failed to create xml for ox crypt message: %w", err) } plainMessage := crypto.NewPlainMessage([]byte(ocm)) pgpMessage, err := keyRing.Encrypt(plainMessage, privKeyRing) if err != nil { return strError, fmt.Errorf("ox: encrypt: failed to create pgp message: %w", err) } om := etree.NewDocument() om.WriteSettings.AttrSingleQuote = true omMessage := om.CreateElement("message") omMessage.CreateAttr("to", recipient) omMessage.CreateAttr("id", getID()) omMessageStore := omMessage.CreateElement("store") omMessageStore.CreateAttr("xmlns", nsHints) omMessageEme := omMessage.CreateElement("encryption") omMessageEme.CreateAttr("xmlns", nsEme) omMessageEme.CreateAttr("namespace", nsOx) omMessageOpgp := omMessage.CreateElement("openpgp") omMessageOpgp.CreateAttr("xmlns", nsOx) omMessageOpgp.CreateText(base64.StdEncoding.EncodeToString(pgpMessage.Data)) omMessageBody := omMessage.CreateElement("body") omMessageBody.CreateText(oxAltBody) oms, err := om.WriteToString() if err != nil { return strError, fmt.Errorf("ox: encrypt: failed to create xml for ox message: %w", err) } return oms, nil } go-sendxmpp-0.14.1/parseconfig.go000066400000000000000000000103561474502115300166740ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "bufio" "fmt" "log" "os" "os/exec" "os/user" "runtime" "strconv" "strings" ) func findConfig() (string, error) { // Get the current user. curUser, err := user.Current() if err != nil { return "", fmt.Errorf("find config: failed to get current user: %w", err) } // Get home directory. home := curUser.HomeDir if home == "" { return "", fmt.Errorf("find config: no home directory found") } osConfigDir := os.Getenv("$XDG_CONFIG_HOME") if osConfigDir == "" { osConfigDir = home + "/.config" } configFiles := [3]string{ osConfigDir + "/go-sendxmpp/config", osConfigDir + "/go-sendxmpp/sendxmpprc", home + "/.sendxmpprc", } for _, r := range configFiles { // Check that the config file is existing. _, err := os.Stat(r) if err == nil { return r, nil } } return "", fmt.Errorf("find config: no configuration file found") } // Opens the config file and returns the specified values // for username, server and port. func parseConfig(configPath string) (configuration, error) { var ( output configuration err error ) // Use $XDG_CONFIG_HOME/.config/go-sendxmpp/config, // $XDG_CONFIG_HOME/.config/go-sendxmpp/sendxmpprc or // ~/.sendxmpprc if no config path is specified. // Get systems user config path. if configPath == "" { configPath, err = findConfig() if err != nil { log.Fatal(err) } } // Only check file permissions if we are not running on windows. if runtime.GOOS != "windows" { info, err := os.Stat(configPath) if err != nil { log.Fatal(err) } // Check for file permissions. Must be 600, 640, 440 or 400. perm := info.Mode().Perm() permissions := strconv.FormatInt(int64(perm), 8) if permissions != "600" && permissions != "640" && permissions != "440" && permissions != "400" { return output, fmt.Errorf("parse config: wrong permissions for %s: %s instead of 400 (recommended), 440, 600 or 640", configPath, permissions) } } // Open config file. file, err := os.Open(configPath) if err != nil { return output, fmt.Errorf("parse config: failed to open config file: %w", err) } scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) // Read config file per line. for scanner.Scan() { if strings.HasPrefix(scanner.Text(), "#") { continue } column := strings.SplitN(scanner.Text(), " ", defaultConfigColumnSep) switch column[0] { case "username:": output.username = column[1] case "jserver:": output.jserver = column[1] case "password:": output.password = column[1] case "eval_password:": shell := os.Getenv("SHELL") if shell == "" { shell = "/bin/sh" } out, err := exec.Command(shell, "-c", column[1]).Output() if err != nil { file.Close() log.Fatal(err) } output.password = string(out) if output.password[len(output.password)-1] == '\n' { output.password = output.password[:len(output.password)-1] } case "port:": output.port = column[1] case "alias:": output.alias = column[1] default: // Try to parse legacy sendxmpp config files. if len(column) >= defaultConfigColumnSep { if strings.Contains(scanner.Text(), ";") { output.username = strings.Split(column[0], ";")[0] output.jserver = strings.Split(column[0], ";")[1] output.password = column[1] } else { output.username = strings.Split(column[0], ":")[0] if strings.Contains(output.username, "@") { jserver := strings.SplitAfter(output.username, "@")[1] if len(jserver) < defaultLenServerConf { log.Fatal("Couldn't parse config: ", column[0]) } output.jserver = jserver } output.password = column[1] } } } } // Check if the username is a valid JID output.username, err = MarshalJID(output.username) if err != nil { // Check whether only the local part was used by appending an @ and the // server part. output.username = output.username + "@" + output.jserver // Check if the username is a valid JID now output.username, err = MarshalJID(output.username) if err != nil { return output, fmt.Errorf("parse config: invalid username/JID: %s", output.username) } } file.Close() return output, err } go-sendxmpp-0.14.1/stanzahandling.go000066400000000000000000000127421474502115300174020ustar00rootroot00000000000000// Copyright Martin Dosch. // Use of this source code is governed by the BSD-2-clause // license that can be found in the LICENSE file. package main import ( "context" "encoding/xml" "fmt" "io" "log" "runtime" "time" "github.com/beevik/etree" // BSD-2-clause "github.com/xmppo/go-xmpp" // BSD-3-Clause ) func sendIQ(client *xmpp.Client, iqc chan xmpp.IQ, target string, iQtype string, content string) (xmpp.IQ, error) { var iq xmpp.IQ id := getID() c := make(chan xmpp.IQ, defaultBufferSize) go getIQ(id, c, iqc) _, err := client.RawInformation(client.JID(), target, id, iQtype, content) if err != nil { return iq, fmt.Errorf("send iq: failed to send iq: %w", err) } select { case iq = <-c: case <-time.After(60 * time.Second): return iq, fmt.Errorf("send iq: server didn't reply to IQ: %s", content) } return iq, nil } func getIQ(id string, c chan xmpp.IQ, iqc chan xmpp.IQ) { for { iq := <-iqc if iq.ID == id { c <- iq return } } } func rcvStanzas(client *xmpp.Client, ctx context.Context, iqc chan xmpp.IQ, msgc chan xmpp.Chat) { type messageError struct { XMLName xml.Name `xml:"message-error"` Text string `xml:"text"` } var me messageError var received interface{} r := make(chan interface{}, defaultBufferSize) e := make(chan error, defaultBufferSize) go func() { for { select { case <-ctx.Done(): return default: } rcv, err := client.Recv() if err != nil { e <- err } else { r <- rcv } } }() for { select { case <-ctx.Done(): return case err := <-e: switch err { case io.EOF, io.ErrUnexpectedEOF: return case nil: continue default: closeAndExit(client, fmt.Errorf("receive stanzas: %v", err)) return } case received = <-r: } switch v := received.(type) { case xmpp.Chat: if v.Type == "error" { for _, oe := range v.OtherElem { err := xml.Unmarshal([]byte(""+ oe.InnerXML+""), &me) if err == nil { fmt.Printf("%s: %s\n", v.Remote, me.Text) } } } msgc <- v case xmpp.IQ: switch v.Type { case "get": var xmlns *etree.Attr iq := etree.NewDocument() err := iq.ReadFromBytes(v.Query) if err != nil { log.Println("Couldn't parse IQ:", string(v.Query), err) } query := iq.SelectElement("query") if query != nil { xmlns = query.SelectAttr("xmlns") } if xmlns == nil { break } switch xmlns.Value { case nsDiscoInfo: root := etree.NewDocument() root.WriteSettings.AttrSingleQuote = true reply := root.CreateElement("iq") reply.CreateAttr("type", "result") reply.CreateAttr("from", client.JID()) reply.CreateAttr("to", v.From) reply.CreateAttr("id", v.ID) replyQuery := reply.CreateElement("query") replyQuery.CreateAttr("xmlns", nsDiscoInfo) identity := replyQuery.CreateElement("identity") identity.CreateAttr("category", "client") identity.CreateAttr("type", "bot") identity.CreateAttr("name", "go-sendxmpp") feat := replyQuery.CreateElement("feature") feat.CreateAttr("var", nsDiscoInfo) feat2 := replyQuery.CreateElement("feature") feat2.CreateAttr("var", nsVersion) xmlString, err := root.WriteToString() if err == nil { _, err = client.SendOrg(xmlString) if err != nil { log.Println(err) } } case nsVersion: root := etree.NewDocument() root.WriteSettings.AttrSingleQuote = true reply := root.CreateElement("iq") reply.CreateAttr("type", "result") reply.CreateAttr("from", client.JID()) reply.CreateAttr("to", v.From) reply.CreateAttr("id", v.ID) replyQuery := reply.CreateElement("query") replyQuery.CreateAttr("xmlns", nsVersion) rqName := replyQuery.CreateElement("name") rqName.CreateText("go-sendxmpp") rqVersion := replyQuery.CreateElement("version") rqVersion.CreateText(version) rqOS := replyQuery.CreateElement("os") rqOS.CreateText(runtime.GOOS) xmlString, err := root.WriteToString() if err == nil { _, err = client.SendOrg(xmlString) if err != nil { log.Println(err) } } default: root := etree.NewDocument() root.WriteSettings.AttrSingleQuote = true reply := root.CreateElement("iq") reply.CreateAttr("type", strError) reply.CreateAttr("from", client.JID()) reply.CreateAttr("to", v.From) reply.CreateAttr("id", v.ID) errorReply := reply.CreateElement(strError) errorReply.CreateAttr("type", "cancel") su := errorReply.CreateElement("service-unavailable") su.CreateAttr("xmlns", nsXMPPStanzas) xmlString, err := root.WriteToString() if err == nil { _, err = client.SendOrg(xmlString) if err != nil { log.Println(err) } } } case "set": root := etree.NewDocument() root.WriteSettings.AttrSingleQuote = true reply := root.CreateElement("iq") reply.CreateAttr("type", strError) reply.CreateAttr("from", client.JID()) reply.CreateAttr("to", v.From) reply.CreateAttr("id", v.ID) errorReply := reply.CreateElement(strError) errorReply.CreateAttr("type", "cancel") su := errorReply.CreateElement("service-unavailable") su.CreateAttr("xmlns", nsXMPPStanzas) xmlString, err := root.WriteToString() if err == nil { _, err = client.SendOrg(xmlString) if err != nil { log.Println(err) } } case "reply", strError: iqc <- v default: iqc <- v } } } }