help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Help fixing NativeMessaging host: read 32-bit message length in nati


From: guest271314
Subject: Re: Help fixing NativeMessaging host: read 32-bit message length in native byte order
Date: Sat, 1 Jul 2023 17:25:07 -0700

I noticed you posted any answer here https://stackoverflow.com/a/76549088.
It would be helpful if you included the complete code that also echoes
input from the host to the client up to 1MB.

On Sat, Jun 24, 2023 at 5:39 PM Grisha Levit <grishalevit@gmail.com> wrote:

> On Sat, Jun 24, 2023, 10:02 Greg Wooledge <greg@wooledge.org> wrote:
>
> > Reading that 4-byte binary number value is the hard part
> >
>
> I think it's doable alright if you read one byte at a time with:
> * LC_ALL=C
> * read -r -d '' -n 1
> * either set a null IFS value or using `read' without supplying an explicit
> variable name
>
> You can then convert the single character of input to a decimal value with
> printf's %d conversion specifier and an argument consisting of a quote
> character followed by the character.
>
> If a null byte is read there's no problem because:
> * read -d '' will return 0 and set an empty REPLY
> * printf %d "'" outputs 0
>
>
> LC_ALL=C
> readmsg() {
>     # return non-zero if fewer than 4 bytes of input available or if
> message
>     # is shorter than length specified by first 4 bytes of input
>     # otherwise, set $msg and return 0
>
>     local -i i n len=0
>     for ((i=0; i<4; i++)); do
>         read -r -d '' -n 1 || return
>         printf -v n %d "'$REPLY"
>         len+='n<<i*8'
>     done
>     read -r -N "$len" && ((${#REPLY}==len)) && msg=$REPLY
> }
>
> sendmsg() {
>     local x
>     printf -v x %08X "${#1}"
>     printf %b%s "\x${x:6:2}\x${x:4:2}\x${x:2:2}\x${x:0:2}" "$1"
> }
>


reply via email to

[Prev in Thread] Current Thread [Next in Thread]