From 527e2e7c5baad40b652d0b0a9ed142b8772f6b8a Mon Sep 17 00:00:00 2001 From: leitner Date: Sun, 30 Jul 2017 12:42:07 +0000 Subject: [PATCH] add unit tests and man page for scan_ldapescape --- textcode/scan_ldapescape.3 | 33 +++++++++++++++++++++++++++++++++ textcode/scan_ldapescape.c | 24 ++++++++++++++++++++---- 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 textcode/scan_ldapescape.3 diff --git a/textcode/scan_ldapescape.3 b/textcode/scan_ldapescape.3 new file mode 100644 index 0000000..3aa38d5 --- /dev/null +++ b/textcode/scan_ldapescape.3 @@ -0,0 +1,33 @@ +.TH scan_ldapescape 3 +.SH NAME +scan_ldapescape \- parse LDIF escaped string +.SH SYNTAX +.B #include + +size_t \fBscan_ldapescape\fP(const char *\fIsrc\fR,char *\fIdest\fR,size_t* \fIdestlen\fR); + +.SH DESCRIPTION +scan_ldapescape parses LDIF escaped text from src into dest. +Parsing stops at the 0 terminator or invalid input characters. + +This function will turn backslash escaped characters into their binary +equivalent, i.e. \0a to new-line and \5c to backslash. + +scan_cescape will then write the number of bytes in dest into *destlen, +and return the number of bytes decoded from src. + +dest can be NULL. destlen can be NULL. + +To make sure dest is large enough, either allocate strlen(src)+1 bytes +or call scan_ldapescape twice, the first time with dest == NULL (*destlen +will still be written). + +.SH "RETURN VALUE" +scan_ldapescape returns the number of bytes successfully parsed +from src. + +.SH EXAMPLES +scan_ldapescape("test\5C\\");",buf,&i) -> return 7, i=5, buf="test\\" (C notation). + +.SH "SEE ALSO" +fmt_ldapescape(3), scan_cescape(3), scan_ldapescape(3) diff --git a/textcode/scan_ldapescape.c b/textcode/scan_ldapescape.c index 6dacaa3..464abf7 100644 --- a/textcode/scan_ldapescape.c +++ b/textcode/scan_ldapescape.c @@ -9,16 +9,32 @@ size_t scan_ldapescape(const char *src,char *dest,size_t *destlen) { if (s[i]=='\\') { int j=scan_fromhex(s[i+1]); if (j<0) break; - dest[written]=j<<4; + if (dest) dest[written]=j<<4; j=scan_fromhex(s[i+2]); if (j<0) break; - dest[written]|=j; + if (dest) dest[written]|=j; i+=2; } else { - dest[written]=s[i]; + if (dest) dest[written]=s[i]; } ++written; } - *destlen=written; + if (destlen) *destlen=written; return i; } + +#ifdef UNITTEST +#include +#undef UNITTEST +#include + +int main() { + size_t dl; + char buf[100]; + assert(scan_ldapescape("test\\n\");",buf,&dl)==4 && dl==4 && !memcmp(buf,"test",4)); + /* check hex escaping */ + assert(scan_ldapescape("test\\0afoo",buf,&dl)==10 && dl==8 && !memcmp(buf,"test\nfoo",8)); + /* check that short sequences are rejected */ + assert(scan_ldapescape("test\\ax",buf,&dl)==4 && dl==4 && !memcmp(buf,"test",4)); +} +#endif