37 lines
2.3 KiB
C
37 lines
2.3 KiB
C
/* SPDX-License-Identifier: GPL-2.0-or-later */
|
|
#include "fragger.h"
|
|
#include <string.h>
|
|
static uint32_t le(const unsigned char *b){return (uint32_t)b[0]|((uint32_t)b[1]<<8)|((uint32_t)b[2]<<16)|((uint32_t)b[3]<<24);}
|
|
static void put(unsigned char *b,uint32_t v){b[0]=(unsigned char)v;b[1]=(unsigned char)(v>>8);b[2]=(unsigned char)(v>>16);b[3]=(unsigned char)(v>>24);}
|
|
void nds_frag_reset(struct nds_frag *s){if(s){volatile unsigned char *p=(volatile unsigned char*)s;for(size_t i=0;i<sizeof *s;i++)p[i]=0;}}
|
|
int nds_frag_step(struct nds_frag *s,uint32_t new_handle,const unsigned char *p,size_t n,unsigned char *out,size_t cap,size_t *used,nds_dispatch dispatch,void *ctx){
|
|
if(!used)return -1;
|
|
*used=0;
|
|
if(!s||!p||!out||!dispatch||n<5||n>NDS_LIMIT+25||cap<12||p[0]!=2)return -1;
|
|
uint32_t h=le(p+1);size_t offset=5;
|
|
if(h==NDS_END){
|
|
if(s->phase||n<25||new_handle==0||new_handle==NDS_END)return -1;
|
|
uint32_t wire=le(p+5),total=le(p+9),reserved=le(p+13),max_reply=le(p+21);
|
|
if(wire<12||wire>NDS_LIMIT||total<12||total-12>NDS_LIMIT||reserved!=0||max_reply>NDS_LIMIT)return -1;
|
|
s->handle=new_handle;s->wire_limit=wire;s->expected=total-12;s->verb=le(p+17);s->reply_limit=max_reply;s->phase=1;offset=25;
|
|
}else if(!s->phase||h!=s->handle)return -1;
|
|
if(s->phase==1){
|
|
size_t part=n-offset;
|
|
if(part>s->expected-s->received||(!part&&s->received<s->expected)){nds_frag_reset(s);return -1;}
|
|
memcpy(s->request+s->received,p+offset,part);s->received+=part;
|
|
if(s->received<s->expected){put(out,4);put(out+4,s->handle);*used=8;return 0;}
|
|
size_t written=0;s->status=dispatch(ctx,s->verb,s->request,s->received,s->reply,s->reply_limit,&written);
|
|
if(written>s->reply_limit){nds_frag_reset(s);return -1;}
|
|
s->reply_len=written;s->phase=2;
|
|
}else if(s->phase==2){if(n!=5){nds_frag_reset(s);return -1;}}
|
|
else return -1;
|
|
int first=s->sent==0;size_t hdr=first?12:8;size_t available=cap<s->wire_limit?cap:s->wire_limit;
|
|
if(available<hdr||(available==hdr&&s->reply_len>s->sent)){nds_frag_reset(s);return -1;}
|
|
size_t remaining=s->reply_len-s->sent,part=remaining<available-hdr?remaining:available-hdr;
|
|
uint32_t next=part==remaining?NDS_END:s->handle;
|
|
put(out,(uint32_t)(hdr+part-4));put(out+4,next);if(first)put(out+8,(uint32_t)s->status);
|
|
memcpy(out+hdr,s->reply+s->sent,part);s->sent+=part;*used=hdr+part;
|
|
if(next==NDS_END)nds_frag_reset(s);
|
|
return 0;
|
|
}
|