about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--Makefile.am9
-rw-r--r--configure.ac13
-rwxr-xr-xinstall-all.sh2
-rw-r--r--src/command/command.c24
-rw-r--r--src/command/commands.c66
-rw-r--r--src/command/commands.h1
-rw-r--r--src/config/account.c9
-rw-r--r--src/config/account.h3
-rw-r--r--src/config/accounts.c26
-rw-r--r--src/config/accounts.h2
-rw-r--r--src/main.c6
-rw-r--r--src/pgp/gpg.c374
-rw-r--r--src/pgp/gpg.h55
-rw-r--r--src/profanity.c9
-rw-r--r--src/ui/console.c4
-rw-r--r--src/xmpp/message.c48
-rw-r--r--src/xmpp/presence.c37
-rw-r--r--src/xmpp/stanza.h2
-rw-r--r--tests/config/stub_accounts.c2
-rw-r--r--tests/pgp/stub_gpg.c25
-rw-r--r--tests/test_cmd_account.c12
-rw-r--r--tests/test_cmd_connect.c6
-rw-r--r--tests/test_cmd_join.c8
-rw-r--r--tests/test_cmd_otr.c2
25 files changed, 725 insertions, 22 deletions
diff --git a/.travis.yml b/.travis.yml
index e546d8b3..a71e321e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,7 @@
 language: c
 install:
     - sudo apt-get update
-    - sudo apt-get -y install libssl-dev libexpat1-dev libncursesw5-dev libglib2.0-dev libnotify-dev libcurl3-dev libxss-dev libotr2-dev uuid-dev
+    - sudo apt-get -y install libssl-dev libexpat1-dev libncursesw5-dev libglib2.0-dev libnotify-dev libcurl3-dev libxss-dev libotr2-dev libgpgme11-dev uuid-dev
     - git clone git://github.com/strophe/libstrophe.git
     - cd libstrophe
     - mkdir m4
diff --git a/Makefile.am b/Makefile.am
index c5449a2b..f3341d04 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -44,6 +44,7 @@ tests_sources = \
 	src/xmpp/xmpp.h src/xmpp/form.c \
 	src/ui/ui.h \
 	src/otr/otr.h \
+	src/pgp/gpg.h \
 	src/command/command.h src/command/command.c \
 	src/command/commands.h src/command/commands.c \
 	src/tools/parser.c \
@@ -63,6 +64,7 @@ tests_sources = \
 	src/event/server_events.c src/event/server_events.h \
 	tests/xmpp/stub_xmpp.c \
 	tests/ui/stub_ui.c \
+	tests/pgp/stub_gpg.c \
 	tests/log/stub_log.c \
 	tests/config/stub_accounts.c \
 	tests/helpers.c tests/helpers.h \
@@ -95,6 +97,9 @@ main_source = src/main.c
 
 git_include = src/gitversion.h
 
+pgp_sources = \
+	src/pgp/gpg.h src/pgp/gpg.c
+
 otr3_sources = \
 	src/otr/otrlib.h src/otr/otrlibv3.c src/otr/otr.h src/otr/otr.c
 
@@ -110,6 +115,10 @@ script_sources = bootstrap.sh configure-debug install-all.sh
 
 man_sources = docs/profanity.1
 
+if BUILD_PGP
+core_sources += $(pgp_sources)
+endif
+
 if BUILD_OTR
 tests_sources += $(otr_test_sources)
 if BUILD_OTR3
diff --git a/configure.ac b/configure.ac
index 1e2c6173..97d99d3a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -42,6 +42,8 @@ AC_ARG_ENABLE([notifications],
     [AS_HELP_STRING([--enable-notifications], [enable desktop notifications])])
 AC_ARG_ENABLE([otr],
     [AS_HELP_STRING([--enable-otr], [enable otr encryption])])
+AC_ARG_ENABLE([pgp],
+    [AS_HELP_STRING([--enable-pgp], [enable pgp])])
 AC_ARG_WITH([libxml2],
     [AS_HELP_STRING([--with-libxml2], [link with libxml2 instead of expat])])
 AC_ARG_WITH([xscreensaver],
@@ -186,6 +188,17 @@ elif test "x$with_xscreensaver" = x; then
         [AC_MSG_NOTICE([libX11 not found, falling back to profanity auto-away])])
 fi
 
+AM_CONDITIONAL([BUILD_PGP], [false])
+if test "x$enable_pgp" = xyes; then
+    AC_CHECK_LIB([gpgme], [main],
+        [AM_CONDITIONAL([BUILD_PGP], [true]) LIBS="-lgpgme $LIBS" AC_DEFINE([HAVE_LIBGPGME], [1], [Have libgpgme])],
+        [AC_MSG_ERROR([libgpgme is required for profanity])])
+elif test "x$enable_pgp" = x; then
+    AC_CHECK_LIB([gpgme], [main],
+        [AM_CONDITIONAL([BUILD_PGP], [true]) LIBS="-lgpgme $LIBS" AC_DEFINE([HAVE_LIBGPGME], [1], [Have libgpgme])],
+        [AC_MSG_NOTICE([libgpgme not found, pgp support not included.])])
+fi
+
 AM_CONDITIONAL([BUILD_OTR], [false])
 AM_CONDITIONAL([BUILD_OTR3], [false])
 AM_CONDITIONAL([BUILD_OTR4], [false])
diff --git a/install-all.sh b/install-all.sh
index a054e166..fc704bbc 100755
--- a/install-all.sh
+++ b/install-all.sh
@@ -24,7 +24,7 @@ debian_prepare()
     echo
     echo Profanity installer... installing dependencies
     echo
-    sudo apt-get -y install git automake autoconf libssl-dev libexpat1-dev libncursesw5-dev libglib2.0-dev libnotify-dev libcurl3-dev libxss-dev libotr5-dev libreadline-dev libtool
+    sudo apt-get -y install git automake autoconf libssl-dev libexpat1-dev libncursesw5-dev libglib2.0-dev libnotify-dev libcurl3-dev libxss-dev libotr5-dev libreadline-dev libtool libgpgme11-dev
 
 }
 
diff --git a/src/command/command.c b/src/command/command.c
index fca25690..519550a3 100644
--- a/src/command/command.c
+++ b/src/command/command.c
@@ -852,6 +852,16 @@ static struct cmd_t command_defs[] =
           "Send chat state notifications during chat sessions.",
           NULL } } },
 
+    { "/pgp",
+        cmd_pgp, parse_args, 1, 1, NULL,
+        { "/pgp keys|libver", "Open PGP.",
+        { "/pgp keys|libver",
+          "----------------",
+          "Open PGP.",
+          "keys   : List private keys."
+          "libver : Show which version of the libgpgme library is being used.",
+          NULL } } },
+
     { "/otr",
         cmd_otr, parse_args, 1, 3, NULL,
         { "/otr command [args..]", "Off The Record encryption commands.",
@@ -1207,6 +1217,7 @@ static Autocomplete time_statusbar_ac;
 static Autocomplete resource_ac;
 static Autocomplete inpblock_ac;
 static Autocomplete receipts_ac;
+static Autocomplete pgp_ac;
 
 /*
  * Initialise command autocompleter and history
@@ -1363,6 +1374,7 @@ cmd_init(void)
     autocomplete_add(account_set_ac, "muc");
     autocomplete_add(account_set_ac, "nick");
     autocomplete_add(account_set_ac, "otr");
+    autocomplete_add(account_set_ac, "pgpkeyid");
 
     account_clear_ac = autocomplete_new();
     autocomplete_add(account_clear_ac, "password");
@@ -1370,6 +1382,7 @@ cmd_init(void)
     autocomplete_add(account_clear_ac, "server");
     autocomplete_add(account_clear_ac, "port");
     autocomplete_add(account_clear_ac, "otr");
+    autocomplete_add(account_clear_ac, "pgpkeyid");
 
     account_default_ac = autocomplete_new();
     autocomplete_add(account_default_ac, "set");
@@ -1571,6 +1584,11 @@ cmd_init(void)
     receipts_ac = autocomplete_new();
     autocomplete_add(receipts_ac, "send");
     autocomplete_add(receipts_ac, "request");
+
+    pgp_ac = autocomplete_new();
+    autocomplete_add(pgp_ac, "keys");
+    autocomplete_add(pgp_ac, "fps");
+    autocomplete_add(pgp_ac, "libver");
 }
 
 void
@@ -1630,6 +1648,7 @@ cmd_uninit(void)
     autocomplete_free(resource_ac);
     autocomplete_free(inpblock_ac);
     autocomplete_free(receipts_ac);
+    autocomplete_free(pgp_ac);
 }
 
 gboolean
@@ -1798,6 +1817,7 @@ cmd_reset_autocomplete()
     autocomplete_reset(resource_ac);
     autocomplete_reset(inpblock_ac);
     autocomplete_reset(receipts_ac);
+    autocomplete_reset(pgp_ac);
 
     if (ui_current_win_type() == WIN_CHAT) {
         ProfChatWin *chatwin = wins_get_current_chat();
@@ -1981,8 +2001,8 @@ _cmd_complete_parameters(const char * const input)
         }
     }
 
-    gchar *cmds[] = { "/help", "/prefs", "/disco", "/close", "/wins", "/subject", "/room" };
-    Autocomplete completers[] = { help_ac, prefs_ac, disco_ac, close_ac, wins_ac, subject_ac, room_ac };
+    gchar *cmds[] = { "/help", "/prefs", "/disco", "/close", "/wins", "/subject", "/room", "/pgp" };
+    Autocomplete completers[] = { help_ac, prefs_ac, disco_ac, close_ac, wins_ac, subject_ac, room_ac, pgp_ac };
 
     for (i = 0; i < ARRAY_SIZE(cmds); i++) {
         result = autocomplete_param_with_ac(input, cmds[i], completers[i], TRUE);
diff --git a/src/command/commands.c b/src/command/commands.c
index 29ae6614..049e9893 100644
--- a/src/command/commands.c
+++ b/src/command/commands.c
@@ -57,6 +57,9 @@
 #ifdef HAVE_LIBOTR
 #include "otr/otr.h"
 #endif
+#ifdef HAVE_LIBGPGME
+#include "pgp/gpg.h"
+#endif
 #include "profanity.h"
 #include "tools/autocomplete.h"
 #include "tools/parser.h"
@@ -514,6 +517,10 @@ cmd_account(gchar **args, struct cmd_help_t help)
                         cons_show("Updated login status for account %s: %s", account_name, value);
                     }
                     cons_show("");
+                } else if (strcmp(property, "pgpkeyid") == 0) {
+                    accounts_set_pgp_keyid(account_name, value);
+                    cons_show("Updated PGP key ID for account %s: %s", account_name, value);
+                    cons_show("");
                 } else if (valid_resource_presence_string(property)) {
                     int intval;
                     char *err_msg = NULL;
@@ -592,6 +599,10 @@ cmd_account(gchar **args, struct cmd_help_t help)
                     accounts_clear_otr(account_name);
                     cons_show("OTR policy removed for account %s", account_name);
                     cons_show("");
+                } else if (strcmp(property, "pgpkeyid") == 0) {
+                    accounts_clear_pgp_keyid(account_name);
+                    cons_show("Removed PGP key ID for account %s", account_name);
+                    cons_show("");
                 } else {
                     cons_show("Invalid property: %s", property);
                     cons_show("");
@@ -4106,6 +4117,61 @@ cmd_xa(gchar **args, struct cmd_help_t help)
 }
 
 gboolean
+cmd_pgp(gchar **args, struct cmd_help_t help)
+{
+#ifdef HAVE_LIBGPGME
+    if (g_strcmp0(args[0], "keys") == 0) {
+        GSList *keys = p_gpg_list_keys();
+        if (keys) {
+            cons_show("PGP keys:");
+            while (keys) {
+                ProfPGPKey *key = keys->data;
+                cons_show("  %s", key->name);
+                cons_show("    ID          : %s", key->id);
+                cons_show("    Fingerprint : %s", key->fp);
+                keys = g_slist_next(keys);
+            }
+        } else {
+            cons_show("No keys found");
+        }
+        g_slist_free_full(keys, (GDestroyNotify)p_gpg_free_key);
+    } else if (g_strcmp0(args[0], "fps") == 0) {
+        GHashTable *fingerprints = p_gpg_fingerprints();
+        GList *jids = g_hash_table_get_keys(fingerprints);
+        if (jids) {
+            cons_show("Received PGP fingerprints:");
+            GList *curr = jids;
+            while (curr) {
+                char *jid = curr->data;
+                char *fingerprint = g_hash_table_lookup(fingerprints, jid);
+                cons_show("  %s: %s", jid, fingerprint);
+                curr = g_list_next(curr);
+            }
+        } else {
+            cons_show("No PGP fingerprints received.");
+        }
+        g_list_free(jids);
+    } else if (g_strcmp0(args[0], "libver") == 0) {
+        const char *libver = p_gpg_libver();
+        if (libver) {
+            GString *fullstr = g_string_new("Using libgpgme version ");
+            g_string_append(fullstr, libver);
+            cons_show("%s", fullstr->str);
+            g_string_free(fullstr, TRUE);
+        } else {
+            cons_show("Could not get libgpgme version");
+        }
+    }
+
+    return TRUE;
+#else
+    cons_show("This version of Profanity has not been built with PGP support enabled");
+    return TRUE;
+#endif
+
+}
+
+gboolean
 cmd_otr(gchar **args, struct cmd_help_t help)
 {
 #ifdef HAVE_LIBOTR
diff --git a/src/command/commands.h b/src/command/commands.h
index 7b7e7c93..9fe645e3 100644
--- a/src/command/commands.h
+++ b/src/command/commands.h
@@ -103,6 +103,7 @@ gboolean cmd_nick(gchar **args, struct cmd_help_t help);
 gboolean cmd_notify(gchar **args, struct cmd_help_t help);
 gboolean cmd_online(gchar **args, struct cmd_help_t help);
 gboolean cmd_otr(gchar **args, struct cmd_help_t help);
+gboolean cmd_pgp(gchar **args, struct cmd_help_t help);
 gboolean cmd_outtype(gchar **args, struct cmd_help_t help);
 gboolean cmd_prefs(gchar **args, struct cmd_help_t help);
 gboolean cmd_priority(gchar **args, struct cmd_help_t help);
diff --git a/src/config/account.c b/src/config/account.c
index 3896286b..82294dac 100644
--- a/src/config/account.c
+++ b/src/config/account.c
@@ -49,7 +49,7 @@ account_new(const gchar * const name, const gchar * const jid,
     int priority_away, int priority_xa, int priority_dnd,
     const gchar * const muc_service, const gchar * const muc_nick,
     const gchar * const otr_policy, GList *otr_manual, GList *otr_opportunistic,
-    GList *otr_always)
+    GList *otr_always, const gchar * const pgp_keyid)
 {
     ProfAccount *new_account = malloc(sizeof(ProfAccount));
 
@@ -142,6 +142,12 @@ account_new(const gchar * const name, const gchar * const jid,
     new_account->otr_opportunistic = otr_opportunistic;
     new_account->otr_always = otr_always;
 
+    if (pgp_keyid != NULL) {
+        new_account->pgp_keyid = strdup(pgp_keyid);
+    } else {
+        new_account->pgp_keyid = NULL;
+    }
+
     return new_account;
 }
 
@@ -170,6 +176,7 @@ account_free(ProfAccount *account)
         free(account->muc_service);
         free(account->muc_nick);
         free(account->otr_policy);
+        free(account->pgp_keyid);
         g_list_free_full(account->otr_manual, g_free);
         g_list_free_full(account->otr_opportunistic, g_free);
         g_list_free_full(account->otr_always, g_free);
diff --git a/src/config/account.h b/src/config/account.h
index c237a19e..a49aebd0 100644
--- a/src/config/account.h
+++ b/src/config/account.h
@@ -59,6 +59,7 @@ typedef struct prof_account_t {
     GList *otr_manual;
     GList *otr_opportunistic;
     GList *otr_always;
+    gchar *pgp_keyid;
 } ProfAccount;
 
 ProfAccount* account_new(const gchar * const name, const gchar * const jid,
@@ -68,7 +69,7 @@ ProfAccount* account_new(const gchar * const name, const gchar * const jid,
     int priority_away, int priority_xa, int priority_dnd,
     const gchar * const muc_service, const gchar * const muc_nick,
     const gchar * const otr_policy, GList *otr_manual, GList *otr_opportunistic,
-    GList *otr_always);
+    GList *otr_always, const gchar * const pgp_keyid);
 
 char* account_create_full_jid(ProfAccount *account);
 
diff --git a/src/config/accounts.c b/src/config/accounts.c
index 6c04549c..b18974ca 100644
--- a/src/config/accounts.c
+++ b/src/config/accounts.c
@@ -280,11 +280,16 @@ accounts_get_account(const char * const name)
             g_strfreev(always);
         }
 
+        gchar *pgp_keyid = NULL;
+        if (g_key_file_has_key(accounts, name, "pgp.keyid", NULL)) {
+            pgp_keyid = g_key_file_get_string(accounts, name, "pgp.keyid", NULL);
+        }
+
         ProfAccount *new_account = account_new(name, jid, password, eval_password, enabled,
             server, port, resource, last_presence, login_presence,
             priority_online, priority_chat, priority_away, priority_xa,
             priority_dnd, muc_service, muc_nick, otr_policy, otr_manual,
-            otr_opportunistic, otr_always);
+            otr_opportunistic, otr_always, pgp_keyid);
 
         g_free(jid);
         g_free(password);
@@ -296,6 +301,7 @@ accounts_get_account(const char * const name)
         g_free(muc_service);
         g_free(muc_nick);
         g_free(otr_policy);
+        g_free(pgp_keyid);
 
         return new_account;
     }
@@ -454,6 +460,15 @@ accounts_set_eval_password(const char * const account_name, const char * const v
 }
 
 void
+accounts_set_pgp_keyid(const char * const account_name, const char * const value)
+{
+    if (accounts_account_exists(account_name)) {
+        g_key_file_set_string(accounts, account_name, "pgp.keyid", value);
+        _save_accounts();
+    }
+}
+
+void
 accounts_clear_password(const char * const account_name)
 {
     if (accounts_account_exists(account_name)) {
@@ -490,6 +505,15 @@ accounts_clear_port(const char * const account_name)
 }
 
 void
+accounts_clear_pgp_keyid(const char * const account_name)
+{
+    if (accounts_account_exists(account_name)) {
+        g_key_file_remove_key(accounts, account_name, "pgp.keyid", NULL);
+        _save_accounts();
+    }
+}
+
+void
 accounts_clear_otr(const char * const account_name)
 {
     if (accounts_account_exists(account_name)) {
diff --git a/src/config/accounts.h b/src/config/accounts.h
index 50307b5b..eb981cb8 100644
--- a/src/config/accounts.h
+++ b/src/config/accounts.h
@@ -77,11 +77,13 @@ void accounts_set_priority_dnd(const char * const account_name, const gint value
 void accounts_set_priority_all(const char * const account_name, const gint value);
 gint accounts_get_priority_for_presence_type(const char * const account_name,
     resource_presence_t presence_type);
+void accounts_set_pgp_keyid(const char * const account_name, const char * const value);
 void accounts_clear_password(const char * const account_name);
 void accounts_clear_eval_password(const char * const account_name);
 void accounts_clear_server(const char * const account_name);
 void accounts_clear_port(const char * const account_name);
 void accounts_clear_otr(const char * const account_name);
+void accounts_clear_pgp_keyid(const char * const account_name);
 void accounts_add_otr_policy(const char * const account_name, const char * const contact_jid, const char * const policy);
 
 #endif
diff --git a/src/main.c b/src/main.c
index 3bb7eeb6..ea8f0cea 100644
--- a/src/main.c
+++ b/src/main.c
@@ -121,6 +121,12 @@ main(int argc, char **argv)
         g_print("OTR support: Disabled\n");
 #endif
 
+#ifdef HAVE_LIBGPGME
+        g_print("PGP support: Enabled\n");
+#else
+        g_print("PGP support: Disabled\n");
+#endif
+
         return 0;
     }
 
diff --git a/src/pgp/gpg.c b/src/pgp/gpg.c
new file mode 100644
index 00000000..a998ecc9
--- /dev/null
+++ b/src/pgp/gpg.c
@@ -0,0 +1,374 @@
+/*
+ * gpg.c
+ *
+ * Copyright (C) 2012 - 2015 James Booth <boothj5@gmail.com>
+ *
+ * This file is part of Profanity.
+ *
+ * Profanity is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Profanity is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Profanity.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * In addition, as a special exception, the copyright holders give permission to
+ * link the code of portions of this program with the OpenSSL library under
+ * certain conditions as described in each individual source file, and
+ * distribute linked combinations including the two.
+ *
+ * You must obey the GNU General Public License in all respects for all of the
+ * code used other than OpenSSL. If you modify file(s) with this exception, you
+ * may extend this exception to your version of the file(s), but you are not
+ * obligated to do so. If you do not wish to do so, delete this exception
+ * statement from your version. If you delete this exception statement from all
+ * source files in the program, then also delete it here.
+ *
+ */
+
+#include <locale.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <glib.h>
+#include <gpgme.h>
+
+#include "pgp/gpg.h"
+#include "log.h"
+
+#define PGP_SIGNATURE_HEADER "-----BEGIN PGP SIGNATURE-----"
+#define PGP_SIGNATURE_FOOTER "-----END PGP SIGNATURE-----"
+#define PGP_MESSAGE_HEADER "-----BEGIN PGP MESSAGE-----"
+#define PGP_MESSAGE_FOOTER "-----END PGP MESSAGE-----"
+
+static const char *libversion;
+static GHashTable *fingerprints;
+
+static char* _remove_header_footer(char *str, const char * const footer);
+static char* _add_header_footer(const char * const str, const char * const header, const char * const footer);
+
+void
+p_gpg_init(void)
+{
+    libversion = gpgme_check_version(NULL);
+    log_debug("GPG: Found gpgme version: %s", libversion);
+    gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
+
+    // TODO add close function to clean up
+    fingerprints = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
+}
+
+void
+p_gpg_close(void)
+{
+    g_hash_table_destroy(fingerprints);
+}
+
+GSList *
+p_gpg_list_keys(void)
+{
+    gpgme_error_t error;
+    gpgme_ctx_t ctx;
+    gpgme_key_t key;
+    GSList *result = NULL;
+
+    error = gpgme_new(&ctx);
+    if (error) {
+        log_error("GPG: Could not list keys. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        return NULL;
+    }
+
+    error = gpgme_op_keylist_start(ctx, NULL, 1);
+    if (error == GPG_ERR_NO_ERROR) {
+        while (!error) {
+            error = gpgme_op_keylist_next(ctx, &key);
+            if (error) {
+                break;
+            }
+
+            ProfPGPKey *p_pgpkey = malloc(sizeof(ProfPGPKey));
+            p_pgpkey->id = strdup(key->subkeys->keyid);
+            p_pgpkey->name = strdup(key->uids->uid);
+            p_pgpkey->fp = strdup(key->subkeys->fpr);
+
+            result = g_slist_append(result, p_pgpkey);
+
+            gpgme_key_release(key);
+        }
+    } else {
+        log_error("GPG: Could not list keys. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+    }
+
+    gpgme_release(ctx);
+
+    return result;
+}
+
+GHashTable *
+p_gpg_fingerprints(void)
+{
+    return fingerprints;
+}
+
+const char*
+p_gpg_libver(void)
+{
+    return libversion;
+}
+
+void
+p_gpg_free_key(ProfPGPKey *key)
+{
+    if (key) {
+        free(key->id);
+        free(key->name);
+        free(key->fp);
+        free(key);
+    }
+}
+
+void
+p_gpg_verify(const char * const barejid, const char *const sign)
+{
+    if (!sign) {
+        return;
+    }
+
+    gpgme_ctx_t ctx;
+    gpgme_error_t error = gpgme_new(&ctx);
+    if (error) {
+        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        return;
+    }
+
+    gpgme_data_t sign_data;
+    gpgme_data_t plain_data;
+    char *sign_with_header_footer = _add_header_footer(sign, PGP_SIGNATURE_HEADER, PGP_SIGNATURE_FOOTER);
+    gpgme_data_new_from_mem(&sign_data, sign_with_header_footer, strlen(sign_with_header_footer), 1);
+    gpgme_data_new(&plain_data);
+
+    error = gpgme_op_verify(ctx, sign_data, NULL, plain_data);
+    if (error) {
+        log_error("GPG: Failed to verify. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release(ctx);
+        return;
+    }
+
+    gpgme_verify_result_t result = gpgme_op_verify_result(ctx);
+    if (result) {
+        if (result->signatures) {
+            log_debug("Fingerprint found for %s: %s ", barejid, result->signatures->fpr);
+            g_hash_table_replace(fingerprints, strdup(barejid), strdup(result->signatures->fpr));
+        }
+    }
+
+    gpgme_data_release(sign_data);
+    gpgme_data_release(plain_data);
+}
+
+char*
+p_gpg_sign(const char * const str, const char * const fp)
+{
+    gpgme_ctx_t ctx;
+    gpgme_error_t error = gpgme_new(&ctx);
+    if (error) {
+        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        return NULL;
+    }
+
+    gpgme_key_t key = NULL;
+    error = gpgme_get_key(ctx, fp, &key, 1);
+    if (error || key == NULL) {
+        log_error("GPG: Failed to get key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release (ctx);
+        return NULL;
+    }
+
+    gpgme_signers_clear(ctx);
+    error = gpgme_signers_add(ctx, key);
+    if (error) {
+        log_error("GPG: Failed to load signer. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release(ctx);
+        return NULL;
+    }
+
+    gpgme_data_t str_data;
+    gpgme_data_t signed_data;
+    char *str_or_empty = NULL;
+    if (str) {
+        str_or_empty = strdup(str);
+    } else {
+        str_or_empty = strdup("");
+    }
+    gpgme_data_new_from_mem(&str_data, str_or_empty, strlen(str_or_empty), 1);
+    gpgme_data_new(&signed_data);
+
+    gpgme_set_armor(ctx,1);
+    error = gpgme_op_sign(ctx,str_data,signed_data,GPGME_SIG_MODE_DETACH);
+    if (error) {
+        log_error("GPG: Failed to sign string. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release(ctx);
+        return NULL;
+    }
+
+    char *result = NULL;
+    gpgme_data_release(str_data);
+
+    size_t len = 0;
+    char *signed_str = gpgme_data_release_and_get_mem(signed_data, &len);
+    if (signed_str != NULL) {
+        signed_str[len] = 0;
+        result = _remove_header_footer(signed_str, PGP_SIGNATURE_FOOTER);
+    }
+    gpgme_free(signed_str);
+    gpgme_release(ctx);
+    free(str_or_empty);
+
+    return result;
+}
+
+char *
+p_gpg_encrypt(const char * const barejid, const char * const message)
+{
+    char *fp = g_hash_table_lookup(fingerprints, barejid);
+
+    if (!fp) {
+        return NULL;
+    }
+
+    gpgme_key_t keys[2];
+
+    keys[0] = NULL;
+    keys[1] = NULL;
+
+    gpgme_ctx_t ctx;
+    gpgme_error_t error = gpgme_new(&ctx);
+    if (error) {
+        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        return NULL;
+    }
+
+    gpgme_key_t key;
+    error = gpgme_get_key(ctx, fp, &key, 0);
+    if (error || key == NULL) {
+        log_error("GPG: Failed to get key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release(ctx);
+        return NULL;
+    }
+
+    keys[0] = key;
+
+    gpgme_data_t plain;
+    gpgme_data_t cipher;
+    gpgme_data_new_from_mem(&plain, message, strlen(message), 1);
+    gpgme_data_new(&cipher);
+
+    gpgme_set_armor(ctx, 1);
+    error = gpgme_op_encrypt(ctx, keys, GPGME_ENCRYPT_ALWAYS_TRUST, plain, cipher);
+    if (error) {
+        log_error("GPG: Failed to encrypt message. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release(ctx);
+        return NULL;
+    }
+    gpgme_data_release(plain);
+
+    char *cipher_str = NULL;
+    char *result = NULL;
+    size_t len;
+    cipher_str = gpgme_data_release_and_get_mem(cipher, &len);
+    if (cipher_str) {
+        result = _remove_header_footer(cipher_str, PGP_MESSAGE_FOOTER);
+    }
+
+    gpgme_free(cipher_str);
+    gpgme_release(ctx);
+
+    return result;
+}
+
+char *
+p_gpg_decrypt(const char * const barejid, const char * const cipher)
+{
+    char *cipher_with_headers = _add_header_footer(cipher, PGP_MESSAGE_HEADER, PGP_MESSAGE_FOOTER);
+
+    gpgme_ctx_t ctx;
+    gpgme_error_t error = gpgme_new(&ctx);
+    if (error) {
+        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        return NULL;
+    }
+
+    gpgme_data_t plain_data;
+    gpgme_data_t cipher_data;
+    gpgme_data_new_from_mem (&cipher_data, cipher_with_headers, strlen(cipher_with_headers), 1);
+    gpgme_data_new(&plain_data);
+
+    error = gpgme_op_decrypt(ctx, cipher_data, plain_data);
+    if (error) {
+        log_error("GPG: Failed to encrypt message. %s %s", gpgme_strsource(error), gpgme_strerror(error));
+        gpgme_release(ctx);
+        return NULL;
+    }
+
+    gpgme_data_release(cipher_data);
+
+    size_t len = 0;
+    char *plain_str = gpgme_data_release_and_get_mem(plain_data, &len);
+    char *result = NULL;
+    if (plain_str) {
+        plain_str[len] = 0;
+        result = g_strdup(plain_str);
+    }
+    gpgme_free(plain_str);
+
+    gpgme_release(ctx);
+
+    return result;
+}
+
+static char*
+_remove_header_footer(char *str, const char * const footer)
+{
+    int pos = 0;
+    int newlines = 0;
+
+    while (newlines < 3) {
+        if (str[pos] == '\n') {
+            newlines++;
+        }
+        pos++;
+
+        if (str[pos] == '\0') {
+            return NULL;
+        }
+    }
+
+    char *stripped = strdup(&str[pos]);
+    char *footer_start = g_strrstr(stripped, footer);
+    footer_start[0] = '\0';
+
+    return stripped;
+}
+
+static char*
+_add_header_footer(const char * const str, const char * const header, const char * const footer)
+{
+    GString *result_str = g_string_new("");
+
+    g_string_append(result_str, header);
+    g_string_append(result_str, "\n\n");
+    g_string_append(result_str, str);
+    g_string_append(result_str, "\n");
+    g_string_append(result_str, footer);
+
+    char *result = result_str->str;
+    g_string_free(result_str, FALSE);
+
+    return result;
+}
diff --git a/src/pgp/gpg.h b/src/pgp/gpg.h
new file mode 100644
index 00000000..fb1f0f6b
--- /dev/null
+++ b/src/pgp/gpg.h
@@ -0,0 +1,55 @@
+/*
+ * gpg.h
+ *
+ * Copyright (C) 2012 - 2015 James Booth <boothj5@gmail.com>
+ *
+ * This file is part of Profanity.
+ *
+ * Profanity is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Profanity is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Profanity.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * In addition, as a special exception, the copyright holders give permission to
+ * link the code of portions of this program with the OpenSSL library under
+ * certain conditions as described in each individual source file, and
+ * distribute linked combinations including the two.
+ *
+ * You must obey the GNU General Public License in all respects for all of the
+ * code used other than OpenSSL. If you modify file(s) with this exception, you
+ * may extend this exception to your version of the file(s), but you are not
+ * obligated to do so. If you do not wish to do so, delete this exception
+ * statement from your version. If you delete this exception statement from all
+ * source files in the program, then also delete it here.
+ *
+ */
+
+#ifndef GPG_H
+#define GPG_H
+
+typedef struct pgp_key_t {
+    char *id;
+    char *name;
+    char *fp;
+} ProfPGPKey;
+
+void p_gpg_init(void);
+void p_gpg_close(void);
+GSList* p_gpg_list_keys(void);
+GHashTable* p_gpg_fingerprints(void);
+const char* p_gpg_libver(void);
+void p_gpg_free_key(ProfPGPKey *key);
+char* p_gpg_sign(const char * const str, const char * const fp);
+void p_gpg_verify(const char * const barejid, const char *const sign);
+char* p_gpg_encrypt(const char * const barejid, const char * const message);
+char* p_gpg_decrypt(const char * const barejid, const char * const cipher);
+
+#endif
diff --git a/src/profanity.c b/src/profanity.c
index 6a2966dd..47063ae8 100644
--- a/src/profanity.c
+++ b/src/profanity.c
@@ -59,6 +59,9 @@
 #ifdef HAVE_LIBOTR
 #include "otr/otr.h"
 #endif
+#ifdef HAVE_LIBGPGME
+#include "pgp/gpg.h"
+#endif
 #include "resource.h"
 #include "xmpp/xmpp.h"
 #include "ui/ui.h"
@@ -241,6 +244,9 @@ _init(const int disable_tls, char *log_level)
 #ifdef HAVE_LIBOTR
     otr_init();
 #endif
+#ifdef HAVE_LIBGPGME
+    p_gpg_init();
+#endif
     atexit(_shutdown);
     ui_input_nonblocking(TRUE);
 }
@@ -265,6 +271,9 @@ _shutdown(void)
 #ifdef HAVE_LIBOTR
     otr_shutdown();
 #endif
+#ifdef HAVE_LIBGPGME
+    p_gpg_close();
+#endif
     chat_log_close();
     prefs_close();
     theme_close();
diff --git a/src/ui/console.c b/src/ui/console.c
index 8dfd473f..246dc336 100644
--- a/src/ui/console.c
+++ b/src/ui/console.c
@@ -710,6 +710,10 @@ cons_show_account(ProfAccount *account)
         g_string_free(always, TRUE);
     }
 
+    if (account->pgp_keyid) {
+        cons_show   ("PGP Key ID        : %s", account->pgp_keyid);
+    }
+
     cons_show       ("Priority          : chat:%d, online:%d, away:%d, xa:%d, dnd:%d",
         account->priority_chat, account->priority_online, account->priority_away,
         account->priority_xa, account->priority_dnd);
diff --git a/src/xmpp/message.c b/src/xmpp/message.c
index ac20cbaf..c06ff89d 100644
--- a/src/xmpp/message.c
+++ b/src/xmpp/message.c
@@ -49,6 +49,7 @@
 #include "roster_list.h"
 #include "xmpp/stanza.h"
 #include "xmpp/xmpp.h"
+#include "pgp/gpg.h"
 
 #define HANDLE(ns, type, func) xmpp_handler_add(conn, func, ns, STANZA_NAME_MESSAGE, type, ctx)
 
@@ -104,7 +105,36 @@ message_send_chat(const char * const barejid, const char * const msg)
     }
 
     char *id = create_unique_id("msg");
-    xmpp_stanza_t *message = stanza_create_message(ctx, id, jid, STANZA_TYPE_CHAT, msg);
+    xmpp_stanza_t *message = NULL;
+
+#ifdef HAVE_LIBGPGME
+    char *account_name = jabber_get_account_name();
+    ProfAccount *account = accounts_get_account(account_name);
+    if (account->pgp_keyid) {
+        Jid *jidp = jid_create(jid);
+        char *encrypted = p_gpg_encrypt(jidp->barejid, msg);
+        if (encrypted) {
+            message = stanza_create_message(ctx, id, jid, STANZA_TYPE_CHAT, "This message is encrypted.");
+            xmpp_stanza_t *x = xmpp_stanza_new(ctx);
+            xmpp_stanza_set_name(x, STANZA_NAME_X);
+            xmpp_stanza_set_ns(x, STANZA_NS_ENCRYPTED);
+            xmpp_stanza_t *enc_st = xmpp_stanza_new(ctx);
+            xmpp_stanza_set_text(enc_st, encrypted);
+            xmpp_stanza_add_child(x, enc_st);
+            xmpp_stanza_release(enc_st);
+            xmpp_stanza_add_child(message, x);
+            xmpp_stanza_release(x);
+            free(encrypted);
+        } else {
+            message = stanza_create_message(ctx, id, jid, STANZA_TYPE_CHAT, msg);
+        }
+    } else {
+        message = stanza_create_message(ctx, id, jid, STANZA_TYPE_CHAT, msg);
+    }
+#else
+    message = stanza_create_message(ctx, id, jid, STANZA_TYPE_CHAT, msg);
+#endif
+
     free(jid);
 
     if (state) {
@@ -641,7 +671,23 @@ _chat_handler(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza,
                 if (delayed) {
                     handle_delayed_message(jid->barejid, message, tv_stamp);
                 } else {
+#ifdef HAVE_LIBGPGME
+                    gboolean handled = FALSE;
+                    xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_ENCRYPTED);
+                    if (x) {
+                        char *enc_message = xmpp_stanza_get_text(x);
+                        char *decrypted = p_gpg_decrypt(jid->barejid, enc_message);
+                        if (decrypted) {
+                            handle_incoming_message(jid->barejid, jid->resourcepart, decrypted);
+                            handled = TRUE;
+                        }
+                    }
+                    if (!handled) {
+                        handle_incoming_message(jid->barejid, jid->resourcepart, message);
+                    }
+#else
                     handle_incoming_message(jid->barejid, jid->resourcepart, message);
+#endif
                 }
                 if (id && prefs_get_boolean(PREF_RECEIPTS_SEND)) {
                     xmpp_stanza_t *receipts = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_RECEIPTS);
diff --git a/src/xmpp/presence.c b/src/xmpp/presence.c
index 2be9780a..98c5109e 100644
--- a/src/xmpp/presence.c
+++ b/src/xmpp/presence.c
@@ -49,6 +49,9 @@
 #include "xmpp/connection.h"
 #include "xmpp/stanza.h"
 #include "xmpp/xmpp.h"
+#ifdef HAVE_LIBGPGME
+#include "pgp/gpg.h"
+#endif
 
 static Autocomplete sub_requests_ac;
 
@@ -222,7 +225,31 @@ presence_update(const resource_presence_t presence_type, const char * const msg,
     char *id = create_unique_id("presence");
     xmpp_stanza_set_id(presence, id);
     stanza_attach_show(ctx, presence, show);
+
     stanza_attach_status(ctx, presence, msg);
+
+#ifdef HAVE_LIBGPGME
+    char *account_name = jabber_get_account_name();
+    ProfAccount *account = accounts_get_account(account_name);
+    if (account->pgp_keyid) {
+        char *signed_status = p_gpg_sign(msg, account->pgp_keyid);
+
+        if (signed_status) {
+            xmpp_stanza_t *x = xmpp_stanza_new(ctx);
+            xmpp_stanza_set_name(x, STANZA_NAME_X);
+            xmpp_stanza_set_ns(x, STANZA_NS_SIGNED);
+            xmpp_stanza_t *signed_text = xmpp_stanza_new(ctx);
+            xmpp_stanza_set_text(signed_text, signed_status);
+            xmpp_stanza_add_child(x, signed_text);
+            xmpp_stanza_release(signed_text);
+            xmpp_stanza_add_child(presence, x);
+            xmpp_stanza_release(x);
+
+            free(signed_status);
+        }
+    }
+#endif
+
     stanza_attach_priority(ctx, presence, pri);
     stanza_attach_last_activity(ctx, presence, idle);
     stanza_attach_caps(ctx, presence);
@@ -580,6 +607,16 @@ _available_handler(xmpp_conn_t * const conn,
         log_debug("Presence available handler fired for: %s", jid);
     }
 
+#ifdef HAVE_LIBGPGME
+    xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_SIGNED);
+    if (x) {
+        char *sign = xmpp_stanza_get_text(x);
+        if (sign) {
+            p_gpg_verify(xmpp_presence->jid->barejid, sign);
+        }
+    }
+#endif
+
     const char *my_jid_str = xmpp_conn_get_jid(conn);
     Jid *my_jid = jid_create(my_jid_str);
 
diff --git a/src/xmpp/stanza.h b/src/xmpp/stanza.h
index 89dbda57..042b6aea 100644
--- a/src/xmpp/stanza.h
+++ b/src/xmpp/stanza.h
@@ -160,6 +160,8 @@
 #define STANZA_NS_CARBONS "urn:xmpp:carbons:2"
 #define STANZA_NS_FORWARD "urn:xmpp:forward:0"
 #define STANZA_NS_RECEIPTS "urn:xmpp:receipts"
+#define STANZA_NS_SIGNED "jabber:x:signed"
+#define STANZA_NS_ENCRYPTED "jabber:x:encrypted"
 
 #define STANZA_DATAFORM_SOFTWARE "urn:xmpp:dataforms:softwareinfo"
 
diff --git a/tests/config/stub_accounts.c b/tests/config/stub_accounts.c
index 32a80fda..c046be86 100644
--- a/tests/config/stub_accounts.c
+++ b/tests/config/stub_accounts.c
@@ -122,6 +122,7 @@ void accounts_set_otr_policy(const char * const account_name, const char * const
 }
 
 void accounts_set_last_presence(const char * const account_name, const char * const value) {}
+void accounts_set_pgp_keyid(const char * const account_name, const char * const value) {}
 
 void accounts_set_login_presence(const char * const account_name, const char * const value)
 {
@@ -182,4 +183,5 @@ void accounts_clear_eval_password(const char * const account_name) {}
 void accounts_clear_server(const char * const account_name) {}
 void accounts_clear_port(const char * const account_name) {}
 void accounts_clear_otr(const char * const account_name) {}
+void accounts_clear_pgp_keyid(const char * const account_name) {}
 void accounts_add_otr_policy(const char * const account_name, const char * const contact_jid, const char * const policy) {}
diff --git a/tests/pgp/stub_gpg.c b/tests/pgp/stub_gpg.c
new file mode 100644
index 00000000..14cdfe96
--- /dev/null
+++ b/tests/pgp/stub_gpg.c
@@ -0,0 +1,25 @@
+#include <glib.h>
+
+#include "pgp/gpg.h"
+
+void p_gpg_init(void) {}
+void p_gpg_close(void) {}
+
+GSList* p_gpg_list_keys(void)
+{
+    return NULL;
+}
+
+GHashTable*
+p_gpg_fingerprints(void)
+{
+    return NULL;
+}
+
+const char* p_gpg_libver(void)
+{
+    return NULL;
+}
+
+void p_gpg_free_key(ProfPGPKey *key) {}
+
diff --git a/tests/test_cmd_account.c b/tests/test_cmd_account.c
index d02fc5ba..9dfc2c04 100644
--- a/tests/test_cmd_account.c
+++ b/tests/test_cmd_account.c
@@ -36,7 +36,7 @@ void cmd_account_shows_account_when_connected_and_no_args(void **state)
 {
     CommandHelp *help = malloc(sizeof(CommandHelp));
     ProfAccount *account = account_new("jabber_org", "me@jabber.org", NULL, NULL,
-        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
     gchar *args[] = { NULL };
 
     will_return(jabber_get_connection_status, JABBER_CONNECTED);
@@ -109,7 +109,7 @@ void cmd_account_show_shows_account_when_exists(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "show", "account_name", NULL };
     ProfAccount *account = account_new("jabber_org", "me@jabber.org", NULL, NULL,
-        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
     expect_any(accounts_get_account, name);
     will_return(accounts_get_account, account);
@@ -478,7 +478,7 @@ void cmd_account_set_password_sets_password(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "set", "a_account", "password", "a_password", NULL };
     ProfAccount *account = account_new("a_account", NULL, NULL, NULL,
-    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
 
     expect_any(accounts_account_exists, account_name);
@@ -504,7 +504,7 @@ void cmd_account_set_eval_password_sets_eval_password(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "set", "a_account", "eval_password", "a_password", NULL };
     ProfAccount *account = account_new("a_account", NULL, NULL, NULL,
-    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
 
     expect_any(accounts_account_exists, account_name);
@@ -529,7 +529,7 @@ void cmd_account_set_password_when_eval_password_set(void **state) {
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "set", "a_account", "password", "a_password", NULL };
     ProfAccount *account = account_new("a_account", NULL, NULL, "a_password",
-    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
 
     expect_any(accounts_account_exists, account_name);
@@ -550,7 +550,7 @@ void cmd_account_set_eval_password_when_password_set(void **state) {
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "set", "a_account", "eval_password", "a_password", NULL };
     ProfAccount *account = account_new("a_account", NULL, "a_password", NULL,
-    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+    TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
 
     expect_any(accounts_account_exists, account_name);
diff --git a/tests/test_cmd_connect.c b/tests/test_cmd_connect.c
index e2089a09..90b154d5 100644
--- a/tests/test_cmd_connect.c
+++ b/tests/test_cmd_connect.c
@@ -411,7 +411,7 @@ void cmd_connect_asks_password_when_not_in_account(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "jabber_org", NULL };
     ProfAccount *account = account_new("jabber_org", "me@jabber.org", NULL, NULL,
-        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
     will_return(jabber_get_connection_status, JABBER_DISCONNECTED);
 
@@ -436,7 +436,7 @@ void cmd_connect_shows_message_when_connecting_with_account(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "jabber_org", NULL };
     ProfAccount *account = account_new("jabber_org", "user@jabber.org", "password", NULL,
-        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
     will_return(jabber_get_connection_status, JABBER_DISCONNECTED);
 
@@ -459,7 +459,7 @@ void cmd_connect_connects_with_account(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { "jabber_org", NULL };
     ProfAccount *account = account_new("jabber_org", "me@jabber.org", "password", NULL,
-        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
     will_return(jabber_get_connection_status, JABBER_DISCONNECTED);
 
diff --git a/tests/test_cmd_join.c b/tests/test_cmd_join.c
index 19824b3a..8dc6cf02 100644
--- a/tests/test_cmd_join.c
+++ b/tests/test_cmd_join.c
@@ -76,7 +76,7 @@ void cmd_join_uses_account_mucservice_when_no_service_specified(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { room, "nick", nick, NULL };
     ProfAccount *account = account_new(account_name, "user@server.org", NULL, NULL,
-        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, account_service, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, account_service, NULL, NULL, NULL, NULL, NULL, NULL);
 
     muc_init();
 
@@ -104,7 +104,7 @@ void cmd_join_uses_supplied_nick(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { room, "nick", nick, NULL };
     ProfAccount *account = account_new(account_name, "user@server.org", NULL, NULL,
-        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
     muc_init();
 
@@ -132,7 +132,7 @@ void cmd_join_uses_account_nick_when_not_supplied(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { room, NULL };
     ProfAccount *account = account_new(account_name, "user@server.org", NULL, NULL,
-        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, NULL, account_nick, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, NULL, account_nick, NULL, NULL, NULL, NULL, NULL);
 
     muc_init();
 
@@ -163,7 +163,7 @@ void cmd_join_uses_password_when_supplied(void **state)
     CommandHelp *help = malloc(sizeof(CommandHelp));
     gchar *args[] = { room, "password", password, NULL };
     ProfAccount *account = account_new(account_name, "user@server.org", NULL, NULL,
-        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, account_service, account_nick, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, "laptop", NULL, NULL, 0, 0, 0, 0, 0, account_service, account_nick, NULL, NULL, NULL, NULL, NULL);
 
     muc_init();
 
diff --git a/tests/test_cmd_otr.c b/tests/test_cmd_otr.c
index dae17947..8841be86 100644
--- a/tests/test_cmd_otr.c
+++ b/tests/test_cmd_otr.c
@@ -308,7 +308,7 @@ void cmd_otr_gen_generates_key_for_connected_account(void **state)
     gchar *args[] = { "gen", NULL };
     char *account_name = "myaccount";
     ProfAccount *account = account_new(account_name, "me@jabber.org", NULL, NULL,
-        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL);
+        TRUE, NULL, 0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
 
     will_return(jabber_get_connection_status, JABBER_CONNECTED);
     will_return(jabber_get_account_name, account_name);
ous revision' href='/akkartik/mu/blame/075channel.mu?h=main&id=ef7d834fdd826977cd8d43253052a7b8e1c5aa72'>^
130596f0 ^








5b1219ca ^



b1ddb414 ^
17622b5a ^
5b1219ca ^


6b43e208 ^
760f683f ^
5b1219ca ^
4a48bedc ^
760f683f ^
dd660682 ^
5b1219ca ^
760f683f ^
5b1219ca ^
4a48bedc ^
760f683f ^
dd660682 ^
5b1219ca ^







b6155734 ^
59085fca ^
e765f9e7 ^
b6155734 ^
b6155734 ^
59085fca ^
5b22547b ^

760f683f ^
05fe4be5 ^
dd660682 ^
5b22547b ^
b6155734 ^
5b1219ca ^
9109a916 ^

359586f0 ^
760f683f ^
9109a916 ^
4a48bedc ^
9109a916 ^
7a84094a ^

9109a916 ^


359586f0 ^

760f683f ^
9109a916 ^
4a48bedc ^
9109a916 ^
7a84094a ^
9109a916 ^


7a84094a ^
17622b5a ^
9109a916 ^



7a84094a ^
9109a916 ^


760f683f ^
9109a916 ^
4a48bedc ^
a0331a9b ^
9109a916 ^


433a7c7b ^

760f683f ^
77d5b5d6 ^
4a48bedc ^
a6cdf15c ^
dd660682 ^
a6cdf15c ^
d6ae0078 ^
a6cdf15c ^

dc1323e9 ^
17622b5a ^
5b22547b ^
dc1323e9 ^


17622b5a ^
502d2ea5 ^
dc1323e9 ^
dc1323e9 ^
7a84094a ^
17622b5a ^
502d2ea5 ^
d31d70b6 ^
fd484d9c ^
dc1323e9 ^
dc1323e9 ^
ada5eb55 ^
dc1323e9 ^

c0f43700 ^
17622b5a ^
502d2ea5 ^
a6cdf15c ^

3ac52339 ^
7a84094a ^
ea19d0dc ^
7a84094a ^
a6cdf15c ^
17622b5a ^
502d2ea5 ^
08f4628e ^
3ac52339 ^
502d2ea5 ^
a6cdf15c ^

5b1219ca ^


e765f9e7 ^
5b1219ca ^
a6cdf15c ^

a6cdf15c ^



ad8161f3 ^
760f683f ^


17622b5a ^
ad8161f3 ^
a6cdf15c ^

7a84094a ^
029a3bdf ^
ad8161f3 ^
17622b5a ^
a6cdf15c ^

ad8161f3 ^

029a3bdf ^
ad8161f3 ^
17622b5a ^
a6cdf15c ^

ad8161f3 ^

029a3bdf ^
ad8161f3 ^
17622b5a ^
a6cdf15c ^

ad8161f3 ^

029a3bdf ^
ad8161f3 ^
17622b5a ^
ad8161f3 ^
a6cdf15c ^
65b3db5d ^
a6cdf15c ^




433a7c7b ^


4a48bedc ^
d6ae0078 ^
433a7c7b ^







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

                                                                         
 


                                                                            
 
                                                                           


                  
               
                                                                  
                          
                                                  
   
                         

                                  


   
                         
                                                                            

                             
                                                                          

                                                                             
                

 



                                                                              
                      


                      
                      

 
                                                                     
             
             
                                                       

                                              
                                                              
                                            
                                           
                                  
                                     
                                 
                                       

 
                            
                                                           
             
             
                                     
                                               
                         


                                                   
   


                                                              
                                    




                                                                           
                              

                               
   
                              
                                          
                            
                                                     
                                          
                                                           
                           
                     

                                        
                                      
                                              
                        
                  
   
              
                                             

                                                          

 
                             
                                                                          
             
             
                                   
                                      
                                              


                                                   
   


                                                              
                                      
                       



                                                                            
                              
                        

                               
   
                              
                   
                                          
                                                     
                                        
                  
                                 
                                                              
                          
                     

                                        
                                      
                                              
                        
                  
   
              
                                             

                                                          

 


                                                                           

                                 
               

                                                  

                                              
   
                         

                         



                                        

                                              
       
                          
                                                

                                              
   
                         

                         



                                       


                                                                
       
                               
                                                  

                                              
   
                         

                         



                       






                                                                
       
                              

                                              
                                                      
                          
                                              
                                                     
                               
                                              
   
                         



                                                     


   

                                     
               

                                                  

                                      
   
                         

                     



                                  


                                                                
       
                          

                                      
   
                         

                     



                             


                                                                
       
                          

                                      
   
                         

                     



                                



                                                                
       
                               

                                      
   
                         

                     

   
 
















                                                                     

                                                  
             








                                              



                                                                   
                         
              


                                                            
                                                                                                     
                                                
             
             
                                             
                                          
 
                                            
             
             
                                             
                                          







                                                                                           
                               
                                           
                   
 
                            
                                           

                        
                                          
                                
                              
   
 
 

          
                                                                        
                                                        
             
             
                                             

                                          


                            

                                                                                     
                                                       
             
             
                             
                                         


                                      
                            
                                             



                                 
                                          


                           
                                                 
             
             
                                       


                     

                                                   
                                                                                                           
             
             
                  
                         
   
                                       

                                                             
                     
                                      
                   


                                           
                                     
                               
                                 
         
                                                       
                                                      
                                
                                                    
                                                          
         
                                   
                            

                            
                            
                                            
                         

          
                                   
                   
                                                
                                       
     
                                           
                    
                                       
                                           
                   

          


                                        
            
     

        



                                            
               


                                                                           
                                               
                     

                                                                        
                                                                            
                                            
                                          
                          

                                                                                         

                            
                                            
                                          
                          

                                                                               

                            
                                            
                                          
                          

                                                                               

                                  
                                            
                                          
                                    
                            
                                                                                       
                                  




                        


                                                                     
             
                                    







                                     
# Mu synchronizes between routines using channels rather than locks, like
# Erlang and Go.
#
# The key property of channels: Writing to a full channel or reading from an
# empty one will put the current routine in 'waiting' state until the
# operation can be completed.
#
# Beware of addresses passed into channels. They can cause race conditions.

scenario channel [
  run [
    local-scope
    source:&:source:num, sink:&:sink:num <- new-channel 3/capacity
    sink <- write sink, 34
    10:num/raw, 11:bool/raw, source <- read source
  ]
  memory-should-contain [
    10 <- 34
    11 <- 0  # read was successful
  ]
]

container channel:_elem [
  lock:bool  # inefficient but simple: serialize all reads as well as writes
  first-full:num  # for write
  first-free:num  # for read
  # A circular buffer contains values from index first-full up to (but not
  # including) index first-free. The reader always modifies it at first-full,
  # while the writer always modifies it at first-free.
  data:&:@:_elem
]

# Since channels have two ends, and since it's an error to use either end from
# multiple routines, let's distinguish the ends.

container source:_elem [
  chan:&:channel:_elem
]

container sink:_elem [
  chan:&:channel:_elem
]

def new-channel capacity:num -> in:&:source:_elem, out:&:sink:_elem [
  local-scope
  load-inputs
  result:&:channel:_elem <- new {(channel _elem): type}
  *result <- put *result, first-full:offset, 0
  *result <- put *result, first-free:offset, 0
  capacity <- add capacity, 1  # unused slot for 'full?' below
  data:&:@:_elem <- new _elem:type, capacity
  *result <- put *result, data:offset, data
  in <- new {(source _elem): type}
  *in <- put *in, chan:offset, result
  out <- new {(sink _elem): type}
  *out <- put *out, chan:offset, result
]

# write a value to a channel
def write out:&:sink:_elem, val:_elem -> out:&:sink:_elem [
  local-scope
  load-inputs
  assert out, [write to null channel]
  chan:&:channel:_elem <- get *out, chan:offset
  <channel-write-initial>
  # block until lock is acquired AND queue has room
  lock:location <- get-location *chan, lock:offset
#?   $print [write], 10/newline
  {
#?     $print [trying to acquire lock for writing], 10/newline
    wait-for-reset-then-set lock
#?     $print [lock acquired for writing], 10/newline
    full?:bool <- channel-full? chan
    break-unless full?
#?     $print [but channel is full; relinquishing lock], 10/newline
    # channel is full; relinquish lock and give a reader the opportunity to
    # create room on it
    reset lock
    current-routine-is-blocked
    switch  # avoid spinlocking
    loop
  }
  current-routine-is-unblocked
#?   $print [performing write], 10/newline
  # store a deep copy of val
  circular-buffer:&:@:_elem <- get *chan, data:offset
  free:num <- get *chan, first-free:offset
  *circular-buffer <- put-index *circular-buffer, free, val
  # mark its slot as filled
  free <- add free, 1
  {
    # wrap free around to 0 if necessary
    len:num <- length *circular-buffer
    at-end?:bool <- greater-or-equal free, len
    break-unless at-end?
    free <- copy 0
  }
  # write back
  *chan <- put *chan, first-free:offset, free
#?   $print [relinquishing lock after writing], 10/newline
  reset lock
]

# read a value from a channel
def read in:&:source:_elem -> result:_elem, eof?:bool, in:&:source:_elem [
  local-scope
  load-inputs
  assert in, [read on null channel]
  eof? <- copy false  # default result
  chan:&:channel:_elem <- get *in, chan:offset
  # block until lock is acquired AND queue has data
  lock:location <- get-location *chan, lock:offset
#?   $print [read], 10/newline
  {
#?     $print [trying to acquire lock for reading], 10/newline
    wait-for-reset-then-set lock
#?     $print [lock acquired for reading], 10/newline
    empty?:bool <- channel-empty? chan
    break-unless empty?
#?     $print [but channel is empty; relinquishing lock], 10/newline
    # channel is empty; relinquish lock and give a writer the opportunity to
    # add to it
    reset lock
    current-routine-is-blocked
    <channel-read-empty>
    switch  # avoid spinlocking
    loop
  }
  current-routine-is-unblocked
  # pull result off
  full:num <- get *chan, first-full:offset
  circular-buffer:&:@:_elem <- get *chan, data:offset
  result <- index *circular-buffer, full
  # clear the slot
  empty:&:_elem <- new _elem:type
  *circular-buffer <- put-index *circular-buffer, full, *empty
  # mark its slot as empty
  full <- add full, 1
  {
    # wrap full around to 0 if necessary
    len:num <- length *circular-buffer
    at-end?:bool <- greater-or-equal full, len
    break-unless at-end?
    full <- copy 0
  }
  # write back
  *chan <- put *chan, first-full:offset, full
#?   $print [relinquishing lock after reading], 10/newline
  reset lock
]

# todo: create a notion of iterator and iterable so we can read/write whole
# aggregates (arrays, lists, ..) of _elems at once.

scenario channel-initialization [
  run [
    local-scope
    source:&:source:num <- new-channel 3/capacity
    chan:&:channel:num <- get *source, chan:offset
    10:num/raw <- get *chan, first-full:offset
    11:num/raw <- get *chan, first-free:offset
  ]
  memory-should-contain [
    10 <- 0  # first-full
    11 <- 0  # first-free
  ]
]

scenario channel-write-increments-free [
  local-scope
  _, sink:&:sink:num <- new-channel 3/capacity
  run [
    sink <- write sink, 34
    chan:&:channel:num <- get *sink, chan:offset
    10:num/raw <- get *chan, first-full:offset
    11:num/raw <- get *chan, first-free:offset
  ]
  memory-should-contain [
    10 <- 0  # first-full
    11 <- 1  # first-free
  ]
]

scenario channel-read-increments-full [
  local-scope
  source:&:source:num, sink:&:sink:num <- new-channel 3/capacity
  sink <- write sink, 34
  run [
    _, _, source <- read source
    chan:&:channel:num <- get *source, chan:offset
    10:num/raw <- get *chan, first-full:offset
    11:num/raw <- get *chan, first-free:offset
  ]
  memory-should-contain [
    10 <- 1  # first-full
    11 <- 1  # first-free
  ]
]

scenario channel-wrap [
  local-scope
  # channel with just 1 slot
  source:&:source:num, sink:&:sink:num <- new-channel 1/capacity
  chan:&:channel:num <- get *source, chan:offset
  # write and read a value
  sink <- write sink, 34
  _, _, source <- read source
  run [
    # first-free will now be 1
    10:num/raw <- get *chan, first-free:offset
    11:num/raw <- get *chan, first-free:offset
    # write second value, verify that first-free wraps
    sink <- write sink, 34
    20:num/raw <- get *chan, first-free:offset
    # read second value, verify that first-full wraps
    _, _, source <- read source
    30:num/raw <- get *chan, first-full:offset
  ]
  memory-should-contain [
    10 <- 1  # first-free after first write
    11 <- 1  # first-full after first read
    20 <- 0  # first-free after second write, wrapped
    30 <- 0  # first-full after second read, wrapped
  ]
]

scenario channel-new-empty-not-full [
  run [
    local-scope
    source:&:source:num <- new-channel 3/capacity
    chan:&:channel:num <- get *source, chan:offset
    10:bool/raw <- channel-empty? chan
    11:bool/raw <- channel-full? chan
  ]
  memory-should-contain [
    10 <- 1  # empty?
    11 <- 0  # full?
  ]
]

scenario channel-write-not-empty [
  local-scope
  source:&:source:num, sink:&:sink:num <- new-channel 3/capacity
  chan:&:channel:num <- get *source, chan:offset
  run [
    sink <- write sink, 34
    10:bool/raw <- channel-empty? chan
    11:bool/raw <- channel-full? chan
  ]
  memory-should-contain [
    10 <- 0  # empty?
    11 <- 0  # full?
  ]
]

scenario channel-write-full [
  local-scope
  source:&:source:num, sink:&:sink:num <- new-channel 1/capacity
  chan:&:channel:num <- get *source, chan:offset
  run [
    sink <- write sink, 34
    10:bool/raw <- channel-empty? chan
    11:bool/raw <- channel-full? chan
  ]
  memory-should-contain [
    10 <- 0  # empty?
    11 <- 1  # full?
  ]
]

scenario channel-read-not-full [
  local-scope
  source:&:source:num, sink:&:sink:num <- new-channel 1/capacity
  chan:&:channel:num <- get *source, chan:offset
  sink <- write sink, 34
  run [
    _, _, source <- read source
    10:bool/raw <- channel-empty? chan
    11:bool/raw <- channel-full? chan
  ]
  memory-should-contain [
    10 <- 1  # empty?
    11 <- 0  # full?
  ]
]

scenario channel-clear [
  local-scope
  # create a channel with a few items
  source:&:source:num, sink:&:sink:num <- new-channel 3/capacity
  chan:&:channel:num <- get *sink, chan:offset
  write sink, 30
  write sink, 31
  write sink, 32
  run [
    clear source
    10:bool/raw <- channel-empty? chan
  ]
  memory-should-contain [
    10 <- 1  # after the call to 'clear', the channel should be empty
  ]
]

def clear in:&:source:_elem -> in:&:source:_elem [
  local-scope
  load-inputs
  chan:&:channel:_elem <- get *in, chan:offset
  {
    empty?:bool <- channel-empty? chan
    break-if empty?
    _, _, in <- read in
    loop
  }
]

## cancelling channels

# every channel comes with a boolean signifying if it's been closed
# initially this boolean is false
container channel:_elem [
  closed?:bool
]

# a channel can be closed from either the source or the sink
# both routines can modify the 'closed?' bit, but they can only ever set it, so this is a benign race
def close x:&:source:_elem -> x:&:source:_elem [
  local-scope
  load-inputs
  chan:&:channel:_elem <- get *x, chan:offset
  *chan <- put *chan, closed?:offset, true
]
def close x:&:sink:_elem -> x:&:sink:_elem [
  local-scope
  load-inputs
  chan:&:channel:_elem <- get *x, chan:offset
  *chan <- put *chan, closed?:offset, true
]

# once a channel is closed from one side, no further operations are expected from that side
# if a channel is closed for reading,
#   no further writes will be let through
# if a channel is closed for writing,
#   future reads continue until the channel empties,
#   then the channel is also closed for reading
after <channel-write-initial> [
  closed?:bool <- get *chan, closed?:offset
  return-if closed?
]
after <channel-read-empty> [
  closed?:bool <- get *chan, closed?:offset
  {
    break-unless closed?
    empty-result:&:_elem <- new _elem:type
    current-routine-is-unblocked
    return *empty-result, true
  }
]

## helpers

# An empty channel has first-free and first-full both at the same value.
def channel-empty? chan:&:channel:_elem -> result:bool [
  local-scope
  load-inputs
  # return chan.first-full == chan.first-free
  full:num <- get *chan, first-full:offset
  free:num <- get *chan, first-free:offset
  result <- equal full, free
]

# A full channel has first-free just before first-full, wasting one slot.
# (Other alternatives: https://www.snellman.net/blog/archive/2016-12-13-ring-buffers)
def channel-full? chan:&:channel:_elem -> result:bool [
  local-scope
  load-inputs
  # tmp = chan.first-free + 1
  tmp:num <- get *chan, first-free:offset
  tmp <- add tmp, 1
  {
    # if tmp == chan.capacity, tmp = 0
    len:num <- capacity chan
    at-end?:bool <- greater-or-equal tmp, len
    break-unless at-end?
    tmp <- copy 0
  }
  # return chan.first-full == tmp
  full:num <- get *chan, first-full:offset
  result <- equal full, tmp
]

def capacity chan:&:channel:_elem -> result:num [
  local-scope
  load-inputs
  q:&:@:_elem <- get *chan, data:offset
  result <- length *q
]

## helpers for channels of characters in particular

def buffer-lines in:&:source:char, buffered-out:&:sink:char -> buffered-out:&:sink:char, in:&:source:char [
  local-scope
  load-inputs
  # repeat forever
  eof?:bool <- copy false
  {
    line:&:buffer:char <- new-buffer 30
    # read characters from 'in' until newline, copy into line
    {
      +next-character
      c:char, eof?:bool, in <- read in
      break-if eof?
      # drop a character on backspace
      {
        # special-case: if it's a backspace
        backspace?:bool <- equal c, 8
        break-unless backspace?
        # drop previous character
        {
          buffer-length:num <- get *line, length:offset
          buffer-empty?:bool <- equal buffer-length, 0
          break-if buffer-empty?
          buffer-length <- subtract buffer-length, 1
          *line <- put *line, length:offset, buffer-length
        }
        # and don't append this one
        loop +next-character
      }
      # append anything else
      line <- append line, c
      line-done?:bool <- equal c, 10/newline
      break-if line-done?
      loop
    }
    # copy line into 'buffered-out'
    i:num <- copy 0
    line-contents:text <- get *line, data:offset
    max:num <- get *line, length:offset
    {
      done?:bool <- greater-or-equal i, max
      break-if done?
      c:char <- index *line-contents, i
      buffered-out <- write buffered-out, c
      i <- add i, 1
      loop
    }
    {
      break-unless eof?
      buffered-out <- close buffered-out
      return
    }
    loop
  }
]

scenario buffer-lines-blocks-until-newline [
  run [
    local-scope
    source:&:source:char, sink:&:sink:char <- new-channel 10/capacity
    _, buffered-stdin:&:sink:char/buffered-stdin <- new-channel 10/capacity
    buffered-chan:&:channel:char <- get *buffered-stdin, chan:offset
    empty?:bool <- channel-empty? buffered-chan
    assert empty?, [ 
F buffer-lines-blocks-until-newline: channel should be empty after init]
    # buffer stdin into buffered-stdin, try to read from buffered-stdin
    buffer-routine:num <- start-running buffer-lines, source, buffered-stdin
    wait-for-routine-to-block buffer-routine
    empty? <- channel-empty? buffered-chan
    assert empty?:bool, [ 
F buffer-lines-blocks-until-newline: channel should be empty after buffer-lines bring-up]
    # write 'a'
    sink <- write sink, 97/a
    restart buffer-routine
    wait-for-routine-to-block buffer-routine
    empty? <- channel-empty? buffered-chan
    assert empty?:bool, [ 
F buffer-lines-blocks-until-newline: channel should be empty after writing 'a']
    # write 'b'
    sink <- write sink, 98/b
    restart buffer-routine
    wait-for-routine-to-block buffer-routine
    empty? <- channel-empty? buffered-chan
    assert empty?:bool, [ 
F buffer-lines-blocks-until-newline: channel should be empty after writing 'b']
    # write newline
    sink <- write sink, 10/newline
    restart buffer-routine
    wait-for-routine-to-block buffer-routine
    empty? <- channel-empty? buffered-chan
    data-emitted?:bool <- not empty?
    assert data-emitted?, [ 
F buffer-lines-blocks-until-newline: channel should contain data after writing newline]
    trace 1, [test], [reached end]
  ]
  trace-should-contain [
    test: reached end
  ]
]

def drain source:&:source:char -> result:text, source:&:source:char [
  local-scope
  load-inputs
  buf:&:buffer:char <- new-buffer 30
  {
    c:char, done?:bool <- read source
    break-if done?
    buf <- append buf, c
    loop
  }
  result <- buffer-to-array buf
]