window

source of pkg::alloy::dbus::wire

1// D-Bus's wire format, little-endian: values written and read by their2// signatures, each aligned to its size from the message's start, and the3// messages around them (a header of fixed fields and a field array, then4// the body).56import std::string;7import std::vector;8import std::option;910import dbus;1112/* --- Signatures --- */1314// The type codes signatures are written in.15pub type Code = enum : u8 {16    Byte = 'y',17    Boolean = 'b',18    Int16 = 'n',19    Uint16 = 'q',20    Int32 = 'i',21    Uint32 = 'u',22    Int64 = 'x',23    Uint64 = 't',24    Double = 'd',25    Text = 's',26    ObjectPath = 'o',27    Signature = 'g',28    Descriptor = 'h', // a file descriptor's index, a Uint32 here29    Variant = 'v',30    Array = 'a',31    Struct = '(',32    StructEnd = ')',33    Entry = '{', // a dict's34    EntryEnd = '}'35};3637// The code a complete type starts with, if it is one.38fn first_code(signature: &[u8]) -> Option<Code> {39    if (signature.length() == 0) {40        return ::None;41    }42    return Code::from(signature[0]);43}4445// Where the complete type starting at `start` ends.46pub fn type_end(signature: &[u8], start: u64) -> u64 {47    if (start >= signature.length()) {48        return start;49    }50    const code = if (Code::from(signature[start]) is ::Some |c|) c else {51        return start + 1;52    };53    match (code) {54        ::Array {55            return type_end(&signature, start + 1);56        }57        ::Struct, ::Entry {58            const close = if (code == Code::Struct) Code::StructEnd else Code::EntryEnd;59            var at = start + 1;60            while (at < signature.length() && signature[at] != close to u8) {61                at = type_end(&signature, at);62            }63            return at + 1;64        }65        else {66            return start + 1;67        }68    }69}7071// The complete types of a signature, in order.72pub fn split(signature: &[u8]) -> Vector<String> {73    var out = Vector<String>::empty();74    var at: u64 = 0;75    while (at < signature.length()) {76        const end = type_end(&signature, at);77        out.push(String::from(&signature[at..end]));78        at = end;79    }80    return move out;81}8283// What a complete type's values align to, an empty one's a byte's.84fn alignment(signature: &[u8]) -> u64 {85    if (signature.length() == 0) {86        return 1;87    }88    const code = if (Code::from(signature[0]) is ::Some |c|) c else {89        return 4;90    };91    return match (code) {92        ::Byte, ::Signature, ::Variant 1;93        ::Int16, ::Uint16 2;94        ::Int64, ::Uint64, ::Double, ::Struct, ::Entry 8;95        else 4;96    };97}9899fn push_code(self out: &var String, code: Code) {100    out.push(code to u8);101}102103/* --- Writing --- */104105pub type Writer = struct {106    pub bytes: Vector<u8>,107};108109pub fn Writer::empty() -> Writer => Writer { .bytes = Vector<u8>::empty() };110111pub fn pad(self w: &var Writer, size: u64) {112    while (w.bytes.length() % size != 0) {113        w.bytes.push(0);114    }115}116117pub fn put_u8(self w: &var Writer, v: u8) {118    w.bytes.push(v);119}120121pub fn put_u16(self w: &var Writer, v: u16) {122    w.pad(2);123    w.bytes.push((v & 0xFF) to u8);124    w.bytes.push((v >> 8) to u8);125}126127pub fn put_u32(self w: &var Writer, v: u32) {128    w.pad(4);129    for ([..4 to u64]) |k| {130        w.bytes.push(((v >> (8 * k to u32)) & 0xFF) to u8);131    }132}133134pub fn put_u64(self w: &var Writer, v: u64) {135    w.pad(8);136    for ([..8 to u64]) |k| {137        w.bytes.push(((v >> (8 * k)) & 0xFF) to u8);138    }139}140141fn put_text(self w: &var Writer, text: &[u8]) {142    w.put_u32(text.length() to u32);143    w.bytes.append(&text);144    w.bytes.push(0);145}146147fn put_signature(self w: &var Writer, text: &[u8]) {148    w.bytes.push(text.length() to u8);149    w.bytes.append(&text);150    w.bytes.push(0);151}152153// Writes the value as the complete type; false when they do not match.154pub fn put(self w: &var Writer, signature: &[u8], value: &Value) -> bool {155    const code = if (first_code(&signature) is ::Some |c|) c else {156        return false;157    };158    if (!fits(&value, code)) {159        return false;160    }161    match (value) {162        ::Byte |v| {163            w.put_u8(v);164        }165        ::Boolean |v| {166            w.put_u32(if (v) 1 else 0);167        }168        ::Int16 |v| {169            w.put_u16(v as u16);170        }171        ::Uint16 |v| {172            w.put_u16(v);173        }174        ::Int32 |v| {175            w.put_u32(v as u32);176        }177        ::Uint32 |v| {178            w.put_u32(v);179        }180        ::Int64 |v| {181            w.put_u64(v as u64);182        }183        ::Uint64 |v| {184            w.put_u64(v);185        }186        ::Double |v| {187            var bits = v;188            w.put_u64(bits as u64);189        }190        ::Text, ::ObjectPath |&t| {191            w.put_text(&t.view());192        }193        ::Signature |&t| {194            w.put_signature(&t.view());195        }196        ::Array |&items| {197            const element = &signature[1..type_end(&signature, 1)];198            w.put_u32(0);199            const length_at = w.bytes.length() - 4;200            w.pad(alignment(&element));201            const start = w.bytes.length();202            for (items.view()) |&item| {203                if (!w.put(&element, &item)) {204                    return false;205                }206            }207            const length = (w.bytes.length() - start) to u32;208            for ([..4 to u64]) |k| {209                w.bytes.get_var(length_at + k) = ((length >> (8 * k to u32)) & 0xFF) to u8;210            }211        }212        ::Struct |&fields| {213            w.pad(8);214            var at: u64 = 1;215            for (fields.view()) |&field| {216                const end = type_end(&signature, at);217                if (end >= signature.length() || !w.put(&signature[at..end], &field)) {218                    return false;219                }220                at = end;221            }222            if (at != signature.length() - 1) {223                return false;224            }225        }226        ::Variant |&inner| {227            const kind = signature_of(&inner);228            w.put_signature(&kind.view());229            return w.put(&kind.view(), &inner);230        }231    }232    return true;233}234235// The code a value's type starts with.236fn code_of(value: &Value) -> Code => match (value) {237    ::Byte Code::Byte;238    ::Boolean Code::Boolean;239    ::Int16 Code::Int16;240    ::Uint16 Code::Uint16;241    ::Int32 Code::Int32;242    ::Uint32 Code::Uint32;243    ::Int64 Code::Int64;244    ::Uint64 Code::Uint64;245    ::Double Code::Double;246    ::Text Code::Text;247    ::ObjectPath Code::ObjectPath;248    ::Signature Code::Signature;249    ::Array Code::Array;250    ::Struct Code::Struct;251    ::Variant Code::Variant;252};253254// Whether a complete type starting with the code takes the value: a255// descriptor is a Uint32 and a dict's entry a struct.256fn fits(value: &Value, code: Code) -> bool {257    const own = code_of(&value);258    return own == code259        || own == Code::Uint32 && code == Code::Descriptor260        || own == Code::Struct && code == Code::Entry;261}262263// The signature a value has: an empty array's elements are strings.264pub fn signature_of(value: &Value) -> String {265    if (value is ::Array |&items|) {266        return array_signature(&items);267    }268    if (value is ::Struct |&fields|) {269        return struct_signature(&fields);270    }271    var out = String::empty();272    out.push_code(code_of(&value));273    return move out;274}275276fn array_signature(items: &Vector<Value>) -> String {277    var out = String::empty();278    out.push_code(::Array);279    if (items.length() == 0) {280        out.push_code(::Text);281        return move out;282    }283    const first = &items.get(0);284    // an array of two-field structs whose first is a basic type: a dict285    if (first is ::Struct |&pair| && pair.length() == 2 && is_basic(&pair.get(0))) {286        out.push_code(::Entry);287        out.append(&signature_of(&pair.get(0)).view());288        out.append(&signature_of(&pair.get(1)).view());289        out.push_code(::EntryEnd);290        return move out;291    }292    out.append(&signature_of(&first).view());293    return move out;294}295296fn struct_signature(fields: &Vector<Value>) -> String {297    var out = String::empty();298    out.push_code(::Struct);299    for (fields.view()) |&field| {300        out.append(&signature_of(&field).view());301    }302    out.push_code(::StructEnd);303    return move out;304}305306fn is_basic(value: &Value) -> bool {307    return !(value is ::Array || value is ::Struct || value is ::Variant);308}309310/* --- Reading --- */311312pub type Reader = struct {313    pub bytes: &[u8],314    pub at: u64,315    pub failed: bool,316};317318pub fn align(self r: &var Reader, size: u64) {319    while (r.at % size != 0) {320        r.at += 1;321    }322}323324fn need(self r: &var Reader, count: u64) -> bool {325    if (r.at + count > r.bytes.length()) {326        r.failed = true;327        r.at = r.bytes.length();328        return false;329    }330    return true;331}332333pub fn get_u8(self r: &var Reader) -> u8 {334    if (!r.need(1)) {335        return 0;336    }337    r.at += 1;338    return r.bytes[r.at - 1];339}340341pub fn get_u16(self r: &var Reader) -> u16 {342    r.align(2);343    if (!r.need(2)) {344        return 0;345    }346    const v = r.bytes[r.at] to u16 | (r.bytes[r.at + 1] to u16 << 8);347    r.at += 2;348    return v;349}350351pub fn get_u32(self r: &var Reader) -> u32 {352    r.align(4);353    if (!r.need(4)) {354        return 0;355    }356    var v: u32 = 0;357    for ([..4 to u64]) |k| {358        v |= r.bytes[r.at + k] to u32 << (8 * k to u32);359    }360    r.at += 4;361    return v;362}363364pub fn get_u64(self r: &var Reader) -> u64 {365    r.align(8);366    if (!r.need(8)) {367        return 0;368    }369    var v: u64 = 0;370    for ([..8 to u64]) |k| {371        v |= r.bytes[r.at + k] to u64 << (8 * k);372    }373    r.at += 8;374    return v;375}376377fn get_text(self r: &var Reader) -> String => r.get_ended(r.get_u32() to u64);378379fn get_signature(self r: &var Reader) -> String => r.get_ended(r.get_u8() to u64);380381// The next bytes, as many as the length says, and the NUL after them.382fn get_ended(self r: &var Reader, length: u64) -> String {383    if (!r.need(length + 1)) {384        return String::empty();385    }386    var text = String::from(&r.bytes[r.at..r.at + length]);387    r.at += length + 1;388    return move text;389}390391// Reads a value of the complete type.392pub fn get(self r: &var Reader, signature: &[u8]) -> Value {393    const code = if (first_code(&signature) is ::Some |c|) c else {394        r.failed = true;395        return Value::Byte(0);396    };397    return match (code) {398        ::Byte Value::Byte(r.get_u8());399        ::Boolean Value::Boolean(r.get_u32() != 0);400        ::Int16 Value::Int16(r.get_u16() as i16);401        ::Uint16 Value::Uint16(r.get_u16());402        ::Int32 Value::Int32(r.get_u32() as i32);403        ::Uint32, ::Descriptor Value::Uint32(r.get_u32());404        ::Int64 Value::Int64(r.get_u64() as i64);405        ::Uint64 Value::Uint64(r.get_u64());406        ::Double Value::Double(double_of(r.get_u64()));407        ::Text Value::Text(r.get_text());408        ::ObjectPath Value::ObjectPath(r.get_text());409        ::Signature Value::Signature(r.get_signature());410        ::Variant r.get_variant();411        ::Array r.get_array(&signature);412        else r.get_struct(&signature);413    };414}415416fn double_of(bits: u64) -> f64 {417    var b = bits;418    return b as f64;419}420421fn get_variant(self r: &var Reader) -> Value {422    const kind = r.get_signature();423    if (kind.length() == 0 || type_end(&kind.view(), 0) != kind.length()) {424        r.failed = true;425        return Value::Byte(0);426    }427    var inner: *var Value = new r.get(&kind.view());428    return Value::Variant(move inner);429}430431fn get_array(self r: &var Reader, signature: &[u8]) -> Value {432    const element = &signature[1..type_end(&signature, 1)];433    const length = r.get_u32() to u64;434    r.align(alignment(&element));435    const end = r.at + length;436    var items = Vector<Value>::empty();437    if (end > r.bytes.length()) {438        r.failed = true;439        return Value::Array(move items);440    }441    while (r.at < end && !r.failed) {442        items.push(r.get(&element));443    }444    return Value::Array(move items);445}446447fn get_struct(self r: &var Reader, signature: &[u8]) -> Value {448    var fields = Vector<Value>::empty();449    const code = first_code(&signature);450    if (code != ::Some(Code::Struct) && code != ::Some(Code::Entry)) {451        r.failed = true;452        return Value::Struct(move fields);453    }454    r.align(8);455    var at: u64 = 1;456    while (at < signature.length() - 1 && !r.failed) {457        const end = type_end(&signature, at);458        fields.push(r.get(&signature[at..end]));459        at = end;460    }461    return Value::Struct(move fields);462}463464/* --- Messages --- */465466// The fields a message's header may have, by their codes.467type HeaderField = enum : u8 {468    Path = 1,469    Interface = 2,470    Member = 3,471    ErrorName = 4,472    ReplySerial = 5,473    Destination = 6,474    Sender = 7,475    Signature = 8,476};477478// The message's bytes; none when its body does not match its signature.479pub fn encode(message: &Message) -> Option<Vector<u8>> {480    var body = Writer::empty();481    var at: u64 = 0;482    const signature = &message.signature.view();483    for (message.body.view()) |&value| {484        const end = type_end(&signature, at);485        if (end > signature.length() || end == at || !body.put(&signature[at..end], &value)) {486            return ::None;487        }488        at = end;489    }490    if (at != signature.length()) {491        return ::None;492    }493    var w = Writer::empty();494    w.put_u8('l');495    w.put_u8(message.kind to u8);496    w.put_u8(message.flags);497    w.put_u8(1);498    w.put_u32(body.bytes.length() to u32);499    w.put_u32(message.serial);500    var fields = Vector<Value>::empty();501    field(&var fields, ::Path, Value::ObjectPath(copy message.path));502    field(&var fields, ::Interface, Value::Text(copy message.interface_name));503    field(&var fields, ::Member, Value::Text(copy message.member));504    field(&var fields, ::ErrorName, Value::Text(copy message.error_name));505    if (message.reply_serial != 0) {506        field(&var fields, ::ReplySerial, Value::Uint32(message.reply_serial));507    }508    field(&var fields, ::Destination, Value::Text(copy message.destination));509    field(&var fields, ::Sender, Value::Text(copy message.sender));510    field(&var fields, ::Signature, Value::Signature(copy message.signature));511    w.put(&"a(yv)", &Value::Array(move fields));512    w.pad(8);513    w.bytes.append(&body.bytes.view());514    return ::Some(move w.bytes);515}516517// A header field, left out when empty.518fn field(fields: &var Vector<Value>, code: HeaderField, value: Value) {519    const empty = match (value) {520        ::Text |&t| t.length() == 0;521        ::ObjectPath |&t| t.length() == 0;522        ::Signature |&t| t.length() == 0;523        else false;524    };525    if (empty) {526        return;527    }528    fields.push(Value::entry(Value::Byte(code to u8), Value::variant(move value)));529}530531// How many bytes the message at the start of the bytes takes, once its532// fixed header is there (16 bytes).533pub fn message_length(bytes: &[u8]) -> Option<u64> {534    if (bytes.length() < 16) {535        return ::None;536    }537    var r = Reader { .bytes = &bytes, .at = 4, .failed = false };538    const body = r.get_u32() to u64;539    r.at = 12;540    const fields = r.get_u32() to u64;541    var header = 16 + fields;542    while (header % 8 != 0) {543        header += 1;544    }545    return ::Some(header + body);546}547548// The message the bytes hold, whole; none when they hold no message.549pub fn decode(bytes: &[u8]) -> Option<Message> {550    if (bytes.length() < 16 || bytes[0] != 'l' || bytes[3] != 1) {551        return ::None;552    }553    var r = Reader { .bytes = &bytes, .at = 1, .failed = false };554    var message = Message::empty();555    message.kind = if (MessageKind::from(r.get_u8()) is ::Some |kind|) kind else ::Signal;556    message.flags = r.get_u8();557    r.get_u8();558    const body_length = r.get_u32() to u64;559    message.serial = r.get_u32();560    const fields = r.get(&"a(yv)");561    if (fields is ::Array |&entries|) {562        for (entries.view()) |&entry| {563            if (entry is ::Struct |&pair| && pair.length() == 2) {564                if (565                    pair.get(0) is ::Byte |code|566                    && HeaderField::from(code) is ::Some |field|567                    && pair.get(1) is ::Variant |&inner|568                ) {569                    message.header(field, &inner);570                }571            }572        }573    }574    r.align(8);575    if (r.failed || r.at + body_length > bytes.length()) {576        return ::None;577    }578    const types = split(&message.signature.view());579    for (types.view()) |&t| {580        message.body.push(r.get(&t.view()));581    }582    if (r.failed) {583        return ::None;584    }585    return ::Some(move message);586}587588fn header(self message: &var Message, field: HeaderField, value: &Value) {589    var text = String::empty();590    match (value) {591        ::Text |&t| {592            text = copy t;593        }594        ::ObjectPath |&t| {595            text = copy t;596        }597        ::Signature |&t| {598            text = copy t;599        }600        ::Uint32 |v| {601            if (field is ::ReplySerial) {602                message.reply_serial = v;603            }604            return;605        }606        else {607            return;608        }609    }610    match (field) {611        ::Path {612            message.path = move text;613        }614        ::Interface {615            message.interface_name = move text;616        }617        ::Member {618            message.member = move text;619        }620        ::ErrorName {621            message.error_name = move text;622        }623        ::Destination {624            message.destination = move text;625        }626        ::Sender {627            message.sender = move text;628        }629        ::Signature {630            message.signature = move text;631        }632        ::ReplySerial {}633    }634}