diff --git a/palm-client/Makefile b/palm-client/Makefile index 4f6098c..b3fbb2c 100644 --- a/palm-client/Makefile +++ b/palm-client/Makefile @@ -10,7 +10,7 @@ APP = visormesh NAME = VisorMesh CREATOR = VMsh -SRCS = src/main.c src/app.c src/home_form.c src/convo_form.c src/node_form.c src/channel_form.c src/convos.c src/protocol.c src/sha256.c src/transport_srm.c src/session.c src/settings.c src/presets.c src/contacts.c src/contacts_form.c src/messages.c src/channels.c src/preview_form.c src/ui/draw.c src/ui/text.c src/ui/rowlist.c src/ui/fontmetrics.c src/ports.c +SRCS = src/main.c src/app.c src/home_form.c src/convo_form.c src/node_form.c src/channel_form.c src/convos.c src/protocol.c src/sha256.c src/transport_srm.c src/session.c src/settings.c src/presets.c src/contacts.c src/contacts_form.c src/contact_form.c src/heard.c src/messages.c src/channels.c src/preview_form.c src/ui/draw.c src/ui/text.c src/ui/rowlist.c src/ui/fontmetrics.c src/ports.c OBJS = $(SRCS:src/%.c=build/%.o) CC = m68k-palmos-gcc diff --git a/palm-client/resources/visormesh.rcp b/palm-client/resources/visormesh.rcp index 8ae1868..89cdd71 100644 --- a/palm-client/resources/visormesh.rcp +++ b/palm-client/resources/visormesh.rcp @@ -90,6 +90,61 @@ BEGIN SCROLLBAR ID ContactsScroll AT (153 16 7 128) VALUE 0 MIN 0 MAX 0 PAGESIZE 1 BUTTON "Refresh" ID ContactsRefreshButton AT (1 147 AUTO AUTO) BUTTON "Done" ID ContactsDoneButton AT (PREVRIGHT+5 PREVTOP AUTO AUTO) + BUTTON "Add" ID ContactsAddButton AT (PREVRIGHT+5 PREVTOP AUTO AUTO) +END + +/* One contact: details and signal history */ +FORM ID ContactForm AT (0 0 160 160) +NOFRAME +USABLE +MENUID MainMenuBar +BEGIN + TITLE " " + GADGET ID ContactGadget AT (0 16 153 128) + SCROLLBAR ID ContactScroll AT (153 16 7 128) VALUE 0 MIN 0 MAX 0 PAGESIZE 1 + BUTTON "Done" ID ContactDoneButton AT (1 147 AUTO AUTO) + BUTTON "Message" ID ContactMessageButton AT (PREVRIGHT+4 PREVTOP AUTO AUTO) + BUTTON "Login" ID ContactLoginButton AT (PREVRIGHT+4 PREVTOP AUTO AUTO) + BUTTON "More" ID ContactMoreButton AT (PREVRIGHT+4 PREVTOP AUTO AUTO) + LIST "Reset Path" "Remove" ID ContactMoreList AT (100 122 58 AUTO) NONUSABLE VISIBLEITEMS 2 +END + +FORM ID ContactAddForm AT (0 0 160 160) +NOFRAME +USABLE +BEGIN + TITLE "Add Contact" + LABEL "Name:" AUTOID AT (5 20) FONT 1 + FIELD ID ContactAddNameField AT (40 20 115 12) UNDERLINED SINGLELINE EDITABLE MAXCHARS 31 + LABEL "Type:" AUTOID AT (5 38) FONT 1 + PUSHBUTTON "Chat" ID ContactAddChatPush AT (40 37 36 12) GROUP ContactAddTypeGroup + PUSHBUTTON "Room" ID ContactAddRoomPush AT (PREVRIGHT+1 PREVTOP 36 12) GROUP ContactAddTypeGroup + PUSHBUTTON "Repeater" ID ContactAddRepeaterPush AT (PREVRIGHT+1 PREVTOP 42 12) GROUP ContactAddTypeGroup + LABEL "Public key (64 hex digits):" AUTOID AT (5 58) FONT 1 + FIELD ID ContactAddKeyField AT (5 72 150 36) UNDERLINED MULTIPLELINES EDITABLE MAXCHARS 80 + LABEL "For a node you haven't heard an advert" AUTOID AT (5 112) + LABEL "from yet. Its path starts unknown (flood)." AUTOID AT (5 123) + BUTTON "Add" ID ContactAddAddButton AT (5 145 AUTO AUTO) + BUTTON "Cancel" ID ContactAddCancelButton AT (PREVRIGHT+6 PREVTOP AUTO AUTO) + GRAFFITISTATEINDICATOR AT (145 147) +END + +ALERT ID PasswordAlert +CONFIRMATION +DEFAULTBUTTON 1 +BEGIN + TITLE "Log In" + MESSAGE "Password for ^1:" + BUTTONS "Log In" "Cancel" +END + +ALERT ID RemoveContactAlert +WARNING +DEFAULTBUTTON 1 +BEGIN + TITLE "Remove Contact" + MESSAGE "Remove ^1 from the radio's contacts? Its messages stay on the Visor." + BUTTONS "Remove" "Cancel" END ALERT ID ContactInfoAlert diff --git a/palm-client/src/app.c b/palm-client/src/app.c index daa196a..3445ade 100644 --- a/palm-client/src/app.c +++ b/palm-client/src/app.c @@ -61,6 +61,8 @@ void AppErrorText(Err err, Char *out) StrCopy(out, "Message too long."); else if (err == serErrNotOpen) StrCopy(out, "Not connected."); + else if (err == vmErrLoginFailed) + StrCopy(out, "Login refused: wrong password?"); else StrPrintF(out, "Error 0x%x.", err); } diff --git a/palm-client/src/contact_form.c b/palm-client/src/contact_form.c new file mode 100644 index 0000000..198715c --- /dev/null +++ b/palm-client/src/contact_form.c @@ -0,0 +1,392 @@ +/* + * A contact's details and signal history, and Add Contact (by key, for a node + * the radio hasn't heard an advert from). + * + * Detail: type, route, last heard, the full key, then every time the radio + * heard the node directly (its own zero-hop adverts, or relaying packets for a + * repeater) with SNR and RSSI. Message opens the DM; for a room it logs in + * first if needed. Login asks for the password; More has Reset Path and + * Remove. + */ +#include +#include "resources.h" +#include "protocol.h" +#include "session.h" +#include "contacts.h" +#include "contacts_form.h" +#include "heard.h" +#include "app.h" +#include "ui/draw.h" +#include "ui/text.h" +#include "ui/rowlist.h" +#include "contact_form.h" + +/* In an extra code segment (VM_SECT3): see sections.h for the rules. */ +static void *GetObject(FormType *form, UInt16 id) VM_SECT3; +static void Error(const Char *msg) VM_SECT3; +static void ErrorFor(Err err) VM_SECT3; +static void FormatWhen(Char *out, UInt32 utc) VM_SECT3; +static void DrawHex(const UInt8 *bytes, UInt16 n, Coord x, Coord y) VM_SECT3; +static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) VM_SECT3; +static void Load(void) VM_SECT3; +static void Status(const Char *text) VM_SECT3; +static Boolean Login(FormType *form) VM_SECT3; +static void OpenConversation(void) VM_SECT3; +static Boolean ReloadContact(void) VM_SECT3; +static void More(FormType *form) VM_SECT3; +static void ShowButtons(FormType *form) VM_SECT3; +static Boolean Add(FormType *form) VM_SECT3; + +#define INFO_ROWS 5 /* type/route, heard, key x2, the Signal header */ +#define MAX_HIST (VM_HEARD_MAX) + +static VmContact gContact; +static VmHeard gHist[MAX_HIST]; +static UInt16 gHistCount; +static RowList gList; +static Char gTitle[VM_NAME_SIZE + 2]; + +void ContactFormOpen(const VmContact *c) +{ + gContact = *c; + FrmGotoForm(ContactForm); +} + +static void *GetObject(FormType *form, UInt16 id) +{ + return FrmGetObjectPtr(form, FrmGetObjectIndex(form, id)); +} + +static void Error(const Char *msg) +{ + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); +} + +static void ErrorFor(Err err) +{ + Char msg[48]; + + AppErrorText(err, msg); + Error(msg); +} + +/* "11-01 17:32", local time. */ +static void FormatWhen(Char *out, UInt32 utc) +{ + DateTimeType dt; + + TimSecondsToDateTime(SessionLocalPalm(utc), &dt); + StrPrintF(out, "%02u-%02u %02u:%02u", dt.month, dt.day, dt.hour, dt.minute); +} + +static void DrawHex(const UInt8 *bytes, UInt16 n, Coord x, Coord y) +{ + Char hex[2 * 16 + 1]; + UInt16 i; + + for (i = 0; i < n && i < 16; i++) + StrPrintF(hex + 2 * i, "%02x", bytes[i]); + WinDrawChars(hex, (Int16)(2 * i), x, y); +} + +static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) +{ + FontID old = FntSetFont(vmSmallFont); + Coord x = b->topLeft.x + 1, y = b->topLeft.y, right = b->topLeft.x + b->extent.x - 1; + Char line[48], route[12], when[16], snr[8]; + UInt32 now = SessionNow(); + + switch (row) { + case 0: + line[0] = ContactTypeGlyph(gContact.type); + ContactFormatRoute(route, gContact.outPathLen); + StrPrintF(line + 1, " %s, %s%s", ContactTypeName(gContact.type), route, + SessionIsLoggedIn(gContact.pubKey) ? ", logged in" : ""); + WinDrawChars(line, StrLen(line), x, y); + break; + case 1: + if (gContact.lastAdvert) { + FormatWhen(when, gContact.lastAdvert); + TxtFormatAge(route, now > gContact.lastAdvert ? now - gContact.lastAdvert : 0); + StrPrintF(line, "Advert %s (%s ago)", when, route); + } else { + StrCopy(line, "No advert heard yet"); + } + WinDrawChars(line, StrLen(line), x, y); + break; + case 2: + WinDrawChars("Key", 3, x, y); + DrawHex(gContact.pubKey, 16, x + 18, y); + break; + case 3: + DrawHex(gContact.pubKey + 16, 16, x + 18, y); + break; + case 4: + DrawSection(gHistCount ? "heard directly" : "not heard directly yet", b->topLeft.x, y, b->extent.x); + break; + default: { + const VmHeard *h = &gHist[row - INFO_ROWS]; + + FormatWhen(when, h->time); + WinDrawChars(when, StrLen(when), x, y); + if (h->kind == VM_HEARD_ADVERT_FAR) { + /* the signal is the last repeater's, not this node's */ + StrPrintF(line, "advert via %u hop%s", h->advertHops, h->advertHops == 1 ? "" : "s"); + DrawRight(line, right, y); + break; + } + TxtFormatSnr(snr, h->snrQ); + StrPrintF(line, "%s %ddBm", snr, (Int16)h->rssi); + WinDrawChars(line, StrLen(line), x + 48, y); + if (h->kind == VM_HEARD_RELAY && h->count > 1) + StrPrintF(line, "relay x%u", h->count); + else + StrCopy(line, h->kind == VM_HEARD_RELAY ? "relay" : "advert"); + DrawRight(line, right, y); + break; + } + } + FntSetFont(old); +} + +static void Load(void) +{ + /* a repeater is heard relaying others' packets; anything else only by its adverts */ + gHistCount = HeardFor(gContact.pubKey, gContact.type == VM_ADV_TYPE_REPEATER, gHist, MAX_HIST); + RowListSetCount(&gList, INFO_ROWS + gHistCount); +} + +/* A line of progress over the bottom of the list while the radio works. */ +static void Status(const Char *text) +{ + FormType *form = FrmGetActiveForm(); + RectangleType r; + FontID old; + + FrmGetObjectBounds(form, FrmGetObjectIndex(form, ContactGadget), &r); + r.topLeft.y += r.extent.y - VM_ROW_H - 1; + r.extent.y = VM_ROW_H + 1; + WinEraseRectangle(&r, 0); + WinDrawLine(r.topLeft.x, r.topLeft.y, r.topLeft.x + r.extent.x - 1, r.topLeft.y); + old = FntSetFont(vmSmallFont); + WinDrawChars(text, StrLen(text), r.topLeft.x + 2, r.topLeft.y + 1); + FntSetFont(old); +} + +/* Asks for the password and logs in; true on success. */ +static Boolean Login(FormType *form) +{ + Char pw[VM_NAME_SIZE], msg[48]; + Boolean admin = false; + Err err; + + if (!SessionIsConnected()) { + Error("Connect to the radio first (Node)."); + return false; + } + pw[0] = 0; + if (FrmCustomResponseAlert(PasswordAlert, gContact.name, "", "", pw, sizeof(pw), NULL) != 0) + return false; + Status("Logging in (waiting for an answer over the mesh)..."); + err = SessionLogin(gContact.pubKey, pw, &admin); + MemSet(pw, sizeof(pw), 0); + RowListDraw(&gList); + if (err != errNone) { + if (err == vmErrNoReply) + Error("No answer: the node may be out of range. Try again, or Reset Path under More."); + else + ErrorFor(err); + return false; + } + if (gContact.type != VM_ADV_TYPE_ROOM) { + StrPrintF(msg, "Logged in to %s%s.", gContact.name, admin ? " as admin" : ""); + FrmCustomAlert(ContactInfoAlert, "Login", msg, ""); + } + return true; +} + +static void OpenConversation(void) +{ + VmConv conv; + + MemSet(&conv, sizeof(conv), 0); + conv.type = VM_CONV_DIRECT; + MemMove(conv.key, gContact.pubKey, 6); + AppOpenConversation(&conv); +} + +/* Re-reads the contact after a refresh; false if it's gone. */ +static Boolean ReloadContact(void) +{ + return ContactsFindByPrefixN(gContact.pubKey, VM_PUB_KEY_SIZE, &gContact); +} + +static void More(FormType *form) +{ + ListType *list = GetObject(form, ContactMoreList); + Int16 pick = LstPopupList(list); + Err err; + + if (pick < 0) + return; + if (!SessionIsConnected()) { + Error("Connect to the radio first (Node)."); + return; + } + if (pick == 0) { /* Reset Path */ + err = SessionKeyCommand(VM_CMD_RESET_PATH, gContact.pubKey); + if (err == errNone) + err = ContactsRefresh(NULL); + if (err != errNone) + ErrorFor(err); + ReloadContact(); + RowListDraw(&gList); + } else if (pick == 1) { /* Remove */ + if (FrmCustomAlert(RemoveContactAlert, gContact.name, "", "") != 0) + return; + err = SessionKeyCommand(VM_CMD_REMOVE_CONTACT, gContact.pubKey); + if (err == errNone) + err = ContactsRefresh(NULL); + if (err != errNone) { + ErrorFor(err); + return; + } + FrmGotoForm(ContactsForm); + } +} + +/* Message for nodes that take text (companions, rooms), Login for rooms and repeaters. */ +static void ShowButtons(FormType *form) +{ + UInt8 t = gContact.type; + UInt16 msg = FrmGetObjectIndex(form, ContactMessageButton), login = FrmGetObjectIndex(form, ContactLoginButton); + + if (t == VM_ADV_TYPE_CHAT || t == VM_ADV_TYPE_ROOM) + FrmShowObject(form, msg); + else + FrmHideObject(form, msg); + if (t == VM_ADV_TYPE_ROOM || t == VM_ADV_TYPE_REPEATER) + FrmShowObject(form, login); + else + FrmHideObject(form, login); +} + +Boolean ContactFormHandleEvent(EventType *event) +{ + FormType *form = FrmGetActiveForm(); + Int16 tapped = -1; + + switch (event->eType) { + case frmOpenEvent: + StrNCopy(gTitle, gContact.name, VM_NAME_SIZE - 1); + gTitle[VM_NAME_SIZE - 1] = 0; + FrmCopyTitle(form, gTitle); + RowListInit(&gList, ContactGadget, ContactScroll, VM_ROW_H, DrawRow, NULL, NULL); + Load(); + FrmDrawForm(form); + ShowButtons(form); + RowListDraw(&gList); + return true; + + case frmUpdateEvent: + if (event->data.frmUpdate.updateCode == frmRedrawUpdateCode) { + FrmDrawForm(form); + ShowButtons(form); + } + Load(); + RowListDraw(&gList); + return true; + + case ctlSelectEvent: + switch (event->data.ctlSelect.controlID) { + case ContactDoneButton: + FrmGotoForm(ContactsForm); + return true; + case ContactMessageButton: + /* a room only takes posts from members: log in first */ + if (gContact.type == VM_ADV_TYPE_ROOM && !SessionIsLoggedIn(gContact.pubKey) && !Login(form)) + return true; + OpenConversation(); + return true; + case ContactLoginButton: + if (Login(form) && gContact.type == VM_ADV_TYPE_ROOM) + OpenConversation(); + else + RowListDraw(&gList); + return true; + case ContactMoreButton: + More(form); + return true; + } + break; + + default: + break; + } + return RowListHandleEvent(&gList, event, &tapped); +} + +/* ---- Add Contact ---- */ + +static Boolean Add(FormType *form) +{ + const Char *name = FldGetTextPtr(GetObject(form, ContactAddNameField)); + const Char *hex = FldGetTextPtr(GetObject(form, ContactAddKeyField)); + UInt16 sel = FrmGetObjectId(form, FrmGetControlGroupSelection(form, ContactAddTypeGroup)); + UInt8 key[VM_PUB_KEY_SIZE], type; + VmContact c; + Err err; + + if (!SessionIsConnected()) { + Error("Connect to the radio first (Node)."); + return false; + } + if (!name || !*name) { + Error("Enter a name for the contact."); + return false; + } + if (!hex || !VmParseHex(hex, key, sizeof(key)) || StrLen(hex) < 2 * VM_PUB_KEY_SIZE) { + Error("The key is 64 hex digits (0-9, a-f); spaces are fine."); + return false; + } + type = sel == ContactAddRoomPush ? VM_ADV_TYPE_ROOM : + sel == ContactAddRepeaterPush ? VM_ADV_TYPE_REPEATER : VM_ADV_TYPE_CHAT; + err = SessionAddContact(key, type, name); + if (err == errNone) + err = ContactsRefresh(NULL); + if (err != errNone) { + ErrorFor(err); + return false; + } + if (ContactsFindByPrefixN(key, VM_PUB_KEY_SIZE, &c)) + ContactFormOpen(&c); + else + FrmGotoForm(ContactsForm); + return true; +} + +Boolean ContactAddFormHandleEvent(EventType *event) +{ + FormType *form = FrmGetActiveForm(); + + switch (event->eType) { + case frmOpenEvent: + FrmSetControlGroupSelection(form, ContactAddTypeGroup, ContactAddChatPush); + FrmDrawForm(form); + FrmSetFocus(form, FrmGetObjectIndex(form, ContactAddNameField)); + return true; + case ctlSelectEvent: + switch (event->data.ctlSelect.controlID) { + case ContactAddAddButton: + Add(form); + return true; + case ContactAddCancelButton: + FrmGotoForm(ContactsForm); + return true; + } + break; + default: + break; + } + return false; +} diff --git a/palm-client/src/contact_form.h b/palm-client/src/contact_form.h new file mode 100644 index 0000000..510b140 --- /dev/null +++ b/palm-client/src/contact_form.h @@ -0,0 +1,13 @@ +#ifndef VM_CONTACT_FORM_H +#define VM_CONTACT_FORM_H + +#include +#include "sections.h" /* this module is in the third code segment */ +#include "protocol.h" + +/* Shows a contact's detail screen. */ +void ContactFormOpen(const VmContact *c) VM_SECT3; +Boolean ContactFormHandleEvent(EventType *event) VM_SECT3; +Boolean ContactAddFormHandleEvent(EventType *event) VM_SECT3; + +#endif diff --git a/palm-client/src/contacts.c b/palm-client/src/contacts.c index 2b23a93..5cd2dc9 100644 --- a/palm-client/src/contacts.c +++ b/palm-client/src/contacts.c @@ -67,6 +67,11 @@ Boolean ContactsGet(UInt16 index, VmContact *out) } Boolean ContactsFindByPrefix(const UInt8 *prefix6, VmContact *out) +{ + return ContactsFindByPrefixN(prefix6, 6, out); +} + +Boolean ContactsFindByPrefixN(const UInt8 *prefix, UInt16 len, VmContact *out) { UInt16 i, n; MemHandle h; @@ -82,7 +87,7 @@ Boolean ContactsFindByPrefix(const UInt8 *prefix6, VmContact *out) if (!h) continue; c = MemHandleLock(h); - if (MemCmp(c->pubKey, prefix6, 6) == 0) { + if (MemCmp(c->pubKey, prefix, len) == 0) { MemMove(out, c, sizeof(VmContact)); found = true; } diff --git a/palm-client/src/contacts.h b/palm-client/src/contacts.h index 7ee6894..b7192a6 100644 --- a/palm-client/src/contacts.h +++ b/palm-client/src/contacts.h @@ -15,6 +15,8 @@ UInt16 ContactsCount(void) VM_SECT2; Boolean ContactsGet(UInt16 index, VmContact *out) VM_SECT2; /* Finds a contact by the first 6 bytes of its key (how DMs name their sender). */ Boolean ContactsFindByPrefix(const UInt8 *prefix6, VmContact *out) VM_SECT2; +/* Same with the first n bytes (room posts name their author by 4). */ +Boolean ContactsFindByPrefixN(const UInt8 *prefix, UInt16 n, VmContact *out) VM_SECT2; /* * Downloads the radio's whole contact list and replaces the stored one. The diff --git a/palm-client/src/contacts_form.c b/palm-client/src/contacts_form.c index 6ef4175..d4661b1 100644 --- a/palm-client/src/contacts_form.c +++ b/palm-client/src/contacts_form.c @@ -1,8 +1,8 @@ /* * Contacts, MeshTerm style: our node pinned first (star), then the stored * contacts by name, each with its type mark, name, when it was last heard and - * its route. Refresh downloads the list; tap a contact for its details and - * Message to open a direct conversation. + * its route. Refresh downloads the list, Add adds one by key; tap a contact + * for its details. */ #include #include "resources.h" @@ -15,11 +15,9 @@ #include "ui/text.h" #include "ui/rowlist.h" #include "contacts_form.h" +#include "contact_form.h" /* In the second code segment: see sections.h for the rules. */ -static Char TypeGlyph(UInt8 type) VM_SECT2; -static const Char *TypeName(UInt8 type) VM_SECT2; -static void FormatRoute(Char *out, UInt8 pathLen) VM_SECT2; static UInt16 SelfRows(void) VM_SECT2; static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) VM_SECT2; static void Load(Boolean draw) VM_SECT2; @@ -33,7 +31,7 @@ static void ShowDetails(UInt16 row) VM_SECT2; static RowList gList; -static Char TypeGlyph(UInt8 type) +Char ContactTypeGlyph(UInt8 type) { switch (type) { case VM_ADV_TYPE_CHAT: return GLYPH_COMPANION; @@ -44,7 +42,7 @@ static Char TypeGlyph(UInt8 type) } } -static const Char *TypeName(UInt8 type) +const Char *ContactTypeName(UInt8 type) { switch (type) { case VM_ADV_TYPE_CHAT: return "Companion"; @@ -56,7 +54,7 @@ static const Char *TypeName(UInt8 type) } /* "direct", "2 hops", or "flood" (no known path). */ -static void FormatRoute(Char *out, UInt8 pathLen) +void ContactFormatRoute(Char *out, UInt8 pathLen) { UInt8 hops = VM_PATH_HOPS(pathLen); @@ -93,7 +91,7 @@ static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) FntSetFont(old); return; } - mark = TypeGlyph(c.type); + mark = ContactTypeGlyph(c.type); WinDrawChars(&mark, 1, x + 1, y); DrawCut(c.name, x + NAME_X, y, NAME_W); if (c.lastAdvert) { @@ -102,7 +100,7 @@ static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) TxtFormatAge(buf, now > c.lastAdvert ? now - c.lastAdvert : 0); DrawRight(buf, x + HEARD_R, y); } - FormatRoute(buf, c.outPathLen); + ContactFormatRoute(buf, c.outPathLen); DrawRight(buf, right - 1, y); FntSetFont(old); } @@ -145,28 +143,9 @@ static void Refresh(FormType *form) static void ShowDetails(UInt16 row) { VmContact c; - DateTimeType dt; - VmConv conv; - Char line[96], route[12]; - if (row < SelfRows() || !ContactsGet(row - SelfRows(), &c)) - return; - FormatRoute(route, c.outPathLen); - if (c.lastAdvert) { - TimSecondsToDateTime(SessionLocalPalm(c.lastAdvert), &dt); - StrPrintF(line, "%s, %s\nKey %02x%02x%02x%02x%02x%02x...\nHeard %u-%02u-%02u %02u:%02u", - TypeName(c.type), route, c.pubKey[0], c.pubKey[1], c.pubKey[2], c.pubKey[3], c.pubKey[4], - c.pubKey[5], dt.year, dt.month, dt.day, dt.hour, dt.minute); - } else { - StrPrintF(line, "%s, %s\nKey %02x%02x%02x%02x%02x%02x...", TypeName(c.type), route, - c.pubKey[0], c.pubKey[1], c.pubKey[2], c.pubKey[3], c.pubKey[4], c.pubKey[5]); - } - if (FrmCustomAlert(ContactInfoAlert, c.name, line, "") == 1) { /* Message */ - MemSet(&conv, sizeof(conv), 0); - conv.type = VM_CONV_DIRECT; - MemMove(conv.key, c.pubKey, 6); - AppOpenConversation(&conv); - } + if (row >= SelfRows() && ContactsGet(row - SelfRows(), &c)) + ContactFormOpen(&c); } Boolean ContactsFormHandleEvent(EventType *event) @@ -198,6 +177,12 @@ Boolean ContactsFormHandleEvent(EventType *event) case ContactsDoneButton: FrmGotoForm(HomeForm); return true; + case ContactsAddButton: + if (SessionIsConnected()) + FrmGotoForm(ContactAddForm); + else + FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first (Node).", "", ""); + return true; } break; diff --git a/palm-client/src/contacts_form.h b/palm-client/src/contacts_form.h index 5e2bb0a..a836701 100644 --- a/palm-client/src/contacts_form.h +++ b/palm-client/src/contacts_form.h @@ -6,4 +6,9 @@ Boolean ContactsFormHandleEvent(EventType *event) VM_SECT2; +/* The type mark and name, and "direct" / "2 hops" / "flood" for a path length. */ +Char ContactTypeGlyph(UInt8 type) VM_SECT2; +const Char *ContactTypeName(UInt8 type) VM_SECT2; +void ContactFormatRoute(Char *out, UInt8 pathLen) VM_SECT2; + #endif diff --git a/palm-client/src/convo_form.c b/palm-client/src/convo_form.c index c970ad2..f28ff7c 100644 --- a/palm-client/src/convo_form.c +++ b/palm-client/src/convo_form.c @@ -80,6 +80,8 @@ static void SenderOf(const VmMsgHeader *h, Char *out, UInt16 size) StrPrintF(out, "%c %s", GLYPH_SELF, SessionSelf()->name[0] ? SessionSelf()->name : "you"); else if (h->conv.type == VM_CONV_CHANNEL) StrNCopy(out, h->sender[0] ? h->sender : "?", size - 1); + else if (h->sender[0]) /* a room post: its author */ + StrNCopy(out, h->sender, size - 1); else ContactNameForPrefix(h->conv.key, out, size); out[size - 1] = 0; diff --git a/palm-client/src/heard.c b/palm-client/src/heard.c new file mode 100644 index 0000000..491411d --- /dev/null +++ b/palm-client/src/heard.c @@ -0,0 +1,99 @@ +#include +#include "heard.h" +#include "app.h" + +/* In an extra code segment (VM_SECT3): see sections.h for the rules. */ +static void Add(UInt8 kind, const UInt8 *id, UInt8 idLen, const VmRxLog *rx, UInt32 now) VM_SECT3; + +#define VM_HEARD_PREFS_ID 1 +#define VM_HEARD_PREFS_VERSION 1 +#define MERGE_SECS 60 + +static VmHeard gHeard[VM_HEARD_MAX]; /* ring, gNext is the oldest slot */ +static UInt16 gUsed = 0, gNext = 0; + +void HeardLoad(void) +{ + UInt16 size = sizeof(gHeard); + + if (PrefGetAppPreferences(VM_CREATOR, VM_HEARD_PREFS_ID, gHeard, &size, false) == VM_HEARD_PREFS_VERSION && + size == sizeof(gHeard)) { + for (gUsed = 0; gUsed < VM_HEARD_MAX && gHeard[gUsed].time; gUsed++) + ; + gNext = gUsed % VM_HEARD_MAX; + /* a full ring: the oldest is after the newest */ + if (gUsed == VM_HEARD_MAX) { + UInt16 i, newest = 0; + + for (i = 1; i < VM_HEARD_MAX; i++) + if (gHeard[i].time >= gHeard[newest].time) + newest = i; + gNext = (newest + 1) % VM_HEARD_MAX; + } + } else { + MemSet(gHeard, sizeof(gHeard), 0); + gUsed = gNext = 0; + } +} + +void HeardSave(void) +{ + PrefSetAppPreferences(VM_CREATOR, VM_HEARD_PREFS_ID, VM_HEARD_PREFS_VERSION, gHeard, sizeof(gHeard), false); +} + +static void Add(UInt8 kind, const UInt8 *id, UInt8 idLen, const VmRxLog *rx, UInt32 now) +{ + UInt16 i; + VmHeard *h; + + /* the same node heard the same way within a minute: update that entry */ + for (i = 0; i < gUsed; i++) { + h = &gHeard[i]; + if (h->kind == kind && h->idLen == idLen && MemCmp(h->id, id, idLen) == 0 && + now >= h->time && now - h->time < MERGE_SECS) { + h->time = now; + h->snrQ = (Int8)rx->snrQ; + h->rssi = rx->rssi; + if (h->count < 255) + h->count++; + return; + } + } + h = &gHeard[gNext]; + MemSet(h, sizeof(*h), 0); + h->time = now; + MemMove(h->id, id, idLen); + h->idLen = idLen; + h->count = 1; + h->snrQ = (Int8)rx->snrQ; + h->rssi = rx->rssi; + h->kind = kind; + h->advertHops = rx->hops; + gNext = (gNext + 1) % VM_HEARD_MAX; + if (gUsed < VM_HEARD_MAX) + gUsed++; +} + +void HeardRecord(const VmRxLog *rx, UInt32 now) +{ + if (rx->isAdvert) + Add(rx->hops == 0 ? VM_HEARD_ADVERT : VM_HEARD_ADVERT_FAR, rx->advertKey, 6, rx, now); + if (rx->fromLen && rx->fromLen < 6) + Add(VM_HEARD_RELAY, rx->from, rx->fromLen, rx, now); +} + +UInt16 HeardFor(const UInt8 *pubKey, Boolean relays, VmHeard *out, UInt16 max) +{ + UInt16 n = 0, k; + + /* newest first: walk back from the slot before gNext */ + for (k = 1; k <= gUsed && n < max; k++) { + const VmHeard *h = &gHeard[(gNext + VM_HEARD_MAX - k) % VM_HEARD_MAX]; + + if (h->kind == VM_HEARD_RELAY && !relays) + continue; + if (MemCmp(h->id, pubKey, h->idLen) == 0) + out[n++] = *h; + } + return n; +} diff --git a/palm-client/src/heard.h b/palm-client/src/heard.h new file mode 100644 index 0000000..8e1bf41 --- /dev/null +++ b/palm-client/src/heard.h @@ -0,0 +1,42 @@ +/* + * Signal history: who the radio heard directly, and how well, from its RX log + * pushes. Each entry is a node heard at one time: a zero-hop advert names the + * advertiser by key prefix, a flooded packet names its last relay by path + * hash (1-3 bytes). Repeat hearings of the same node within a minute update + * one entry. Kept in memory and in an unsaved preference across launches. + */ +#ifndef VM_HEARD_H +#define VM_HEARD_H + +#include +#include "sections.h" /* this module is in the third code segment */ +#include "protocol.h" + +#define VM_HEARD_MAX 48 + +typedef struct { + UInt32 time; /* Unix seconds of the latest hearing */ + UInt8 id[6]; /* key prefix or path hash */ + UInt8 idLen; + UInt8 count; /* hearings merged into this entry */ + Int8 snrQ; /* the latest: quarter dB */ + Int8 rssi; + UInt8 kind; /* VM_HEARD_ADVERT (its own advert) or VM_HEARD_RELAY (relaying a packet) */ + UInt8 advertHops; /* VM_HEARD_ADVERT_FAR: an advert that came through repeaters */ +} VmHeard; + +#define VM_HEARD_ADVERT 0 +#define VM_HEARD_RELAY 1 +#define VM_HEARD_ADVERT_FAR 2 /* its advert, via advertHops repeaters: the signal is the last relay's */ + +void HeardLoad(void) VM_SECT3; +void HeardSave(void) VM_SECT3; +void HeardRecord(const VmRxLog *rx, UInt32 now) VM_SECT3; +/* + * The entries for a node, newest first: fills up to max, returns how many. + * Relay entries only match when relays is true (repeaters: a companion + * doesn't forward, so a hash match would be another node). + */ +UInt16 HeardFor(const UInt8 *pubKey, Boolean relays, VmHeard *out, UInt16 max) VM_SECT3; + +#endif diff --git a/palm-client/src/main.c b/palm-client/src/main.c index c7c2181..6adebf9 100644 --- a/palm-client/src/main.c +++ b/palm-client/src/main.c @@ -8,6 +8,8 @@ #include "home_form.h" #include "convo_form.h" #include "contacts_form.h" +#include "contact_form.h" +#include "heard.h" #include "node_form.h" #include "settings.h" #include "ports.h" @@ -68,6 +70,8 @@ static Boolean AppHandleEvent(EventType *event) case PortsForm: FrmSetEventHandler(form, PortsFormHandleEvent); break; case FontPreviewForm: FrmSetEventHandler(form, FontPreviewFormHandleEvent); break; case ChannelForm: FrmSetEventHandler(form, ChannelFormHandleEvent); break; + case ContactForm: FrmSetEventHandler(form, ContactFormHandleEvent); break; + case ContactAddForm: FrmSetEventHandler(form, ContactAddFormHandleEvent); break; } return true; } @@ -151,9 +155,11 @@ UInt32 PilotMain(UInt16 cmd, MemPtr cmdPBP, UInt16 launchFlags) if (cmd == sysAppLaunchCmdNormalLaunch) { UiFontInit(); AppLoadPrefs(); + HeardLoad(); FrmGotoForm(HomeForm); AppEventLoop(); SessionDisconnect(); + HeardSave(); FrmCloseAllForms(); ContactsClose(); ChannelsClose(); diff --git a/palm-client/src/messages.c b/palm-client/src/messages.c index b870260..157b210 100644 --- a/palm-client/src/messages.c +++ b/palm-client/src/messages.c @@ -2,6 +2,7 @@ #include "protocol.h" #include "ui/text.h" #include "messages.h" +#include "contacts.h" /* In the second code segment: see sections.h for the rules. */ static Err Append(const VmMsgHeader *hdr, const Char *text, UInt16 *index) VM_SECT2; @@ -124,6 +125,14 @@ Err MessagesAddIncoming(const VmMessage *m, UInt32 now) } else { hdr.conv.type = VM_CONV_DIRECT; MemMove(hdr.conv.key, m->senderPrefix, 6); + if (m->hasSigner) { /* a room post: file it under its author */ + VmContact author; + + if (ContactsFindByPrefixN(m->signer, 4, &author)) + StrNCopy(hdr.sender, author.name, VM_NAME_SIZE - 1); + else + StrPrintF(hdr.sender, "%02x%02x%02x%02x", m->signer[0], m->signer[1], m->signer[2], m->signer[3]); + } } hdr.dir = VM_DIR_IN; hdr.unread = 1; diff --git a/palm-client/src/protocol.c b/palm-client/src/protocol.c index 03398a4..961a51a 100644 --- a/palm-client/src/protocol.c +++ b/palm-client/src/protocol.c @@ -398,6 +398,47 @@ UInt16 VmBuildSendAdvert(UInt8 *out, UInt16 outSize, Boolean flood) return VmEncodeFrame(out, outSize, p, 2); } +/* CMD_SEND_LOGIN: code, pub_key[32], password (rest of frame). */ +UInt16 VmBuildLogin(UInt8 *out, UInt16 outSize, const UInt8 *pubKey, const UInt8 *password, UInt16 pwLen) +{ + UInt8 p[1 + VM_PUB_KEY_SIZE + VM_NAME_SIZE]; + + if (pwLen > VM_NAME_SIZE) + return 0; + p[0] = VM_CMD_SEND_LOGIN; + CopyBytes(p + 1, pubKey, VM_PUB_KEY_SIZE); + CopyBytes(p + 1 + VM_PUB_KEY_SIZE, password, pwLen); + return VmEncodeFrame(out, outSize, p, (UInt16)(1 + VM_PUB_KEY_SIZE + pwLen)); +} + +UInt16 VmBuildKeyCommand(UInt8 *out, UInt16 outSize, UInt8 code, const UInt8 *pubKey) +{ + UInt8 p[1 + VM_PUB_KEY_SIZE]; + + p[0] = code; + CopyBytes(p + 1, pubKey, VM_PUB_KEY_SIZE); + return VmEncodeFrame(out, outSize, p, sizeof(p)); +} + +/* CMD_ADD_UPDATE_CONTACT: code, pub_key[32], type, flags, out_path_len, out_path[64], name[32], last_advert. */ +UInt16 VmBuildAddContact(UInt8 *out, UInt16 outSize, const UInt8 *pubKey, UInt8 type, + const UInt8 *name, UInt16 nameLen) +{ + UInt8 p[1 + VM_PUB_KEY_SIZE + 3 + VM_MAX_PATH_SIZE + VM_NAME_SIZE + 4]; + UInt16 i; + + if (nameLen == 0 || nameLen > VM_NAME_SIZE - 1) + return 0; + for (i = 0; i < sizeof(p); i++) + p[i] = 0; + p[0] = VM_CMD_ADD_UPDATE_CONTACT; + CopyBytes(p + 1, pubKey, VM_PUB_KEY_SIZE); + p[1 + VM_PUB_KEY_SIZE] = type; + p[1 + VM_PUB_KEY_SIZE + 2] = VM_PATH_UNKNOWN; /* no path yet: flood */ + CopyBytes(p + 1 + VM_PUB_KEY_SIZE + 3 + VM_MAX_PATH_SIZE, name, nameLen); + return VmEncodeFrame(out, outSize, p, sizeof(p)); +} + /* CMD_REBOOT: code + "reboot" (the firmware checks the word, so a stray byte can't reboot it). */ UInt16 VmBuildReboot(UInt8 *out, UInt16 outSize) { @@ -526,10 +567,13 @@ Boolean VmParseMessage(const UInt8 *p, UInt16 len, VmMessage *out) out->txtType = p[i++]; out->timestamp = GetLE32(p + i); i += 4; + out->hasSigner = 0; if (!out->isChannel && out->txtType == VM_TXT_TYPE_SIGNED_PLAIN) { if (len < i + 4) return 0; - i += 4; /* signer's key prefix */ + CopyBytes(out->signer, p + i, 4); /* the author, e.g. of a room post */ + out->hasSigner = 1; + i += 4; } out->text = p + i; out->textLen = (UInt16)(len - i); @@ -575,3 +619,57 @@ Boolean VmParseCurrTime(const UInt8 *p, UInt16 len, UInt32 *unixSeconds) *unixSeconds = GetLE32(p + 1); return 1; } + +/* LOGIN_SUCCESS: code, permissions, prefix[6], ...; LOGIN_FAIL: code, 0, prefix[6]. */ +Boolean VmParseLoginResult(const UInt8 *p, UInt16 len, Boolean *ok, Boolean *isAdmin, UInt8 *prefix6) +{ + if (len < 8 || (p[0] != VM_PUSH_LOGIN_SUCCESS && p[0] != VM_PUSH_LOGIN_FAIL)) + return 0; + *ok = p[0] == VM_PUSH_LOGIN_SUCCESS; + *isAdmin = *ok && (p[1] & 1); + CopyBytes(prefix6, p + 2, 6); + return 1; +} + +/* LOG_RX: code, snr*4, rssi, then the raw packet: header, [transport codes], path_len, path, payload. */ +Boolean VmParseRxLog(const UInt8 *p, UInt16 len, VmRxLog *out) +{ + UInt16 i = 3, pathBytes; + UInt8 header, route, size; + + if (len < 5 || p[0] != VM_PUSH_LOG_RX) + return 0; + out->snrQ = (Int8)p[1]; + out->rssi = (Int8)p[2]; + header = p[i++]; + route = header & 0x03; + out->payloadType = (UInt8)((header >> 2) & 0x0F); + if (route == 0 || route == 3) /* transport codes */ + i += 4; + if (len < i + 1) + return 0; + out->hops = VM_PATH_HOPS(p[i]); + size = VM_PATH_HASH_BYTES(p[i]); + if (size > 3) + return 0; + pathBytes = (UInt16)out->hops * size; + i++; + if (len < i + pathBytes) + return 0; + out->isAdvert = 0; + out->fromLen = 0; + if (out->payloadType == VM_PAYLOAD_ADVERT && len >= i + pathBytes + 6) { + out->isAdvert = 1; + CopyBytes(out->advertKey, p + i + pathBytes, 6); + } + if (route == 1 || route == 0) { /* flood: the path is who relayed it, in order */ + if (out->hops > 0) { + out->fromLen = size; + CopyBytes(out->from, p + i + pathBytes - size, size); + } else if (out->isAdvert) { + out->fromLen = 6; + CopyBytes(out->from, out->advertKey, 6); + } + } + return 1; +} diff --git a/palm-client/src/protocol.h b/palm-client/src/protocol.h index d541a19..d8de9fe 100644 --- a/palm-client/src/protocol.h +++ b/palm-client/src/protocol.h @@ -53,10 +53,15 @@ typedef char Char; #define VM_CMD_SET_DEVICE_TIME 6 #define VM_CMD_SEND_SELF_ADVERT 7 #define VM_CMD_SET_ADVERT_NAME 8 +#define VM_CMD_ADD_UPDATE_CONTACT 9 #define VM_CMD_SYNC_NEXT_MESSAGE 10 #define VM_CMD_SET_RADIO_PARAMS 11 #define VM_CMD_SET_RADIO_TX_POWER 12 +#define VM_CMD_RESET_PATH 13 +#define VM_CMD_REMOVE_CONTACT 15 #define VM_CMD_REBOOT 19 +#define VM_CMD_SEND_LOGIN 26 +#define VM_CMD_LOGOUT 29 #define VM_CMD_DEVICE_QUERY 22 #define VM_CMD_GET_CHANNEL 31 #define VM_CMD_SET_CHANNEL 32 @@ -82,6 +87,9 @@ typedef char Char; #define VM_PUSH_PATH_UPDATED 0x81 #define VM_PUSH_SEND_CONFIRMED 0x82 #define VM_PUSH_MSG_WAITING 0x83 +#define VM_PUSH_LOGIN_SUCCESS 0x85 +#define VM_PUSH_LOGIN_FAIL 0x86 +#define VM_PUSH_LOG_RX 0x88 #define VM_PUSH_NEW_ADVERT 0x8A #define VM_IS_PUSH(code) ((code) >= 0x80) @@ -183,6 +191,8 @@ typedef struct { UInt8 senderPrefix[6];/* contact messages: first 6 bytes of the sender's key */ UInt8 pathLen; /* 0xFF = direct */ UInt8 txtType; + Boolean hasSigner; /* signed text (e.g. a room post): signer is the author's key prefix */ + UInt8 signer[4]; UInt32 timestamp; /* sender's clock, seconds since 1970 */ const UInt8 *text; /* points into the payload; not NUL-terminated */ UInt16 textLen; @@ -228,6 +238,13 @@ UInt16 VmBuildSendChannelTxt(UInt8 *out, UInt16 outSize, UInt8 channelIdx, UInt3 UInt16 VmBuildGetTime(UInt8 *out, UInt16 outSize) VM_SECT2; UInt16 VmBuildSetTime(UInt8 *out, UInt16 outSize, UInt32 unixSeconds) VM_SECT2; UInt16 VmBuildSendAdvert(UInt8 *out, UInt16 outSize, Boolean flood) VM_SECT2; +/* Room/repeater login: the full 32-byte key and a password (UTF-8, may be empty). Reply SENT, then a login push. */ +UInt16 VmBuildLogin(UInt8 *out, UInt16 outSize, const UInt8 *pubKey, const UInt8 *password, UInt16 pwLen) VM_SECT2; +/* Commands that take only a full 32-byte key: VM_CMD_LOGOUT, VM_CMD_RESET_PATH, VM_CMD_REMOVE_CONTACT. */ +UInt16 VmBuildKeyCommand(UInt8 *out, UInt16 outSize, UInt8 code, const UInt8 *pubKey) VM_SECT2; +/* CMD_ADD_UPDATE_CONTACT for a node we only know by key: unknown path, no advert time yet. */ +UInt16 VmBuildAddContact(UInt8 *out, UInt16 outSize, const UInt8 *pubKey, UInt8 type, + const UInt8 *name, UInt16 nameLen) VM_SECT2; /* CMD_REBOOT: the radio restarts without replying. */ UInt16 VmBuildReboot(UInt8 *out, UInt16 outSize) VM_SECT2; @@ -242,5 +259,26 @@ Boolean VmParseChannelInfo(const UInt8 *p, UInt16 len, VmChannel *out) VM_SECT2; Boolean VmParseSent(const UInt8 *p, UInt16 len, VmSent *out) VM_SECT2; Boolean VmParseSendConfirmed(const UInt8 *p, UInt16 len, UInt32 *ack, UInt32 *tripMs) VM_SECT2; Boolean VmParseCurrTime(const UInt8 *p, UInt16 len, UInt32 *unixSeconds) VM_SECT2; +/* + * PUSH_LOG_RX: a packet the radio received, with its signal. 'from' names the + * node we heard it from directly, when that's known: the advertiser of a + * zero-hop advert (fromLen 6, its key prefix), or the last repeater on a + * flooded packet's path (fromLen = the path hash size, 1-3 bytes). + */ +typedef struct { + Int16 snrQ; /* SNR in quarter dB */ + Int8 rssi; /* dBm */ + UInt8 payloadType; /* 4 = advert */ + UInt8 hops; + Boolean isAdvert; + UInt8 advertKey[6]; /* the advertiser (any hop count), if isAdvert */ + UInt8 fromLen; /* 0 = not known */ + UInt8 from[6]; +} VmRxLog; +#define VM_PAYLOAD_ADVERT 4 +Boolean VmParseRxLog(const UInt8 *p, UInt16 len, VmRxLog *out) VM_SECT2; + +/* PUSH_LOGIN_SUCCESS / PUSH_LOGIN_FAIL: which node (key prefix) and, on success, whether we're admin. */ +Boolean VmParseLoginResult(const UInt8 *p, UInt16 len, Boolean *ok, Boolean *isAdmin, UInt8 *prefix6) VM_SECT2; #endif diff --git a/palm-client/src/resources.h b/palm-client/src/resources.h index 7de4472..160fd78 100644 --- a/palm-client/src/resources.h +++ b/palm-client/src/resources.h @@ -50,6 +50,29 @@ #define ContactsScroll 1302 #define ContactsRefreshButton 1303 #define ContactsDoneButton 1304 +#define ContactsAddButton 1305 + +#define ContactForm 1800 +#define ContactGadget 1801 +#define ContactScroll 1802 +#define ContactDoneButton 1803 +#define ContactMessageButton 1804 +#define ContactLoginButton 1805 +#define ContactMoreButton 1806 +#define ContactMoreList 1807 + +#define ContactAddForm 1900 +#define ContactAddNameField 1901 +#define ContactAddChatPush 1902 +#define ContactAddRoomPush 1903 +#define ContactAddRepeaterPush 1904 +#define ContactAddKeyField 1905 +#define ContactAddAddButton 1906 +#define ContactAddCancelButton 1907 +#define ContactAddTypeGroup 4 + +#define PasswordAlert 2007 +#define RemoveContactAlert 2008 #define HomeForm 1500 #define HomeGadget 1501 diff --git a/palm-client/src/session.c b/palm-client/src/session.c index 2c7e583..94d029e 100644 --- a/palm-client/src/session.c +++ b/palm-client/src/session.c @@ -6,6 +6,7 @@ #include "contacts.h" #include "ui/text.h" #include "session.h" +#include "heard.h" #define VM_APP_NAME "VisorMesh" #define VM_REPLY_TIMEOUT (2 * SysTicksPerSecond()) @@ -69,6 +70,11 @@ static void HandlePush(void) } else if (code == VM_PUSH_SEND_CONFIRMED) { if (VmParseSendConfirmed(gDecoder.payload, gDecoder.len, &ack, &trip) && MessagesAcked(ack)) gChanged |= VM_CHANGED_MESSAGES; + } else if (code == VM_PUSH_LOG_RX) { + VmRxLog rx; + + if (VmParseRxLog(gDecoder.payload, gDecoder.len, &rx)) + HeardRecord(&rx, SessionNow()); } else if (code == VM_PUSH_ADVERT || code == VM_PUSH_NEW_ADVERT || code == VM_PUSH_PATH_UPDATED) { gChanged |= VM_CHANGED_CONTACTS; } @@ -487,6 +493,82 @@ UInt16 SessionPoll(void) return changed; } +/* Rooms logged into this session (key prefixes); the firmware keeps them alive. */ +#define VM_MAX_LOGINS 4 +static UInt8 gLogins[VM_MAX_LOGINS][6]; +static UInt16 gLoginCount = 0; + +Boolean SessionIsLoggedIn(const UInt8 *prefix6) +{ + UInt16 i; + + for (i = 0; i < gLoginCount; i++) + if (MemCmp(gLogins[i], prefix6, 6) == 0) + return true; + return false; +} + +Err SessionLogin(const UInt8 *pubKey, const Char *password, Boolean *isAdmin) +{ + static const UInt8 sentCode[] = { VM_RESP_SENT }; + static const UInt8 resultCodes[] = { VM_PUSH_LOGIN_SUCCESS, VM_PUSH_LOGIN_FAIL }; + UInt8 frame[VM_HEADER_LEN + 1 + VM_PUB_KEY_SIZE + VM_NAME_SIZE]; + UInt8 pw[VM_NAME_SIZE], prefix[6]; + UInt16 len, n; + VmSent sent; + Boolean ok; + Int32 wait; + Err err; + + if (!gConnected) + return serErrNotOpen; + n = TxtPalmToUtf8(password, StrLen(password), pw, sizeof(pw)); + if (*password && n == 0) + return vmErrTooLong; + len = VmBuildLogin(frame, sizeof(frame), pubKey, pw, n); + err = RequestAny(frame, len, sentCode, 1, 1); + if (err == errNone && !VmParseSent(gDecoder.payload, gDecoder.len, &sent)) + err = vmErrBadReply; + if (err != errNone) + return err; + /* the answer comes back over the mesh: wait as long as the radio estimates, plus slack */ + wait = (Int32)((sent.timeoutMs + 5000UL) / 1000UL) * SysTicksPerSecond(); + err = WaitForAny(resultCodes, 2, wait); + if (err != errNone) + return err; + if (!VmParseLoginResult(gDecoder.payload, gDecoder.len, &ok, isAdmin, prefix)) + return vmErrBadReply; + if (!ok) + return vmErrLoginFailed; + if (!SessionIsLoggedIn(prefix) && gLoginCount < VM_MAX_LOGINS) + MemMove(gLogins[gLoginCount++], prefix, 6); + return errNone; +} + +Err SessionKeyCommand(UInt8 code, const UInt8 *pubKey) +{ + UInt8 frame[VM_HEADER_LEN + 1 + VM_PUB_KEY_SIZE]; + UInt16 len = VmBuildKeyCommand(frame, sizeof(frame), code, pubKey); + + if (!gConnected) + return serErrNotOpen; + return Request(frame, len, VM_RESP_OK, 1); +} + +Err SessionAddContact(const UInt8 *pubKey, UInt8 type, const Char *name) +{ + UInt8 frame[VM_HEADER_LEN + 1 + VM_PUB_KEY_SIZE + 3 + VM_MAX_PATH_SIZE + VM_NAME_SIZE + 4]; + UInt8 utf8[VM_NAME_SIZE]; + UInt16 n = TxtPalmToUtf8(name, StrLen(name), utf8, VM_NAME_SIZE - 1), len; + + if (!gConnected) + return serErrNotOpen; + if (n == 0) + return vmErrTooLong; + len = VmBuildAddContact(frame, sizeof(frame), pubKey, type, utf8, n); + return Request(frame, len, VM_RESP_OK, 1); +} + Err SessionSendAdvert(Boolean flood) { UInt8 frame[VM_HEADER_LEN + 2]; @@ -530,6 +612,7 @@ void SessionDisconnect(void) { TransportClose(); gConnected = false; + gLoginCount = 0; /* the radio keeps room sessions alive, but re-check after a reconnect */ } Boolean SessionIsConnected(void) diff --git a/palm-client/src/session.h b/palm-client/src/session.h index 12a0abf..1cf3c5f 100644 --- a/palm-client/src/session.h +++ b/palm-client/src/session.h @@ -14,6 +14,7 @@ #define vmErrRadio (appErrorClass | 2) /* radio replied RESP_ERR */ #define vmErrBadReply (appErrorClass | 3) /* reply had the right code but didn't parse */ #define vmErrTooLong (appErrorClass | 4) /* message text over the byte limit */ +#define vmErrLoginFailed (appErrorClass | 5) /* a room/repeater refused the password */ /* What SessionPoll found changed, so the screen on show can redraw. */ #define VM_CHANGED_MESSAGES 0x0001 @@ -85,4 +86,15 @@ Err SessionSend(const VmConv *conv, const Char *text, UInt16 *index); Err SessionRetry(UInt16 index); Err SessionSendAdvert(Boolean flood); +/* + * Logs into a room (or repeater) by its full key: waits for the answer over + * the mesh (vmErrLoginFailed for a wrong password, vmErrNoReply if none). + */ +Err SessionLogin(const UInt8 *pubKey, const Char *password, Boolean *isAdmin); +Boolean SessionIsLoggedIn(const UInt8 *prefix6); +/* VM_CMD_RESET_PATH, VM_CMD_REMOVE_CONTACT, VM_CMD_LOGOUT for a full key; needs RESP_OK. */ +Err SessionKeyCommand(UInt8 code, const UInt8 *pubKey); +/* Adds a contact the radio hasn't heard yet, by its full key (unknown path). */ +Err SessionAddContact(const UInt8 *pubKey, UInt8 type, const Char *name); + #endif diff --git a/palm-client/tests/test_protocol.c b/palm-client/tests/test_protocol.c index a7af0d6..cb29a47 100644 --- a/palm-client/tests/test_protocol.c +++ b/palm-client/tests/test_protocol.c @@ -240,6 +240,69 @@ static void test_sha256_and_channels(void) testKey) == 0); } +static void test_contacts_and_rooms(void) +{ + UInt8 out[200], key[32], prefix[6]; + Boolean ok, admin; + VmFrameDecoder d; + VmMessage m; + UInt16 i; + static const UInt8 success[] = { 0x3e, 0x0e, 0x00, 0x85, 0x01, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 3, 1 }; + static const UInt8 fail[] = { 0x3e, 0x08, 0x00, 0x86, 0x00, 1, 2, 3, 4, 5, 6 }; + + for (i = 0; i < 32; i++) + key[i] = (UInt8)(0x40 + i); + + CHECK(VmBuildLogin(out, sizeof(out), key, (const UInt8 *)"hello", 5) == 3 + 1 + 32 + 5); + CHECK(out[3] == 26 && out[4] == 0x40 && out[35] == 0x5f && memcmp(out + 36, "hello", 5) == 0); + CHECK(VmBuildLogin(out, sizeof(out), key, (const UInt8 *)"", 0) == 3 + 1 + 32); /* empty password */ + + CHECK(VmBuildKeyCommand(out, sizeof(out), VM_CMD_REMOVE_CONTACT, key) == 3 + 33); + CHECK(out[3] == 15 && out[4] == 0x40 && out[35] == 0x5f); + CHECK(VmBuildKeyCommand(out, sizeof(out), VM_CMD_RESET_PATH, key) == 3 + 33 && out[3] == 13); + CHECK(VmBuildKeyCommand(out, sizeof(out), VM_CMD_LOGOUT, key) == 3 + 33 && out[3] == 29); + + /* same layout as a CONTACT record (MyMesh::updateContactFromFrame), without the optional tail */ + CHECK(VmBuildAddContact(out, sizeof(out), key, VM_ADV_TYPE_ROOM, (const UInt8 *)"Room", 4) == 3 + 1 + 32 + 3 + 64 + 32 + 4); + CHECK(out[3] == 9 && out[4 + 32] == 3 && out[4 + 33] == 0 && out[4 + 34] == 0xff); + CHECK(memcmp(out + 4 + 35 + 64, "Room", 4) == 0 && out[4 + 35 + 64 + 4] == 0); + CHECK(VmBuildAddContact(out, sizeof(out), key, 1, (const UInt8 *)"", 0) == 0); + + decode_one(&d, success, sizeof(success)); + CHECK(VmParseLoginResult(d.payload, d.len, &ok, &admin, prefix) && ok && admin && prefix[5] == 6); + decode_one(&d, fail, sizeof(fail)); + CHECK(VmParseLoginResult(d.payload, d.len, &ok, &admin, prefix) && !ok && !admin && prefix[0] == 1); + + /* a signed message keeps its author's prefix (room posts) */ + decode_one(&d, kSignedMsg, sizeof(kSignedMsg)); + CHECK(VmParseMessage(d.payload, d.len, &m) && m.hasSigner && m.signer[0] == 0xa0 && m.signer[3] == 0xa3); + decode_one(&d, kContactMsg, sizeof(kContactMsg)); + CHECK(VmParseMessage(d.payload, d.len, &m) && !m.hasSigner); +} + +static void test_rx_log(void) +{ + VmRxLog rx; + /* zero-hop flood advert: snr +6.25, rssi -92 */ + static const UInt8 advert0[] = { 0x88, 25, (UInt8)-92, (VM_PAYLOAD_ADVERT << 2) | 1, 0x40, + 0x9b, 0x1e, 0x4f, 0x92, 0xf1, 0x37, 0, 0 }; + /* advert relayed by two repeaters, 2-byte hashes: aaaa then bbbb */ + static const UInt8 advert2[] = { 0x88, (UInt8)-8, (UInt8)-110, (VM_PAYLOAD_ADVERT << 2) | 1, 0x42, + 0xaa, 0xaa, 0xbb, 0xbb, 0x9b, 0x1e, 0x4f, 0x92, 0xf1, 0x37 }; + /* text message with transport codes, flood, 1 hop of 1-byte hash cc */ + static const UInt8 text1[] = { 0x88, 4, (UInt8)-80, (2 << 2) | 0, 1, 2, 3, 4, 0x01, 0xcc, 9, 9, 9 }; + /* direct route: the path is the route ahead, so no 'from' */ + static const UInt8 direct[] = { 0x88, 4, (UInt8)-80, (2 << 2) | 2, 0x01, 0xdd, 9, 9 }; + + CHECK(VmParseRxLog(advert0, sizeof(advert0), &rx) && rx.snrQ == 25 && rx.rssi == -92); + CHECK(rx.isAdvert && rx.hops == 0 && rx.fromLen == 6 && rx.from[0] == 0x9b && rx.advertKey[5] == 0x37); + CHECK(VmParseRxLog(advert2, sizeof(advert2), &rx) && rx.snrQ == -8 && rx.hops == 2); + CHECK(rx.isAdvert && rx.advertKey[0] == 0x9b && rx.fromLen == 2 && rx.from[0] == 0xbb && rx.from[1] == 0xbb); + CHECK(VmParseRxLog(text1, sizeof(text1), &rx) && !rx.isAdvert && rx.hops == 1 && rx.fromLen == 1 && rx.from[0] == 0xcc); + CHECK(VmParseRxLog(direct, sizeof(direct), &rx) && rx.fromLen == 0); + CHECK(!VmParseRxLog(advert2, 7, &rx)); /* path cut off */ +} + static void test_path_len(void) { CHECK(VM_PATH_HOPS(0x00) == 0 && VM_PATH_HASH_BYTES(0x00) == 1); @@ -436,6 +499,8 @@ int main(void) test_decimals(); test_path_len(); test_sha256_and_channels(); + test_contacts_and_rooms(); + test_rx_log(); test_messaging(); test_parse_self_info(); test_parse_contacts();