├── .formatter.exs ├── test ├── test_helper.exs ├── support │ ├── simple.sh │ └── set_env.sh └── beam_notify_test.exs ├── .github └── dependabot.yml ├── NOTICE ├── .credo.exs ├── REUSE.toml ├── .gitignore ├── CHANGELOG.md ├── mix.exs ├── Makefile ├── .circleci └── config.yml ├── mix.lock ├── lib └── beam_notify.ex ├── LICENSES ├── CC0-1.0.txt ├── Apache-2.0.txt └── CC-BY-4.0.txt ├── README.md └── c_src └── beam_notify.c /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | ExUnit.start() 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: mix 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /test/support/simple.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # SPDX-FileCopyrightText: 2021 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | echo "This is simple.sh" 8 | 9 | $BEAM_NOTIFY Hello world 10 | -------------------------------------------------------------------------------- /test/support/set_env.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # SPDX-FileCopyrightText: 2021 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | echo "This is set_env.sh" 8 | 9 | export TEST_ENV_VAR=42 10 | 11 | $BEAM_NOTIFY 12 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | BEAMNotify is open-source software licensed under the Apache License, Version 2 | 2.0. 3 | 4 | Copyright holders include Ed Wildgoose and Frank Hunleth. 5 | 6 | Authoritative REUSE-compliant copyright and license metadata available at 7 | https://hex.pm/packages/beam_notify. 8 | -------------------------------------------------------------------------------- /.credo.exs: -------------------------------------------------------------------------------- 1 | # .credo.exs 2 | %{ 3 | configs: [ 4 | %{ 5 | name: "default", 6 | strict: true, 7 | checks: [ 8 | {Credo.Check.Refactor.MapInto, false}, 9 | {Credo.Check.Warning.LazyLogging, false}, 10 | {Credo.Check.Readability.LargeNumbers, only_greater_than: 86400}, 11 | {Credo.Check.Readability.ParenthesesOnZeroArityDefs, parens: true}, 12 | {Credo.Check.Readability.Specs, tags: []}, 13 | {Credo.Check.Readability.StrictModuleLayout, tags: []} 14 | ] 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /REUSE.toml: -------------------------------------------------------------------------------- 1 | version = 1 2 | 3 | [[annotations]] 4 | path = [ 5 | ".circleci/config.yml", 6 | ".credo.exs", 7 | ".formatter.exs", 8 | ".github/dependabot.yml", 9 | ".gitignore", 10 | "CHANGELOG.md", 11 | "NOTICE", 12 | "REUSE.toml", 13 | "mix.exs", 14 | "mix.lock" 15 | ] 16 | precedence = "aggregate" 17 | SPDX-FileCopyrightText = "None" 18 | SPDX-License-Identifier = "CC0-1.0" 19 | 20 | [[annotations]] 21 | path = [ 22 | "README.md" 23 | ] 24 | precedence = "aggregate" 25 | SPDX-FileCopyrightText = "2021 Frank Hunleth" 26 | SPDX-License-Identifier = "CC-BY-4.0" 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | beam_notify-*.tar 24 | 25 | 26 | # Temporary files for e.g. tests 27 | /tmp 28 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## v1.1.1 4 | 5 | * Fixes 6 | * Fix compilation on systems with Erlang installed in a directory with spaces 7 | 8 | ## v1.1.0 9 | 10 | This release fixes warnings when compiled with Elixir 1.15. It removes support 11 | for Elixir 1.9. 12 | 13 | ## v1.0.0 14 | 15 | This release has no changes except for the version number. 16 | 17 | ## v0.2.2 18 | 19 | * New features 20 | * Add `:mode` option for setting socket file permissions. Thanks to Ed 21 | Wildgoose for this feature. 22 | 23 | ## v0.2.1 24 | 25 | This release only cleans up Makefile prints and bumps dependencies. No code 26 | changes were made. 27 | 28 | ## v0.2.0 29 | 30 | * New features 31 | * Support for explicitly passing the socket path - this enables use in 32 | restricted environments where it's impossible or hard to pass parameters 33 | through environment variables 34 | * Reporting the environment is off by default. See the `:report_env` option 35 | * Default socket paths are obfuscated. This also removes OS-specific 36 | character-set issues and length limitations 37 | 38 | ## v0.1.0 39 | 40 | Initial release to hex. 41 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule BEAMNotify.MixProject do 2 | use Mix.Project 3 | 4 | @version "1.1.1" 5 | @source_url "https://github.com/nerves-networking/beam_notify" 6 | 7 | def project do 8 | [ 9 | app: :beam_notify, 10 | version: @version, 11 | elixir: "~> 1.10", 12 | start_permanent: Mix.env() == :prod, 13 | compilers: [:elixir_make | Mix.compilers()], 14 | make_targets: ["all"], 15 | make_clean: ["mix_clean"], 16 | make_error_message: "", 17 | deps: deps(), 18 | dialyzer: dialyzer(), 19 | docs: docs(), 20 | package: package(), 21 | description: description() 22 | ] 23 | end 24 | 25 | def application do 26 | [ 27 | extra_applications: [:logger] 28 | ] 29 | end 30 | 31 | def cli do 32 | [preferred_envs: %{docs: :docs, "hex.publish": :docs, "hex.build": :docs, credo: :test}] 33 | end 34 | 35 | defp description do 36 | "Send a message to the BEAM from a shell script" 37 | end 38 | 39 | defp package do 40 | %{ 41 | files: [ 42 | "CHANGELOG.md", 43 | "c_src/*.[ch]", 44 | "lib", 45 | "LICENSES/*", 46 | "Makefile", 47 | "mix.exs", 48 | "NOTICE", 49 | "README.md", 50 | "REUSE.toml" 51 | ], 52 | licenses: ["Apache-2.0"], 53 | links: %{ 54 | "GitHub" => @source_url, 55 | "REUSE Compliance" => 56 | "https://api.reuse.software/info/github.com/nerves-networking/beam_notify" 57 | } 58 | } 59 | end 60 | 61 | defp deps do 62 | [ 63 | {:elixir_make, "~> 0.6", runtime: false}, 64 | {:ex_doc, "~> 0.22", only: :docs, runtime: false}, 65 | {:dialyxir, "~> 1.4.1", only: :dev, runtime: false}, 66 | {:credo, "~> 1.2", only: :test, runtime: false} 67 | ] 68 | end 69 | 70 | defp dialyzer() do 71 | [ 72 | flags: [:missing_return, :extra_return, :unmatched_returns, :error_handling, :underspecs] 73 | ] 74 | end 75 | 76 | defp docs do 77 | [ 78 | extras: ["README.md", "CHANGELOG.md"], 79 | main: "readme", 80 | source_ref: "v#{@version}", 81 | source_url: @source_url, 82 | skip_undefined_reference_warnings_on: ["CHANGELOG.md"] 83 | ] 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Frank Hunleth 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | # Makefile for building port binaries 6 | # 7 | # Makefile targets: 8 | # 9 | # all/install build and install beam_notify 10 | # clean clean build products and intermediates 11 | # 12 | # Variables to override: 13 | # 14 | # MIX_APP_PATH path to the build directory 15 | # 16 | # CC C compiler 17 | # CROSSCOMPILE crosscompiler prefix, if any 18 | # CFLAGS compiler flags for compiling all C files 19 | # ERL_CFLAGS additional compiler flags for files using Erlang header files 20 | # ERL_EI_INCLUDE_DIR include path to ei.h (Required for crosscompile) 21 | # ERL_EI_LIBDIR path to libei.a (Required for crosscompile) 22 | # LDFLAGS linker flags for linking all binaries 23 | # ERL_LDFLAGS additional linker flags for projects referencing Erlang libraries 24 | # 25 | ifeq ($(MIX_APP_PATH),) 26 | calling_from_make: 27 | mix compile 28 | endif 29 | 30 | PREFIX = $(MIX_APP_PATH)/priv 31 | BUILD = $(MIX_APP_PATH)/obj 32 | 33 | # Set Erlang-specific compile and linker flags 34 | ERL_CFLAGS ?= -I"$(ERL_EI_INCLUDE_DIR)" 35 | ERL_LDFLAGS = -L"$(ERL_EI_LIBDIR)" -lei_st 36 | 37 | CFLAGS ?= -O2 -Wall -Wextra -Wno-unused-parameter -pedantic 38 | 39 | DEFAULT_TARGETS = $(PREFIX) $(PREFIX)/beam_notify 40 | 41 | # Enable for debug messages 42 | # CFLAGS += -DDEBUG 43 | 44 | all: install 45 | 46 | install: $(BUILD) $(PREFIX) $(DEFAULT_TARGETS) 47 | 48 | $(BUILD)/%.o: c_src/%.c 49 | @echo " CC $(notdir $@)" 50 | $(CC) -c $(ERL_CFLAGS) $(CFLAGS) -o $@ $< 51 | 52 | $(PREFIX)/beam_notify: $(BUILD)/beam_notify.o 53 | @echo " LD $(notdir $@)" 54 | $(CC) $^ $(ERL_LDFLAGS) $(LDFLAGS) -o $@ 55 | 56 | $(PREFIX) $(BUILD): 57 | mkdir -p $@ 58 | 59 | mix_clean: 60 | $(RM) $(PREFIX)/beam_notify \ 61 | $(BUILD)/*.o 62 | clean: 63 | mix clean 64 | 65 | format: 66 | astyle \ 67 | --style=kr \ 68 | --indent=spaces=4 \ 69 | --align-pointer=name \ 70 | --align-reference=name \ 71 | --convert-tabs \ 72 | --attach-namespaces \ 73 | --max-code-length=100 \ 74 | --max-instatement-indent=120 \ 75 | --pad-header \ 76 | --pad-oper \ 77 | c_src/*.c 78 | 79 | .PHONY: all clean mix_clean calling_from_make install format 80 | 81 | .SILENT: 82 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | latest: &latest 4 | pattern: "^1.19.*-erlang-28.*$" 5 | 6 | tags: &tags 7 | [ 8 | 1.19.3-erlang-28.1.1-alpine-3.22.2, 9 | 1.18.4-erlang-27.3.4.3-alpine-3.22.1, 10 | 1.17.3-erlang-27.2-alpine-3.20.3, 11 | 1.16.3-erlang-26.2.5-alpine-3.20.0, 12 | 1.15.7-erlang-26.2.1-alpine-3.18.4, 13 | 1.14.5-erlang-25.3.2-alpine-3.18.0, 14 | 1.13.4-erlang-24.3.4-alpine-3.15.3 15 | ] 16 | 17 | jobs: 18 | check-license: 19 | docker: 20 | - image: fsfe/reuse:latest 21 | steps: 22 | - checkout 23 | - run: reuse lint 24 | 25 | build-test: 26 | parameters: 27 | tag: 28 | type: string 29 | docker: 30 | - image: hexpm/elixir:<< parameters.tag >> 31 | working_directory: ~/repo 32 | environment: 33 | LC_ALL: C.UTF-8 34 | steps: 35 | - run: 36 | name: Install system dependencies 37 | command: apk add --no-cache build-base 38 | - checkout 39 | - run: 40 | name: Install hex and rebar 41 | command: | 42 | mix local.hex --force 43 | mix local.rebar --force 44 | - restore_cache: 45 | keys: 46 | - v1-mix-cache-<< parameters.tag >>-{{ checksum "mix.lock" }} 47 | - run: mix deps.get 48 | - run: mix test 49 | - when: 50 | condition: 51 | matches: { <<: *latest, value: << parameters.tag >> } 52 | steps: 53 | - run: mix format --check-formatted 54 | - run: mix deps.unlock --check-unused 55 | - run: mix docs 56 | - run: mix hex.build 57 | - run: mix credo -a --strict 58 | - run: mix dialyzer 59 | - save_cache: 60 | key: v1-mix-cache-<< parameters.tag >>-{{ checksum "mix.lock" }} 61 | paths: 62 | - _build 63 | - deps 64 | 65 | automerge: 66 | docker: 67 | - image: alpine:3.21.0 68 | steps: 69 | - run: 70 | name: Install GitHub CLI 71 | command: apk add --no-cache build-base github-cli 72 | - run: 73 | name: Attempt PR automerge 74 | command: | 75 | author=$(gh pr view "${CIRCLE_PULL_REQUEST}" --json author --jq '.author.login' || true) 76 | if [ "$author" = "app/dependabot" ]; then 77 | gh pr merge "${CIRCLE_PULL_REQUEST}" --auto --rebase || echo "Failed trying to set automerge" 78 | else 79 | echo "Not a dependabot PR, skipping automerge" 80 | fi 81 | 82 | workflows: 83 | checks: 84 | jobs: 85 | - check-license: 86 | filters: 87 | tags: 88 | only: /.*/ 89 | - build-test: 90 | name: << matrix.tag >> 91 | matrix: 92 | parameters: 93 | tag: *tags 94 | 95 | - automerge: 96 | requires: *tags 97 | context: org-global 98 | filters: 99 | branches: 100 | only: /^dependabot.*/ 101 | -------------------------------------------------------------------------------- /test/beam_notify_test.exs: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Ed Wildgoose 2 | # SPDX-FileCopyrightText: 2021 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule BEAMNotifyTest do 7 | use ExUnit.Case 8 | require Bitwise 9 | 10 | defp beam_notify_child_spec(context, extra_options \\ []) do 11 | us = self() 12 | base_options = [name: context.test, dispatcher: &send(us, {&1, &2})] 13 | {BEAMNotify, Keyword.merge(base_options, extra_options)} 14 | end 15 | 16 | test "directly sending a message", context do 17 | pid = start_supervised!(beam_notify_child_spec(context)) 18 | 19 | env = BEAMNotify.env(pid) 20 | {"", 0} = System.cmd(env["BEAM_NOTIFY"], ["hello", "from", "a", "c", "program"], env: env) 21 | 22 | empty_map = %{} 23 | assert_receive {["hello", "from", "a", "c", "program"], ^empty_map} 24 | end 25 | 26 | test "nameless use" do 27 | us = self() 28 | pid = start_supervised!({BEAMNotify, dispatcher: &send(us, {&1, &2})}) 29 | 30 | env = BEAMNotify.env(pid) 31 | {"", 0} = System.cmd(env["BEAM_NOTIFY"], ["hello", "nameless"], env: env) 32 | 33 | assert_receive {["hello", "nameless"], %{}} 34 | end 35 | 36 | test "explicit socket path" do 37 | us = self() 38 | pid = start_supervised!({BEAMNotify, path: "test_socket", dispatcher: &send(us, {&1, &2})}) 39 | 40 | env = BEAMNotify.env(pid) 41 | {"", 0} = System.cmd(env["BEAM_NOTIFY"], ["hello", "explicit", "path"], env: env) 42 | 43 | assert_receive {["hello", "explicit", "path"], %{}} 44 | end 45 | 46 | test "explicit socket permissions" do 47 | # Unusual mode 48 | mode = 0o711 49 | _ = start_supervised!({BEAMNotify, path: "test_socket", mode: mode}) 50 | 51 | assert mode == Bitwise.band(File.stat!("test_socket").mode, 0o777) 52 | end 53 | 54 | test "sending a message via a script", context do 55 | pid = start_supervised!(beam_notify_child_spec(context)) 56 | 57 | {"This is simple.sh\n", 0} = 58 | System.cmd("/bin/sh", ["test/support/simple.sh"], env: BEAMNotify.env(pid)) 59 | 60 | assert_receive {["Hello", "world"], %{}} 61 | end 62 | 63 | test "capturing environment variables", context do 64 | pid = start_supervised!(beam_notify_child_spec(context, report_env: true)) 65 | 66 | {"This is set_env.sh\n", 0} = 67 | System.cmd("/bin/sh", ["test/support/set_env.sh"], env: BEAMNotify.env(pid)) 68 | 69 | assert_receive {[], %{"TEST_ENV_VAR" => "42"}} 70 | end 71 | 72 | test "bin_path/0 location matches environment" do 73 | env = BEAMNotify.env(name: "test_name") 74 | bin_path = BEAMNotify.bin_path() 75 | 76 | assert bin_path == env["BEAM_NOTIFY"] 77 | end 78 | 79 | test "sending a message via commandline args", context do 80 | pid = start_supervised!(beam_notify_child_spec(context)) 81 | script = "#{BEAMNotify.bin_path()} #{BEAMNotify.env(pid)["BEAM_NOTIFY_OPTIONS"]} -- hello" 82 | 83 | # BEAM_NOTIFY_OPTIONS not set 84 | {"", 0} = System.cmd("/bin/sh", ["-c", script]) 85 | assert_receive {["hello"], %{}} 86 | 87 | # BEAM_NOTIFY_OPTIONS set to an empty string (easy mistake when trying to unset a variable) 88 | {"", 0} = System.cmd("/bin/sh", ["-c", script], env: %{"BEAM_NOTIFY_OPTIONS" => ""}) 89 | 90 | assert_receive {["hello"], %{}} 91 | 92 | # BEAM_NOTIFY_OPTIONS set to a string with spaces 93 | {"", 0} = System.cmd("/bin/sh", ["-c", script], env: %{"BEAM_NOTIFY_OPTIONS" => " "}) 94 | 95 | assert_receive {["hello"], %{}} 96 | end 97 | end 98 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "credo": {:hex, :credo, "1.7.13", "126a0697df6b7b71cd18c81bc92335297839a806b6f62b61d417500d1070ff4e", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "47641e6d2bbff1e241e87695b29f617f1a8f912adea34296fb10ecc3d7e9e84f"}, 4 | "dialyxir": {:hex, :dialyxir, "1.4.7", "dda948fcee52962e4b6c5b4b16b2d8fa7d50d8645bbae8b8685c3f9ecb7f5f4d", [:mix], [{:erlex, ">= 0.2.8", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b34527202e6eb8cee198efec110996c25c5898f43a4094df157f8d28f27d9efe"}, 5 | "earmark_parser": {:hex, :earmark_parser, "1.4.44", "f20830dd6b5c77afe2b063777ddbbff09f9759396500cdbe7523efd58d7a339c", [:mix], [], "hexpm", "4778ac752b4701a5599215f7030989c989ffdc4f6df457c5f36938cc2d2a2750"}, 6 | "elixir_make": {:hex, :elixir_make, "0.9.0", "6484b3cd8c0cee58f09f05ecaf1a140a8c97670671a6a0e7ab4dc326c3109726", [:mix], [], "hexpm", "db23d4fd8b757462ad02f8aa73431a426fe6671c80b200d9710caf3d1dd0ffdb"}, 7 | "erlex": {:hex, :erlex, "0.2.8", "cd8116f20f3c0afe376d1e8d1f0ae2452337729f68be016ea544a72f767d9c12", [:mix], [], "hexpm", "9d66ff9fedf69e49dc3fd12831e12a8a37b76f8651dd21cd45fcf5561a8a7590"}, 8 | "ex_doc": {:hex, :ex_doc, "0.39.1", "e19d356a1ba1e8f8cfc79ce1c3f83884b6abfcb79329d435d4bbb3e97ccc286e", [:mix], [{:earmark_parser, "~> 1.4.44", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "8abf0ed3e3ca87c0847dfc4168ceab5bedfe881692f1b7c45f4a11b232806865"}, 9 | "file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"}, 10 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 11 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 12 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, 13 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.2", "03e1804074b3aa64d5fad7aa64601ed0fb395337b982d9bcf04029d68d51b6a7", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "af33ff7ef368d5893e4a267933e7744e46ce3cf1f61e2dccf53a111ed3aa3727"}, 14 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, 15 | } 16 | -------------------------------------------------------------------------------- /lib/beam_notify.ex: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Ed Wildgoose 2 | # SPDX-FileCopyrightText: 2021 Frank Hunleth 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | defmodule BEAMNotify do 7 | @moduledoc """ 8 | Send a message to the BEAM from a shell script 9 | """ 10 | use GenServer 11 | 12 | require Logger 13 | 14 | @typedoc """ 15 | Callback for dispatching notifications 16 | 17 | BEAMNotify calls the dispatcher function whenever a message comes in. The 18 | first parameter is the list of arguments passed to `$BEAM_NOTIFY`. The 19 | second argument is a map containing environment variables. Whether or 20 | not the map is populated depends on the options to `start_link/1`. 21 | """ 22 | @type dispatcher() :: ([String.t()], %{String.t() => String.t()} -> :ok) 23 | 24 | @typedoc """ 25 | BEAMNotify takes the following options 26 | 27 | * `:name` - a unique name for this notifier. This is required if you expect 28 | to run multiple BEAMNotify GenServers at a time. 29 | * `:dispatcher` - a function to call when a notification comes in 30 | * `:path` - the path to use for the named socket. A path in the system 31 | temporary directory is the default. 32 | * `:mode` - the permissions to apply to the socket. Should be an octal number 33 | eg: 0o660 for read/write owner/group, no access to everyone else 34 | * `:report_env` - set to `true` to report environment variables in addition 35 | to commandline argument. Defaults to `false` 36 | * `:recbuf` - receive buffer size. If you're sending a particular large 37 | amount of data and getting errors from `:erlang.binary_to_term(data)`, try 38 | making this bigger. Defaults to 8192. 39 | """ 40 | @type options() :: [ 41 | name: binary() | atom(), 42 | path: Path.t(), 43 | mode: non_neg_integer(), 44 | dispatcher: dispatcher(), 45 | report_env: boolean(), 46 | recbuf: non_neg_integer() 47 | ] 48 | 49 | @doc """ 50 | Start the BEAMNotify message receiver 51 | """ 52 | @spec start_link(options()) :: GenServer.on_start() 53 | def start_link(options) do 54 | name = options |> name_from_options() |> gen_server_name() 55 | GenServer.start_link(__MODULE__, options, name: name) 56 | end 57 | 58 | @doc """ 59 | Return the OS environment needed to call `$BEAM_NOTIFY` 60 | 61 | This returns a map that can be passed directly to `System.cmd/3` via its 62 | `:env` option. 63 | 64 | This function can be passed different things based on what's convenient. 65 | 66 | 1. If you're setting up `child_spec`'s for a supervision tree and need the 67 | environment to pass in another `child_spec`, call this with the same 68 | options that you'd pass to `start_link/1`. This is a very common use. 69 | 70 | 2. If you called `start_link/1` manually and have the pid, call it with 71 | the pid. 72 | 73 | 3. If you only have the name that was passed to `start_link/1`, then call 74 | it with the name. The name alone is insufficient for returning the 75 | `$BEAM_NOTIFY_OPTIONS` environment variable, so the `BEAMNotify` 76 | GenServer must be running. If you're in a chicken-and-egg situation 77 | where you're setting up a supervision tree, but it hasn't been started 78 | yet, see option 1. 79 | """ 80 | @spec env(pid() | binary() | atom() | keyword()) :: Enumerable.t() 81 | def env(options) when is_list(options) do 82 | options_to_env(options) 83 | end 84 | 85 | def env(pid) when is_pid(pid) do 86 | GenServer.call(pid, :env) 87 | end 88 | 89 | def env(name) when is_binary(name) or is_atom(name) do 90 | GenServer.call(gen_server_name(name), :env) 91 | end 92 | 93 | @doc """ 94 | Return the path to `beam_notify` 95 | """ 96 | @spec bin_path() :: Path.t() 97 | def bin_path() do 98 | Application.app_dir(:beam_notify, ["priv", "beam_notify"]) 99 | end 100 | 101 | @impl GenServer 102 | def init(options) do 103 | socket_path = socket_path(options) 104 | dispatcher = Keyword.get(options, :dispatcher, &null_dispatcher/2) 105 | recbuf = Keyword.get(options, :recbuf, 8192) 106 | mode = Keyword.get(options, :mode) 107 | 108 | # Blindly try to remove an old file just in case it exists from a previous run 109 | _ = File.rm(socket_path) 110 | _ = File.mkdir_p(Path.dirname(socket_path)) 111 | 112 | {:ok, socket} = 113 | :gen_udp.open(0, [ 114 | :local, 115 | :binary, 116 | {:active, true}, 117 | {:ip, {:local, socket_path}}, 118 | {:recbuf, recbuf} 119 | ]) 120 | 121 | if mode, do: File.chmod!(socket_path, mode) 122 | 123 | state = %{ 124 | socket_path: socket_path, 125 | socket: socket, 126 | options: options, 127 | dispatcher: dispatcher 128 | } 129 | 130 | {:ok, state} 131 | end 132 | 133 | @impl GenServer 134 | def handle_call(:env, _from, state) do 135 | {:reply, options_to_env(state.options), state} 136 | end 137 | 138 | @impl GenServer 139 | def handle_info({:udp, socket, _, 0, data}, %{socket: socket} = state) do 140 | {args, env} = :erlang.binary_to_term(data) 141 | 142 | state.dispatcher.(args, env) 143 | 144 | {:noreply, state} 145 | end 146 | 147 | @impl GenServer 148 | def terminate(_reason, state) do 149 | # Try to clean up 150 | _ = File.rm(state.socket_path) 151 | end 152 | 153 | defp gen_server_name(name) do 154 | Module.concat(__MODULE__, name) 155 | end 156 | 157 | defp name_from_options(options) do 158 | Keyword.get(options, :name, :unnamed) 159 | end 160 | 161 | defp null_dispatcher(args, env) do 162 | Logger.warning("beam_notify called with no dispatcher: #{inspect(args)}, #{inspect(env)}") 163 | end 164 | 165 | defp options_to_env(options) do 166 | bn_options = options_to_cmdline(options) |> Enum.map_join(" ", "e_string/1) 167 | %{"BEAM_NOTIFY" => bin_path(), "BEAM_NOTIFY_OPTIONS" => bn_options} 168 | end 169 | 170 | defp options_to_cmdline(options) do 171 | ["-p", socket_path(options)] ++ report_env_arg(options) 172 | end 173 | 174 | defp report_env_arg(options) do 175 | if Keyword.get(options, :report_env) do 176 | ["-e"] 177 | else 178 | [] 179 | end 180 | end 181 | 182 | defp quote_string(s) do 183 | if String.contains?(s, " ") do 184 | "\"" <> s <> "\"" 185 | else 186 | s 187 | end 188 | end 189 | 190 | defp socket_path(options) do 191 | case Keyword.get(options, :path) do 192 | nil -> 193 | safe_name = name_from_options(options) |> :erlang.phash2() |> Integer.to_string() 194 | name = "beam_notify-" <> safe_name 195 | Path.join(System.tmp_dir!(), name) 196 | 197 | path -> 198 | path 199 | end 200 | end 201 | end 202 | -------------------------------------------------------------------------------- /LICENSES/CC0-1.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BEAMNotify 2 | 3 | [![Hex version](https://img.shields.io/hexpm/v/beam_notify.svg "Hex version")](https://hex.pm/packages/beam_notify) 4 | [![API docs](https://img.shields.io/hexpm/v/beam_notify.svg?label=hexdocs "API docs")](https://hexdocs.pm/beam_notify/BEAMNotify.html) 5 | [![CircleCI](https://dl.circleci.com/status-badge/img/gh/nerves-networking/beam_notify/tree/main.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/nerves-networking/beam_notify/tree/main) 6 | [![REUSE status](https://api.reuse.software/badge/github.com/nerves-networking/beam_notify)](https://api.reuse.software/info/github.com/nerves-networking/beam_notify) 7 | 8 | Send a message to the BEAM from a shell script 9 | 10 | This is one solution sending notifications from non-BEAM programs into Elixir. 11 | `BEAMNotify` lets you set up a GenServer that listens for notifications from 12 | shell scripts or anything that can invoke an OS process. Communication is via a 13 | Unix Domain socket. Messages are limited to strings that passed via commandline 14 | arguments or the environment to the `beam_notify` binary. 15 | 16 | There are, of course, other ways of solving this problem. Some non-Elixir 17 | programs already expose Unix domain or TCP socket interfaces for communication. 18 | This might be a better choice. You could also use 19 | [erl_call](http://erlang.org/doc/man/erl_call.html) or write a [C 20 | node](http://erlang.org/doc/apps/erl_interface/ei_users_guide.html#introduction) 21 | and communicate over distributed Erlang. 22 | 23 | ## Overview 24 | 25 | `BEAMNotify` would typically be added to a supervision tree in your program. 26 | Options to `BEAMNotify` specify things like its name, a dispatch function to 27 | call, and other things. 28 | 29 | The shell script (or any program) needs to call the `beam_notify` program 30 | supplied by this library. The message is passed via commandline arguments or 31 | environment variables (see `:report_env` option). 32 | 33 | Since `beam_notify` needs to know how to connect to the appropriate 34 | `BEAMNotify` GenServer (there may be more than one), the shell script must pass 35 | some options. To make this easy, `BEAMNotify` provides two environment 36 | variables by calling `BEAMNotify.env/1`: 37 | 38 | 1. `$BEAM_NOTIFY` - the absolute path to the `beam_notify` executable 39 | 2. `$BEAM_NOTIFY_OPTIONS` - how `beam_notify` should connect 40 | 41 | In the shell script, run `$BEAM_NOTIFY` and pass it any arguments that you want 42 | send up. `BEAMNotify` reports environment variables too. 43 | 44 | If it is not possible to pass the `$BEAM_NOTIFY*` environment variables through 45 | to your script due to a restricted shell environment, see the restricted shell 46 | section below. 47 | 48 | Back in Elixir, whenever a proper message is received, `BEAMNotify` will call 49 | the dispatch function. The dispatch function is responsible for forwarding on 50 | messages however makes sense in your application. If handling is simple, you can 51 | process them in the dispatch function. You could also publish them through 52 | `Phoenix.PubSub` or another pubsub service. `BEAMNotify` only handles strings, 53 | so if you want to be fancier with your messages or filter them, you'll have to 54 | add that to your dispatcher function. 55 | 56 | It is important to keep in mind that the amount of data that can be sent in a 57 | notification is limited by the transport and by OS limits on commandline 58 | arguments. Suffice it to say that this is not intended for file transfer. 59 | 60 | ## Example 61 | 62 | What we're going to do is create a script that sends a message to Elixir. 63 | First, make sure that you have `:beam_notify` by either cloning this project or 64 | creating a test Elixir project (`mix new ...`) and adding it to the `mix.exs`: 65 | 66 | ```elixir 67 | def deps do 68 | [ 69 | {:beam_notify, "~> 0.2.0"} 70 | ] 71 | end 72 | ``` 73 | 74 | Now open an editor and create `simple.sh` with the following contents: 75 | 76 | ```sh 77 | #!/bin/sh 78 | 79 | echo "This is simple.sh" 80 | 81 | $BEAM_NOTIFY Hello world 82 | ``` 83 | 84 | Start up Elixir with `iex -S mix`: 85 | 86 | ```elixir 87 | # Get the PID that's running the IEx console 88 | iex> us = self() 89 | #PID<0.204.0> 90 | 91 | # Start a BEAMNotify GenServer. The dispatcher function sends a tuple with the 92 | # arguments and environment passed in from the shell script. 93 | iex> BEAMNotify.start_link(name: "sulu", report_env: true, dispatcher: &send(us, {&1, &2})) 94 | {:ok, #PID<0.211.0>} 95 | 96 | # Run the shell script. We're doing this from Elixir, but you 97 | # can also grab the environment by calling `BEAMNotify.env/1` and run it 98 | # in another terminal window. 99 | iex> System.cmd("/bin/sh", ["simple.sh"], env: BEAMNotify.env("sulu")) 100 | {"This is simple.sh\n", 0} 101 | 102 | # See what was sent 103 | iex> flush 104 | {["Hello", "world"], %{...}} 105 | ``` 106 | 107 | ## Supervision example 108 | 109 | Here's a code snippet of starting a hypothetical non-Elixir program that needs 110 | to send messages back to Elixir. This code is part of a [module-based 111 | supervisor](https://hexdocs.pm/elixir/Supervisor.html#module-module-based-supervisors), 112 | but this isn't necessary. Two GenServers are started: one for `BEAMNotify` and 113 | one to start and monitor the non-Elixir program using 114 | [`MuonTrap.Daemon`](https://hexdocs.pm/muontrap/MuonTrap.Daemon.html). 115 | 116 | Note how `BEAMNotify.env/1` is used to pass the proper environment to the 117 | program. 118 | 119 | ```elixir 120 | @impl Supervisor 121 | def init(_) do 122 | beam_notify_options = [name: "my_beam", dispatcher: &Some.function/2] 123 | children = [ 124 | {BEAMNotify, beam_notify_options}, 125 | {MuonTrap.Daemon, 126 | [ 127 | "/path/to/program", 128 | ["-s", "script_calling_beam_notify.sh"], 129 | [log_output: :debug, env: BEAMNotify.env(beam_notify_options)] 130 | ]} 131 | ] 132 | 133 | opts = [strategy: :one_for_one] 134 | Supervisor.start_link(children, opts) 135 | end 136 | ``` 137 | 138 | If you're lucky, it might be sufficient to call `BEAMNotify.bin_path/0` to get 139 | the path to the `beam_notify` program and pass that directly to the non-Elixir 140 | program. You'll still need to set the environment for `beam_notify` to work. On 141 | the bright side, this will skip out having your system start `bash` on each 142 | notification. 143 | 144 | ## Restricted shell environments 145 | 146 | Some programs clear the OS environment before running programs as a security 147 | precaution. It's still possible send messages to Elixir. 148 | 149 | You'll need to know the path to the `beam_notify` binary and have a place to put 150 | the communications socket that both Elixir and the `beam_notify` binary can 151 | open. In this example, the socket will be created as 152 | `/tmp/my_beam_notify_socket`. In Elixir, the `BEAMNotify` child_spec might look 153 | like this: 154 | 155 | ```elixir 156 | {BEAMNotify, name: "any name", path: "/tmp/my_beam_notify_socket", dispatcher: &Some.function/2} 157 | ``` 158 | 159 | For the script, here's a sample for Nerves devices where code is installed under 160 | `/srv/erlang`. 161 | 162 | ```sh 163 | #!/bin/sh 164 | 165 | BEAM_NOTIFY=$(ls /srv/erlang/lib/beam_notify-*/priv/beam_notify) 166 | 167 | $BEAM_NOTIFY -p /tmp/my_beam_notify_socket -- hello 168 | ``` 169 | 170 | The arguments following the `--` are passed. The `-p /tmp/my_beam_notify_socket` 171 | part will be dropped. 172 | 173 | Arguments are only parsed (and dropped) if `$BEAM_NOTIFY_OPTIONS` isn't defined. 174 | In other words, `$BEAM_NOTIFY_OPTIONS` takes precedence. 175 | 176 | ## License 177 | 178 | This library is covered by the Apache 2 license. 179 | -------------------------------------------------------------------------------- /c_src/beam_notify.c: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2021 Frank Hunleth 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | 16 | #define MIN_SEND_SIZE 8192 17 | 18 | extern char **environ; 19 | 20 | struct beam_notify_options { 21 | char *path; 22 | int encode_environment; 23 | }; 24 | 25 | static void encode_string(ei_x_buff *buff, const char *str) 26 | { 27 | // Encode strings as binaries so that we get Elixir strings 28 | // NOTE: the strings that we encounter here are expected to be ASCII to 29 | // my knowledge 30 | ei_x_encode_binary(buff, str, strlen(str)); 31 | } 32 | 33 | static int should_encode(const char *kv, const struct beam_notify_options *bn) 34 | { 35 | if (!bn->encode_environment || 36 | strncmp(kv, "BEAM_NOTIFY=", 12) == 0 || 37 | strncmp(kv, "BEAM_NOTIFY_OPTIONS=", 20) == 0) 38 | return 0; 39 | else 40 | return 1; 41 | } 42 | 43 | static int count_environ_to_encode(const struct beam_notify_options *bn) 44 | { 45 | char **p = environ; 46 | int n = 0; 47 | 48 | while (*p != NULL) { 49 | if (should_encode(*p, bn)) 50 | n++; 51 | 52 | p++; 53 | } 54 | 55 | return n; 56 | } 57 | 58 | static void encode_env_kv(ei_x_buff *buff, const char *kv) 59 | { 60 | char key[32]; 61 | 62 | const char *equal = strchr(kv, '='); 63 | if (equal == NULL) 64 | return; 65 | 66 | size_t keylen = equal - kv; 67 | if (keylen >= sizeof(key)) 68 | keylen = sizeof(key) - 1; 69 | memcpy(key, kv, keylen); 70 | key[keylen] = '\0'; 71 | 72 | const char *value = equal + 1; 73 | 74 | encode_string(buff, key); 75 | encode_string(buff, value); 76 | } 77 | 78 | static void encode_environ(ei_x_buff *buff, const struct beam_notify_options *bn) 79 | { 80 | int kv_to_encode = count_environ_to_encode(bn); 81 | ei_x_encode_map_header(buff, kv_to_encode); 82 | 83 | char **p = environ; 84 | while (*p != NULL && kv_to_encode > 0) { 85 | const char *kv = *p; 86 | 87 | if (should_encode(kv, bn)) { 88 | encode_env_kv(buff, kv); 89 | kv_to_encode--; 90 | } 91 | 92 | p++; 93 | } 94 | } 95 | 96 | static void encode_args(ei_x_buff *buff, int argc, char *argv[]) 97 | { 98 | ei_x_encode_list_header(buff, argc - 1); 99 | 100 | if (argc > 1) { 101 | int i; 102 | for (i = 1; i < argc; i++) 103 | encode_string(buff, argv[i]); 104 | 105 | ei_x_encode_empty_list(buff); 106 | } 107 | } 108 | 109 | static int inplace_string_to_argv(char *str, char **argv, int max_args) 110 | { 111 | int argc = 0; 112 | char *c = str; 113 | #define STATE_SPACE 0 114 | #define STATE_TOKEN 1 115 | #define STATE_QUOTED_TOKEN 2 116 | int state = STATE_SPACE; 117 | max_args--; // leave room for final null 118 | while (*c != '\0') { 119 | switch (state) { 120 | case STATE_SPACE: 121 | if (isspace(*c)) 122 | break; 123 | else if (*c == '"') { 124 | *argv = c + 1; 125 | state = STATE_QUOTED_TOKEN; 126 | } else { 127 | *argv = c; 128 | state = STATE_TOKEN; 129 | } 130 | break; 131 | case STATE_TOKEN: 132 | if (isspace(*c)) { 133 | *c = '\0'; 134 | argv++; 135 | argc++; 136 | state = STATE_SPACE; 137 | 138 | if (argc == max_args) 139 | break; 140 | } 141 | break; 142 | case STATE_QUOTED_TOKEN: 143 | if (*c == '"') { 144 | *c = '\0'; 145 | argv++; 146 | argc++; 147 | state = STATE_SPACE; 148 | 149 | if (argc == max_args) 150 | break; 151 | } 152 | break; 153 | } 154 | c++; 155 | } 156 | 157 | if (state != STATE_SPACE) 158 | argc++; 159 | argv = NULL; 160 | 161 | return argc; 162 | } 163 | 164 | static int parse_arguments(int argc, char *argv[], struct beam_notify_options *bn) 165 | { 166 | int opt; 167 | 168 | while ((opt = getopt(argc, argv, "ep:")) != -1) { 169 | switch (opt) { 170 | case 'e': 171 | bn->encode_environment = 1; 172 | break; 173 | case 'p': 174 | bn->path = optarg; 175 | break; 176 | default: 177 | return -1; 178 | } 179 | } 180 | 181 | return optind; 182 | } 183 | 184 | int main(int argc, char *argv[]) 185 | { 186 | struct beam_notify_options bn; 187 | memset(&bn, 0, sizeof(bn)); 188 | 189 | // Parse options from $BEAM_NOTIFY_OPTIONS. If insufficient, check the commandline 190 | char *options = getenv("BEAM_NOTIFY_OPTIONS"); 191 | if (options) { 192 | #define MAX_OPTIONS 3 193 | char *options_argv[MAX_OPTIONS + 1]; 194 | options_argv[0] = ""; // "Program name" 195 | int option_argc = inplace_string_to_argv(options, &options_argv[1], MAX_OPTIONS); 196 | if (parse_arguments(option_argc + 1, options_argv, &bn) < 0) 197 | errx(EXIT_FAILURE, "$BEAM_NOTIFY_OPTIONS is corrupt or invalid"); 198 | } 199 | if (bn.path == NULL) { 200 | int processed_argc = parse_arguments(argc, argv, &bn); 201 | if (processed_argc < 0) 202 | errx(EXIT_FAILURE, "Invalid arguments or $BEAM_NOTIFY_OPTIONS's value was lost"); 203 | 204 | if (bn.path == NULL) 205 | errx(EXIT_FAILURE, "Missing socket path. Either use $BEAM_NOTIFY_OPTIONS or pass -p "); 206 | 207 | // Adjust argc, argv so that they start after our arguments 208 | argc = argc - processed_argc + 1; 209 | argv += processed_argc - 1; 210 | *argv[0] = '\0'; // new program name 211 | 212 | } 213 | 214 | int fd = socket(AF_UNIX, SOCK_DGRAM, 0); 215 | if (fd < 0) 216 | err(EXIT_FAILURE, "socket"); 217 | 218 | struct sockaddr_un addr; 219 | memset(&addr, 0, sizeof(addr)); 220 | addr.sun_family = AF_UNIX; 221 | strncpy(addr.sun_path, bn.path, sizeof(addr.sun_path) - 1); 222 | 223 | if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) 224 | err(EXIT_FAILURE, "connect"); 225 | 226 | // Increase the send buffer if it's really small 227 | int send_size; 228 | socklen_t optlen = sizeof(send_size); 229 | int res = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &send_size, &optlen); 230 | if (res >= 0 && send_size < MIN_SEND_SIZE) { 231 | // Set buffer size 232 | send_size = MIN_SEND_SIZE; 233 | 234 | res = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &send_size, sizeof(send_size)); 235 | if (res < 0) 236 | warn("Couldn't increase buffer size to %d", send_size); 237 | } 238 | 239 | ei_x_buff buff; 240 | if (ei_x_new_with_version(&buff) < 0) 241 | err(EXIT_FAILURE, "ei_x_new_with_version"); 242 | 243 | ei_x_encode_tuple_header(&buff, 2); 244 | 245 | encode_args(&buff, argc, argv); 246 | encode_environ(&buff, &bn); 247 | 248 | ssize_t rc = write(fd, buff.buff, buff.index); 249 | if (rc < 0) 250 | err(EXIT_FAILURE, "write"); 251 | 252 | if (rc != buff.index) 253 | errx(EXIT_FAILURE, "write wasn't able to send %d chars all at once!", buff.index); 254 | 255 | close(fd); 256 | return 0; 257 | } 258 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /LICENSES/CC-BY-4.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution 4.0 International 2 | 3 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 4 | 5 | Using Creative Commons Public Licenses 6 | 7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | 9 | Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. 10 | 11 | Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. 12 | 13 | Creative Commons Attribution 4.0 International Public License 14 | 15 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 16 | 17 | Section 1 – Definitions. 18 | 19 | a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 20 | 21 | b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 22 | 23 | c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 24 | 25 | d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 26 | 27 | e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 28 | 29 | f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 30 | 31 | g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 32 | 33 | h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. 34 | 35 | i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 36 | 37 | j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 38 | 39 | k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 40 | 41 | Section 2 – Scope. 42 | 43 | a. License grant. 44 | 45 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 46 | 47 | A. reproduce and Share the Licensed Material, in whole or in part; and 48 | 49 | B. produce, reproduce, and Share Adapted Material. 50 | 51 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 52 | 53 | 3. Term. The term of this Public License is specified in Section 6(a). 54 | 55 | 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 56 | 57 | 5. Downstream recipients. 58 | 59 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 60 | 61 | B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 62 | 63 | 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 64 | 65 | b. Other rights. 66 | 67 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 68 | 69 | 2. Patent and trademark rights are not licensed under this Public License. 70 | 71 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. 72 | 73 | Section 3 – License Conditions. 74 | 75 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 76 | 77 | a. Attribution. 78 | 79 | 1. If You Share the Licensed Material (including in modified form), You must: 80 | 81 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 82 | 83 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 84 | 85 | ii. a copyright notice; 86 | 87 | iii. a notice that refers to this Public License; 88 | 89 | iv. a notice that refers to the disclaimer of warranties; 90 | 91 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 92 | 93 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 94 | 95 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 96 | 97 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 98 | 99 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 100 | 101 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 102 | 103 | Section 4 – Sui Generis Database Rights. 104 | 105 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 106 | 107 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; 108 | 109 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 110 | 111 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 112 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 113 | 114 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 115 | 116 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 117 | 118 | b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 119 | 120 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 121 | 122 | Section 6 – Term and Termination. 123 | 124 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 125 | 126 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 127 | 128 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 129 | 130 | 2. upon express reinstatement by the Licensor. 131 | 132 | c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 133 | 134 | d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 135 | 136 | e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 137 | 138 | Section 7 – Other Terms and Conditions. 139 | 140 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 141 | 142 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 143 | 144 | Section 8 – Interpretation. 145 | 146 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 147 | 148 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 149 | 150 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 151 | 152 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 153 | 154 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 155 | 156 | Creative Commons may be contacted at creativecommons.org. 157 | --------------------------------------------------------------------------------