Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
Comment: | initial mass-change merge of main repo with my fork. |
---|---|
Downloads: | Tarball | ZIP archive |
Timelines: | family | ancestors | descendants | both | json |
Files: | files | file ages | folders |
SHA1: |
5b44a419cdf6be06632176bedacf4259 |
User & Date: | stephan 2011-09-15 12:03:20.147 |
Context
2011-09-16
| ||
11:48 | compile fix for mingw (thanks to Robert Engelhardt). ... (check-in: 58d41564 user: stephan tags: json) | |
2011-09-15
| ||
12:03 | initial mass-change merge of main repo with my fork. ... (check-in: 5b44a419 user: stephan tags: json) | |
11:55 | merged in with trunk for clean state before i pull in my fork. ... (check-in: 716bb292 user: stephan tags: json) | |
Changes
Changes to src/blob.c.
︙ | ︙ | |||
1011 1012 1013 1014 1015 1016 1017 | if( z[i]=='"' ) z[i] = '_'; } return; } } blob_append(pBlob, zIn, -1); } | > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 | if( z[i]=='"' ) z[i] = '_'; } return; } } blob_append(pBlob, zIn, -1); } /* ** A read(2)-like impl for the Blob class. Reads (copies) up to nLen ** bytes from pIn, starting at position pIn->iCursor, and copies them ** to pDest (which must be valid memory at least nLen bytes long). ** ** Returns the number of bytes read/copied, which may be less than ** nLen (if end-of-blob is encountered). ** ** Updates pIn's cursor. ** ** Returns 0 if pIn contains no data. */ unsigned int blob_read(Blob *pIn, void * pDest, unsigned int nLen ){ if( !pIn->aData || (pIn->iCursor >= pIn->nUsed) ){ return 0; } else if( (pIn->iCursor + nLen) > (unsigned int)pIn->nUsed ){ nLen = (unsigned int) (pIn->nUsed - pIn->iCursor); } assert( pIn->nUsed > pIn->iCursor ); assert( (pIn->iCursor+nLen) <= pIn->nUsed ); if( nLen ){ memcpy( pDest, pIn->aData, nLen ); pIn->iCursor += nLen; } return nLen; } |
Changes to src/captcha.c.
︙ | ︙ | |||
410 411 412 413 414 415 416 417 | sqlite3_randomness(sizeof(x), &x); x &= 0x7fffffff; return x; } /* ** Translate a captcha seed value into the captcha password string. */ | > > | | 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | sqlite3_randomness(sizeof(x), &x); x &= 0x7fffffff; return x; } /* ** Translate a captcha seed value into the captcha password string. ** The returned string is static and overwritten on each call to ** this function. */ char const *captcha_decode(unsigned int seed){ const char *zSecret; const char *z; Blob b; static char zRes[20]; zSecret = db_get("captcha-secret", 0); if( zSecret==0 ){ |
︙ | ︙ |
Changes to src/cgi.c.
︙ | ︙ | |||
700 701 702 703 704 705 706 | } z = (char*)P("REMOTE_ADDR"); if( z ) g.zIpAddr = mprintf("%s", z); len = atoi(PD("CONTENT_LENGTH", "0")); g.zContentType = zType = P("CONTENT_TYPE"); | | > > > | 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | } z = (char*)P("REMOTE_ADDR"); if( z ) g.zIpAddr = mprintf("%s", z); len = atoi(PD("CONTENT_LENGTH", "0")); g.zContentType = zType = P("CONTENT_TYPE"); if( !g.json.isJsonMode && (len>0 && zType) ){/* in JSON mode this is delegated to the cson_cgi API.*/ blob_zero(&g.cgiIn); if( fossil_strcmp(zType,"application/x-www-form-urlencoded")==0 || strncmp(zType,"multipart/form-data",19)==0 ){ z = fossil_malloc( len+1 ); len = fread(z, 1, len, g.httpIn); z[len] = 0; if( zType[0]=='a' ){ add_param_list(z, '&'); }else{ process_multipart_form_data(z, len); } }else if( fossil_strcmp(zType, "application/x-fossil")==0 ){ blob_read_from_channel(&g.cgiIn, g.httpIn, len); blob_uncompress(&g.cgiIn, &g.cgiIn); }else if( fossil_strcmp(zType, "application/x-fossil-debug")==0 ){ blob_read_from_channel(&g.cgiIn, g.httpIn, len); }else if( fossil_strcmp(zType, "application/x-fossil-uncompressed")==0 ){ blob_read_from_channel(&g.cgiIn, g.httpIn, len); } /* FIXME: treat application/json and text/plain as unencoded JSON data. */ } z = (char*)P("HTTP_COOKIE"); if( z ){ z = mprintf("%s",z); add_param_list(z, ';'); } |
︙ | ︙ |
Added src/cson_amalgamation.c.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 | /* auto-generated! Do not edit! */ #include "cson_amalgamation.h" /* begin file parser/JSON_parser.h */ /* See JSON_parser.c for copyright information and licensing. */ #ifndef JSON_PARSER_H #define JSON_PARSER_H /* JSON_parser.h */ #include <stddef.h> /* Windows DLL stuff */ #ifdef JSON_PARSER_DLL # ifdef _MSC_VER # ifdef JSON_PARSER_DLL_EXPORTS # define JSON_PARSER_DLL_API __declspec(dllexport) # else # define JSON_PARSER_DLL_API __declspec(dllimport) # endif # else # define JSON_PARSER_DLL_API # endif #else # define JSON_PARSER_DLL_API #endif /* Determine the integer type use to parse non-floating point numbers */ #if __STDC_VERSION__ >= 199901L || HAVE_LONG_LONG == 1 typedef long long JSON_int_t; #define JSON_PARSER_INTEGER_SSCANF_TOKEN "%lld" #define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%lld" #else typedef long JSON_int_t; #define JSON_PARSER_INTEGER_SSCANF_TOKEN "%ld" #define JSON_PARSER_INTEGER_SPRINTF_TOKEN "%ld" #endif #ifdef __cplusplus extern "C" { #endif typedef enum { JSON_E_NONE = 0, JSON_E_INVALID_CHAR, JSON_E_INVALID_KEYWORD, JSON_E_INVALID_ESCAPE_SEQUENCE, JSON_E_INVALID_UNICODE_SEQUENCE, JSON_E_INVALID_NUMBER, JSON_E_NESTING_DEPTH_REACHED, JSON_E_UNBALANCED_COLLECTION, JSON_E_EXPECTED_KEY, JSON_E_EXPECTED_COLON, JSON_E_OUT_OF_MEMORY } JSON_error; typedef enum { JSON_T_NONE = 0, JSON_T_ARRAY_BEGIN, JSON_T_ARRAY_END, JSON_T_OBJECT_BEGIN, JSON_T_OBJECT_END, JSON_T_INTEGER, JSON_T_FLOAT, JSON_T_NULL, JSON_T_TRUE, JSON_T_FALSE, JSON_T_STRING, JSON_T_KEY, JSON_T_MAX } JSON_type; typedef struct JSON_value_struct { union { JSON_int_t integer_value; double float_value; struct { const char* value; size_t length; } str; } vu; } JSON_value; typedef struct JSON_parser_struct* JSON_parser; /*! \brief JSON parser callback \param ctx The pointer passed to new_JSON_parser. \param type An element of JSON_type but not JSON_T_NONE. \param value A representation of the parsed value. This parameter is NULL for JSON_T_ARRAY_BEGIN, JSON_T_ARRAY_END, JSON_T_OBJECT_BEGIN, JSON_T_OBJECT_END, JSON_T_NULL, JSON_T_TRUE, and JSON_T_FALSE. String values are always returned as zero-terminated C strings. \return Non-zero if parsing should continue, else zero. */ typedef int (*JSON_parser_callback)(void* ctx, int type, const struct JSON_value_struct* value); /** A typedef for allocator functions semantically compatible with malloc(). */ typedef void* (*JSON_malloc_t)(size_t n); /** A typedef for deallocator functions semantically compatible with free(). */ typedef void (*JSON_free_t)(void* mem); /*! \brief The structure used to configure a JSON parser object */ typedef struct { /** Pointer to a callback, called when the parser has something to tell the user. This parameter may be NULL. In this case the input is merely checked for validity. */ JSON_parser_callback callback; /** Callback context - client-specified data to pass to the callback function. This parameter may be NULL. */ void* callback_ctx; /** Specifies the levels of nested JSON to allow. Negative numbers yield unlimited nesting. If negative, the parser can parse arbitrary levels of JSON, otherwise the depth is the limit. */ int depth; /** To allow C style comments in JSON, set to non-zero. */ int allow_comments; /** To decode floating point numbers manually set this parameter to non-zero. */ int handle_floats_manually; /** The memory allocation routine, which must be semantically compatible with malloc(3). If set to NULL, malloc(3) is used. If this is set to a non-NULL value then the 'free' member MUST be set to the proper deallocation counterpart for this function. Failure to do so results in undefined behaviour at deallocation time. */ JSON_malloc_t malloc; /** The memory deallocation routine, which must be semantically compatible with free(3). If set to NULL, free(3) is used. If this is set to a non-NULL value then the 'alloc' member MUST be set to the proper allocation counterpart for this function. Failure to do so results in undefined behaviour at deallocation time. */ JSON_free_t free; } JSON_config; /*! \brief Initializes the JSON parser configuration structure to default values. The default configuration is - 127 levels of nested JSON (depends on JSON_PARSER_STACK_SIZE, see json_parser.c) - no parsing, just checking for JSON syntax - no comments - Uses realloc() for memory de/allocation. \param config. Used to configure the parser. */ JSON_PARSER_DLL_API void init_JSON_config(JSON_config * config); /*! \brief Create a JSON parser object \param config. Used to configure the parser. Set to NULL to use the default configuration. See init_JSON_config. Its contents are copied by this function, so it need not outlive the returned object. \return The parser object, which is owned by the caller and must eventually be freed by calling delete_JSON_parser(). */ JSON_PARSER_DLL_API JSON_parser new_JSON_parser(JSON_config const* config); /*! \brief Destroy a previously created JSON parser object. */ JSON_PARSER_DLL_API void delete_JSON_parser(JSON_parser jc); /*! \brief Parse a character. \return Non-zero, if all characters passed to this function are part of are valid JSON. */ JSON_PARSER_DLL_API int JSON_parser_char(JSON_parser jc, int next_char); /*! \brief Finalize parsing. Call this method once after all input characters have been consumed. \return Non-zero, if all parsed characters are valid JSON, zero otherwise. */ JSON_PARSER_DLL_API int JSON_parser_done(JSON_parser jc); /*! \brief Determine if a given string is valid JSON white space \return Non-zero if the string is valid, zero otherwise. */ JSON_PARSER_DLL_API int JSON_parser_is_legal_white_space_string(const char* s); /*! \brief Gets the last error that occurred during the use of JSON_parser. \return A value from the JSON_error enum. */ JSON_PARSER_DLL_API int JSON_parser_get_last_error(JSON_parser jc); /*! \brief Re-sets the parser to prepare it for another parse run. \return True (non-zero) on success, 0 on error (e.g. !jc). */ JSON_PARSER_DLL_API int JSON_parser_reset(JSON_parser jc); #ifdef __cplusplus } #endif #endif /* JSON_PARSER_H */ /* end file parser/JSON_parser.h */ /* begin file parser/JSON_parser.c */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Callbacks, comments, Unicode handling by Jean Gressmann (jean@0x42.de), 2007-2010. Changelog: 2010-11-25 Support for custom memory allocation (sgbeal@googlemail.com). 2010-05-07 Added error handling for memory allocation failure (sgbeal@googlemail.com). Added diagnosis errors for invalid JSON. 2010-03-25 Fixed buffer overrun in grow_parse_buffer & cleaned up code. 2009-10-19 Replaced long double in JSON_value_struct with double after reports of strtold being broken on some platforms (charles@transmissionbt.com). 2009-05-17 Incorporated benrudiak@googlemail.com fix for UTF16 decoding. 2009-05-14 Fixed float parsing bug related to a locale being set that didn't use '.' as decimal point character (charles@transmissionbt.com). 2008-10-14 Renamed states.IN to states.IT to avoid name clash which IN macro defined in windef.h (alexey.pelykh@gmail.com) 2008-07-19 Removed some duplicate code & debugging variable (charles@transmissionbt.com) 2008-05-28 Made JSON_value structure ansi C compliant. This bug was report by trisk@acm.jhu.edu 2008-05-20 Fixed bug reported by charles@transmissionbt.com where the switching from static to dynamic parse buffer did not copy the static parse buffer's content. */ #include <assert.h> #include <ctype.h> #include <float.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #ifdef _MSC_VER # if _MSC_VER >= 1400 /* Visual Studio 2005 and up */ # pragma warning(disable:4996) /* unsecure sscanf */ # pragma warning(disable:4127) /* conditional expression is constant */ # endif #endif #define true 1 #define false 0 #define __ -1 /* the universal error code */ /* values chosen so that the object size is approx equal to one page (4K) */ #ifndef JSON_PARSER_STACK_SIZE # define JSON_PARSER_STACK_SIZE 128 #endif #ifndef JSON_PARSER_PARSE_BUFFER_SIZE # define JSON_PARSER_PARSE_BUFFER_SIZE 3500 #endif typedef void* (*JSON_debug_malloc_t)(size_t bytes, const char* reason); #ifdef JSON_PARSER_DEBUG_MALLOC # define JSON_parser_malloc(func, bytes, reason) ((JSON_debug_malloc_t)func)(bytes, reason) #else # define JSON_parser_malloc(func, bytes, reason) func(bytes) #endif typedef unsigned short UTF16; struct JSON_parser_struct { JSON_parser_callback callback; void* ctx; signed char state, before_comment_state, type, escaped, comment, allow_comments, handle_floats_manually, error; char decimal_point; UTF16 utf16_high_surrogate; int current_char; int depth; int top; int stack_capacity; signed char* stack; char* parse_buffer; size_t parse_buffer_capacity; size_t parse_buffer_count; signed char static_stack[JSON_PARSER_STACK_SIZE]; char static_parse_buffer[JSON_PARSER_PARSE_BUFFER_SIZE]; JSON_malloc_t malloc; JSON_free_t free; }; #define COUNTOF(x) (sizeof(x)/sizeof(x[0])) /* Characters are mapped into these character classes. This allows for a significant reduction in the size of the state transition table. */ enum classes { C_SPACE, /* space */ C_WHITE, /* other whitespace */ C_LCURB, /* { */ C_RCURB, /* } */ C_LSQRB, /* [ */ C_RSQRB, /* ] */ C_COLON, /* : */ C_COMMA, /* , */ C_QUOTE, /* " */ C_BACKS, /* \ */ C_SLASH, /* / */ C_PLUS, /* + */ C_MINUS, /* - */ C_POINT, /* . */ C_ZERO , /* 0 */ C_DIGIT, /* 123456789 */ C_LOW_A, /* a */ C_LOW_B, /* b */ C_LOW_C, /* c */ C_LOW_D, /* d */ C_LOW_E, /* e */ C_LOW_F, /* f */ C_LOW_L, /* l */ C_LOW_N, /* n */ C_LOW_R, /* r */ C_LOW_S, /* s */ C_LOW_T, /* t */ C_LOW_U, /* u */ C_ABCDF, /* ABCDF */ C_E, /* E */ C_ETC, /* everything else */ C_STAR, /* * */ NR_CLASSES }; static const signed char ascii_class[128] = { /* This array maps the 128 ASCII characters into character classes. The remaining Unicode characters should be mapped to C_ETC. Non-whitespace control characters are errors. */ __, __, __, __, __, __, __, __, __, C_WHITE, C_WHITE, __, __, C_WHITE, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH, C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC, C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC, C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC }; /* The state codes. */ enum states { GO, /* start */ OK, /* ok */ OB, /* object */ KE, /* key */ CO, /* colon */ VA, /* value */ AR, /* array */ ST, /* string */ ES, /* escape */ U1, /* u1 */ U2, /* u2 */ U3, /* u3 */ U4, /* u4 */ MI, /* minus */ ZE, /* zero */ IT, /* integer */ FR, /* fraction */ E1, /* e */ E2, /* ex */ E3, /* exp */ T1, /* tr */ T2, /* tru */ T3, /* true */ F1, /* fa */ F2, /* fal */ F3, /* fals */ F4, /* false */ N1, /* nu */ N2, /* nul */ N3, /* null */ C1, /* / */ C2, /* / * */ C3, /* * */ FX, /* *.* *eE* */ D1, /* second UTF-16 character decoding started by \ */ D2, /* second UTF-16 character proceeded by u */ NR_STATES }; enum actions { CB = -10, /* comment begin */ CE = -11, /* comment end */ FA = -12, /* false */ TR = -13, /* false */ NU = -14, /* null */ DE = -15, /* double detected by exponent e E */ DF = -16, /* double detected by fraction . */ SB = -17, /* string begin */ MX = -18, /* integer detected by minus */ ZX = -19, /* integer detected by zero */ IX = -20, /* integer detected by 1-9 */ EX = -21, /* next char is escaped */ UC = -22 /* Unicode character read */ }; static const signed char state_transition_table[NR_STATES][NR_CLASSES] = { /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the text the state is OK and if the mode is MODE_DONE. white 1-9 ABCDF etc space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E | * */ /*start GO*/ {GO,GO,-6,__,-5,__,__,__,__,__,CB,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*ok OK*/ {OK,OK,__,-8,__,-7,__,-3,__,__,CB,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*object OB*/ {OB,OB,__,-9,__,__,__,__,SB,__,CB,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,CB,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*colon CO*/ {CO,CO,__,__,__,__,-2,__,__,__,CB,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*value VA*/ {VA,VA,-6,__,-5,__,__,__,SB,__,CB,__,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__}, /*array AR*/ {AR,AR,-6,__,-5,-7,__,__,SB,__,CB,__,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__}, /*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,-4,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST}, /*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__}, /*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__}, /*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__}, /*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__}, /*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__}, /*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IT,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*zero ZE*/ {OK,OK,__,-8,__,-7,__,-3,__,__,CB,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*int IT*/ {OK,OK,__,-8,__,-7,__,-3,__,__,CB,__,__,DF,IT,IT,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__}, /*frac FR*/ {OK,OK,__,-8,__,-7,__,-3,__,__,CB,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__}, /*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*exp E3*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__}, /*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__}, /*true T3*/ {__,__,__,__,__,__,__,__,__,__,CB,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__}, /*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__}, /*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__}, /*false F4*/ {__,__,__,__,__,__,__,__,__,__,CB,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__}, /*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__}, /*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__}, /*null N3*/ {__,__,__,__,__,__,__,__,__,__,CB,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__}, /*/ C1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,C2}, /*/* C2*/ {C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C3}, /** C3*/ {C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,CE,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C2,C3}, /*_. FX*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__}, /*\ D1*/ {__,__,__,__,__,__,__,__,__,D2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*\ D2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,U1,__,__,__,__}, }; /* These modes can be pushed on the stack. */ enum modes { MODE_ARRAY = 1, MODE_DONE = 2, MODE_KEY = 3, MODE_OBJECT = 4 }; static void set_error(JSON_parser jc) { switch (jc->state) { case GO: switch (jc->current_char) { case '{': case '}': case '[': case ']': jc->error = JSON_E_UNBALANCED_COLLECTION; break; default: jc->error = JSON_E_INVALID_CHAR; break; } break; case OB: jc->error = JSON_E_EXPECTED_KEY; break; case AR: jc->error = JSON_E_UNBALANCED_COLLECTION; break; case CO: jc->error = JSON_E_EXPECTED_COLON; break; case KE: jc->error = JSON_E_EXPECTED_KEY; break; /* \uXXXX\uYYYY */ case U1: case U2: case U3: case U4: case D1: case D2: jc->error = JSON_E_INVALID_UNICODE_SEQUENCE; break; /* true, false, null */ case T1: case T2: case T3: case F1: case F2: case F3: case F4: case N1: case N2: case N3: jc->error = JSON_E_INVALID_KEYWORD; break; /* minus, integer, fraction, exponent */ case MI: case ZE: case IT: case FR: case E1: case E2: case E3: jc->error = JSON_E_INVALID_NUMBER; break; default: jc->error = JSON_E_INVALID_CHAR; break; } } static int push(JSON_parser jc, int mode) { /* Push a mode onto the stack. Return false if there is overflow. */ assert(jc->top <= jc->stack_capacity); if (jc->depth < 0) { if (jc->top == jc->stack_capacity) { const size_t bytes_to_copy = jc->stack_capacity * sizeof(jc->stack[0]); const size_t new_capacity = jc->stack_capacity * 2; const size_t bytes_to_allocate = new_capacity * sizeof(jc->stack[0]); void* mem = JSON_parser_malloc(jc->malloc, bytes_to_allocate, "stack"); if (!mem) { jc->error = JSON_E_OUT_OF_MEMORY; return false; } jc->stack_capacity = (int)new_capacity; memcpy(mem, jc->stack, bytes_to_copy); if (jc->stack != &jc->static_stack[0]) { jc->free(jc->stack); } jc->stack = (signed char*)mem; } } else { if (jc->top == jc->depth) { jc->error = JSON_E_NESTING_DEPTH_REACHED; return false; } } jc->stack[++jc->top] = (signed char)mode; return true; } static int pop(JSON_parser jc, int mode) { /* Pop the stack, assuring that the current mode matches the expectation. Return false if there is underflow or if the modes mismatch. */ if (jc->top < 0 || jc->stack[jc->top] != mode) { return false; } jc->top -= 1; return true; } #define parse_buffer_clear(jc) \ do {\ jc->parse_buffer_count = 0;\ jc->parse_buffer[0] = 0;\ } while (0) #define parse_buffer_pop_back_char(jc)\ do {\ assert(jc->parse_buffer_count >= 1);\ --jc->parse_buffer_count;\ jc->parse_buffer[jc->parse_buffer_count] = 0;\ } while (0) void delete_JSON_parser(JSON_parser jc) { if (jc) { if (jc->stack != &jc->static_stack[0]) { jc->free((void*)jc->stack); } if (jc->parse_buffer != &jc->static_parse_buffer[0]) { jc->free((void*)jc->parse_buffer); } jc->free((void*)jc); } } int JSON_parser_reset(JSON_parser jc) { if (NULL == jc) { return false; } jc->state = GO; jc->top = -1; /* parser has been used previously? */ if (NULL == jc->parse_buffer) { /* Do we want non-bound stack? */ if (jc->depth > 0) { jc->stack_capacity = jc->depth; if (jc->depth <= (int)COUNTOF(jc->static_stack)) { jc->stack = &jc->static_stack[0]; } else { const size_t bytes_to_alloc = jc->stack_capacity * sizeof(jc->stack[0]); jc->stack = (signed char*)JSON_parser_malloc(jc->malloc, bytes_to_alloc, "stack"); if (jc->stack == NULL) { return false; } } } else { jc->stack_capacity = (int)COUNTOF(jc->static_stack); jc->depth = -1; jc->stack = &jc->static_stack[0]; } /* set up the parse buffer */ jc->parse_buffer = &jc->static_parse_buffer[0]; jc->parse_buffer_capacity = COUNTOF(jc->static_parse_buffer); } /* set parser to start */ push(jc, MODE_DONE); parse_buffer_clear(jc); return true; } JSON_parser new_JSON_parser(JSON_config const * config) { /* new_JSON_parser starts the checking process by constructing a JSON_parser object. It takes a depth parameter that restricts the level of maximum nesting. To continue the process, call JSON_parser_char for each character in the JSON text, and then call JSON_parser_done to obtain the final result. These functions are fully reentrant. */ int use_std_malloc = false; JSON_config default_config; JSON_parser jc; JSON_malloc_t alloc; /* set to default configuration if none was provided */ if (NULL == config) { /* initialize configuration */ init_JSON_config(&default_config); config = &default_config; } /* use std malloc if either the allocator or deallocator function isn't set */ use_std_malloc = NULL == config->malloc || NULL == config->free; alloc = use_std_malloc ? malloc : config->malloc; jc = JSON_parser_malloc(alloc, sizeof(*jc), "parser"); if (NULL == jc) { return NULL; } /* configure the parser */ memset(jc, 0, sizeof(*jc)); jc->malloc = alloc; jc->free = use_std_malloc ? free : config->free; jc->callback = config->callback; jc->ctx = config->callback_ctx; jc->allow_comments = (signed char)(config->allow_comments != 0); jc->handle_floats_manually = (signed char)(config->handle_floats_manually != 0); jc->decimal_point = *localeconv()->decimal_point; /* We need to be able to push at least one object */ jc->depth = config->depth == 0 ? 1 : config->depth; /* reset the parser */ if (!JSON_parser_reset(jc)) { jc->free(jc); return NULL; } return jc; } static int parse_buffer_grow(JSON_parser jc) { const size_t bytes_to_copy = jc->parse_buffer_count * sizeof(jc->parse_buffer[0]); const size_t new_capacity = jc->parse_buffer_capacity * 2; const size_t bytes_to_allocate = new_capacity * sizeof(jc->parse_buffer[0]); void* mem = JSON_parser_malloc(jc->malloc, bytes_to_allocate, "parse buffer"); if (mem == NULL) { jc->error = JSON_E_OUT_OF_MEMORY; return false; } assert(new_capacity > 0); memcpy(mem, jc->parse_buffer, bytes_to_copy); if (jc->parse_buffer != &jc->static_parse_buffer[0]) { jc->free(jc->parse_buffer); } jc->parse_buffer = (char*)mem; jc->parse_buffer_capacity = new_capacity; return true; } static int parse_buffer_reserve_for(JSON_parser jc, unsigned chars) { while (jc->parse_buffer_count + chars + 1 > jc->parse_buffer_capacity) { if (!parse_buffer_grow(jc)) { assert(jc->error == JSON_E_OUT_OF_MEMORY); return false; } } return true; } #define parse_buffer_has_space_for(jc, count) \ (jc->parse_buffer_count + (count) + 1 <= jc->parse_buffer_capacity) #define parse_buffer_push_back_char(jc, c)\ do {\ assert(parse_buffer_has_space_for(jc, 1)); \ jc->parse_buffer[jc->parse_buffer_count++] = c;\ jc->parse_buffer[jc->parse_buffer_count] = 0;\ } while (0) #define assert_is_non_container_type(jc) \ assert( \ jc->type == JSON_T_NULL || \ jc->type == JSON_T_FALSE || \ jc->type == JSON_T_TRUE || \ jc->type == JSON_T_FLOAT || \ jc->type == JSON_T_INTEGER || \ jc->type == JSON_T_STRING) static int parse_parse_buffer(JSON_parser jc) { if (jc->callback) { JSON_value value, *arg = NULL; if (jc->type != JSON_T_NONE) { assert_is_non_container_type(jc); switch(jc->type) { case JSON_T_FLOAT: arg = &value; if (jc->handle_floats_manually) { value.vu.str.value = jc->parse_buffer; value.vu.str.length = jc->parse_buffer_count; } else { /* not checking with end pointer b/c there may be trailing ws */ value.vu.float_value = strtod(jc->parse_buffer, NULL); } break; case JSON_T_INTEGER: arg = &value; sscanf(jc->parse_buffer, JSON_PARSER_INTEGER_SSCANF_TOKEN, &value.vu.integer_value); break; case JSON_T_STRING: arg = &value; value.vu.str.value = jc->parse_buffer; value.vu.str.length = jc->parse_buffer_count; break; } if (!(*jc->callback)(jc->ctx, jc->type, arg)) { return false; } } } parse_buffer_clear(jc); return true; } #define IS_HIGH_SURROGATE(uc) (((uc) & 0xFC00) == 0xD800) #define IS_LOW_SURROGATE(uc) (((uc) & 0xFC00) == 0xDC00) #define DECODE_SURROGATE_PAIR(hi,lo) ((((hi) & 0x3FF) << 10) + ((lo) & 0x3FF) + 0x10000) static const unsigned char utf8_lead_bits[4] = { 0x00, 0xC0, 0xE0, 0xF0 }; static int decode_unicode_char(JSON_parser jc) { int i; unsigned uc = 0; char* p; int trail_bytes; assert(jc->parse_buffer_count >= 6); p = &jc->parse_buffer[jc->parse_buffer_count - 4]; for (i = 12; i >= 0; i -= 4, ++p) { unsigned x = *p; if (x >= 'a') { x -= ('a' - 10); } else if (x >= 'A') { x -= ('A' - 10); } else { x &= ~0x30u; } assert(x < 16); uc |= x << i; } /* clear UTF-16 char from buffer */ jc->parse_buffer_count -= 6; jc->parse_buffer[jc->parse_buffer_count] = 0; /* attempt decoding ... */ if (jc->utf16_high_surrogate) { if (IS_LOW_SURROGATE(uc)) { uc = DECODE_SURROGATE_PAIR(jc->utf16_high_surrogate, uc); trail_bytes = 3; jc->utf16_high_surrogate = 0; } else { /* high surrogate without a following low surrogate */ return false; } } else { if (uc < 0x80) { trail_bytes = 0; } else if (uc < 0x800) { trail_bytes = 1; } else if (IS_HIGH_SURROGATE(uc)) { /* save the high surrogate and wait for the low surrogate */ jc->utf16_high_surrogate = (UTF16)uc; return true; } else if (IS_LOW_SURROGATE(uc)) { /* low surrogate without a preceding high surrogate */ return false; } else { trail_bytes = 2; } } jc->parse_buffer[jc->parse_buffer_count++] = (char) ((uc >> (trail_bytes * 6)) | utf8_lead_bits[trail_bytes]); for (i = trail_bytes * 6 - 6; i >= 0; i -= 6) { jc->parse_buffer[jc->parse_buffer_count++] = (char) (((uc >> i) & 0x3F) | 0x80); } jc->parse_buffer[jc->parse_buffer_count] = 0; return true; } static int add_escaped_char_to_parse_buffer(JSON_parser jc, int next_char) { assert(parse_buffer_has_space_for(jc, 1)); jc->escaped = 0; /* remove the backslash */ parse_buffer_pop_back_char(jc); switch(next_char) { case 'b': parse_buffer_push_back_char(jc, '\b'); break; case 'f': parse_buffer_push_back_char(jc, '\f'); break; case 'n': parse_buffer_push_back_char(jc, '\n'); break; case 'r': parse_buffer_push_back_char(jc, '\r'); break; case 't': parse_buffer_push_back_char(jc, '\t'); break; case '"': parse_buffer_push_back_char(jc, '"'); break; case '\\': parse_buffer_push_back_char(jc, '\\'); break; case '/': parse_buffer_push_back_char(jc, '/'); break; case 'u': parse_buffer_push_back_char(jc, '\\'); parse_buffer_push_back_char(jc, 'u'); break; default: return false; } return true; } static int add_char_to_parse_buffer(JSON_parser jc, int next_char, int next_class) { if (!parse_buffer_reserve_for(jc, 1)) { assert(JSON_E_OUT_OF_MEMORY == jc->error); return false; } if (jc->escaped) { if (!add_escaped_char_to_parse_buffer(jc, next_char)) { jc->error = JSON_E_INVALID_ESCAPE_SEQUENCE; return false; } } else if (!jc->comment) { if ((jc->type != JSON_T_NONE) | !((next_class == C_SPACE) | (next_class == C_WHITE)) /* non-white-space */) { parse_buffer_push_back_char(jc, (char)next_char); } } return true; } #define assert_type_isnt_string_null_or_bool(jc) \ assert(jc->type != JSON_T_FALSE); \ assert(jc->type != JSON_T_TRUE); \ assert(jc->type != JSON_T_NULL); \ assert(jc->type != JSON_T_STRING) int JSON_parser_char(JSON_parser jc, int next_char) { /* After calling new_JSON_parser, call this function for each character (or partial character) in your JSON text. It can accept UTF-8, UTF-16, or UTF-32. It returns true if things are looking ok so far. If it rejects the text, it returns false. */ int next_class, next_state; /* Store the current char for error handling */ jc->current_char = next_char; /* Determine the character's class. */ if (next_char < 0) { jc->error = JSON_E_INVALID_CHAR; return false; } if (next_char >= 128) { next_class = C_ETC; } else { next_class = ascii_class[next_char]; if (next_class <= __) { set_error(jc); return false; } } if (!add_char_to_parse_buffer(jc, next_char, next_class)) { return false; } /* Get the next state from the state transition table. */ next_state = state_transition_table[jc->state][next_class]; if (next_state >= 0) { /* Change the state. */ jc->state = (signed char)next_state; } else { /* Or perform one of the actions. */ switch (next_state) { /* Unicode character */ case UC: if(!decode_unicode_char(jc)) { jc->error = JSON_E_INVALID_UNICODE_SEQUENCE; return false; } /* check if we need to read a second UTF-16 char */ if (jc->utf16_high_surrogate) { jc->state = D1; } else { jc->state = ST; } break; /* escaped char */ case EX: jc->escaped = 1; jc->state = ES; break; /* integer detected by minus */ case MX: jc->type = JSON_T_INTEGER; jc->state = MI; break; /* integer detected by zero */ case ZX: jc->type = JSON_T_INTEGER; jc->state = ZE; break; /* integer detected by 1-9 */ case IX: jc->type = JSON_T_INTEGER; jc->state = IT; break; /* floating point number detected by exponent*/ case DE: assert_type_isnt_string_null_or_bool(jc); jc->type = JSON_T_FLOAT; jc->state = E1; break; /* floating point number detected by fraction */ case DF: assert_type_isnt_string_null_or_bool(jc); if (!jc->handle_floats_manually) { /* Some versions of strtod (which underlies sscanf) don't support converting C-locale formated floating point values. */ assert(jc->parse_buffer[jc->parse_buffer_count-1] == '.'); jc->parse_buffer[jc->parse_buffer_count-1] = jc->decimal_point; } jc->type = JSON_T_FLOAT; jc->state = FX; break; /* string begin " */ case SB: parse_buffer_clear(jc); assert(jc->type == JSON_T_NONE); jc->type = JSON_T_STRING; jc->state = ST; break; /* n */ case NU: assert(jc->type == JSON_T_NONE); jc->type = JSON_T_NULL; jc->state = N1; break; /* f */ case FA: assert(jc->type == JSON_T_NONE); jc->type = JSON_T_FALSE; jc->state = F1; break; /* t */ case TR: assert(jc->type == JSON_T_NONE); jc->type = JSON_T_TRUE; jc->state = T1; break; /* closing comment */ case CE: jc->comment = 0; assert(jc->parse_buffer_count == 0); assert(jc->type == JSON_T_NONE); jc->state = jc->before_comment_state; break; /* opening comment */ case CB: if (!jc->allow_comments) { return false; } parse_buffer_pop_back_char(jc); if (!parse_parse_buffer(jc)) { return false; } assert(jc->parse_buffer_count == 0); assert(jc->type != JSON_T_STRING); switch (jc->stack[jc->top]) { case MODE_ARRAY: case MODE_OBJECT: switch(jc->state) { case VA: case AR: jc->before_comment_state = jc->state; break; default: jc->before_comment_state = OK; break; } break; default: jc->before_comment_state = jc->state; break; } jc->type = JSON_T_NONE; jc->state = C1; jc->comment = 1; break; /* empty } */ case -9: parse_buffer_clear(jc); if (jc->callback && !(*jc->callback)(jc->ctx, JSON_T_OBJECT_END, NULL)) { return false; } if (!pop(jc, MODE_KEY)) { return false; } jc->state = OK; break; /* } */ case -8: parse_buffer_pop_back_char(jc); if (!parse_parse_buffer(jc)) { return false; } if (jc->callback && !(*jc->callback)(jc->ctx, JSON_T_OBJECT_END, NULL)) { return false; } if (!pop(jc, MODE_OBJECT)) { jc->error = JSON_E_UNBALANCED_COLLECTION; return false; } jc->type = JSON_T_NONE; jc->state = OK; break; /* ] */ case -7: parse_buffer_pop_back_char(jc); if (!parse_parse_buffer(jc)) { return false; } if (jc->callback && !(*jc->callback)(jc->ctx, JSON_T_ARRAY_END, NULL)) { return false; } if (!pop(jc, MODE_ARRAY)) { jc->error = JSON_E_UNBALANCED_COLLECTION; return false; } jc->type = JSON_T_NONE; jc->state = OK; break; /* { */ case -6: parse_buffer_pop_back_char(jc); if (jc->callback && !(*jc->callback)(jc->ctx, JSON_T_OBJECT_BEGIN, NULL)) { return false; } if (!push(jc, MODE_KEY)) { return false; } assert(jc->type == JSON_T_NONE); jc->state = OB; break; /* [ */ case -5: parse_buffer_pop_back_char(jc); if (jc->callback && !(*jc->callback)(jc->ctx, JSON_T_ARRAY_BEGIN, NULL)) { return false; } if (!push(jc, MODE_ARRAY)) { return false; } assert(jc->type == JSON_T_NONE); jc->state = AR; break; /* string end " */ case -4: parse_buffer_pop_back_char(jc); switch (jc->stack[jc->top]) { case MODE_KEY: assert(jc->type == JSON_T_STRING); jc->type = JSON_T_NONE; jc->state = CO; if (jc->callback) { JSON_value value; value.vu.str.value = jc->parse_buffer; value.vu.str.length = jc->parse_buffer_count; if (!(*jc->callback)(jc->ctx, JSON_T_KEY, &value)) { return false; } } parse_buffer_clear(jc); break; case MODE_ARRAY: case MODE_OBJECT: assert(jc->type == JSON_T_STRING); if (!parse_parse_buffer(jc)) { return false; } jc->type = JSON_T_NONE; jc->state = OK; break; default: return false; } break; /* , */ case -3: parse_buffer_pop_back_char(jc); if (!parse_parse_buffer(jc)) { return false; } switch (jc->stack[jc->top]) { case MODE_OBJECT: /* A comma causes a flip from object mode to key mode. */ if (!pop(jc, MODE_OBJECT) || !push(jc, MODE_KEY)) { return false; } assert(jc->type != JSON_T_STRING); jc->type = JSON_T_NONE; jc->state = KE; break; case MODE_ARRAY: assert(jc->type != JSON_T_STRING); jc->type = JSON_T_NONE; jc->state = VA; break; default: return false; } break; /* : */ case -2: /* A colon causes a flip from key mode to object mode. */ parse_buffer_pop_back_char(jc); if (!pop(jc, MODE_KEY) || !push(jc, MODE_OBJECT)) { return false; } assert(jc->type == JSON_T_NONE); jc->state = VA; break; /* Bad action. */ default: set_error(jc); return false; } } return true; } int JSON_parser_done(JSON_parser jc) { if ((jc->state == OK || jc->state == GO) && pop(jc, MODE_DONE)) { return true; } jc->error = JSON_E_UNBALANCED_COLLECTION; return false; } int JSON_parser_is_legal_white_space_string(const char* s) { int c, char_class; if (s == NULL) { return false; } for (; *s; ++s) { c = *s; if (c < 0 || c >= 128) { return false; } char_class = ascii_class[c]; if (char_class != C_SPACE && char_class != C_WHITE) { return false; } } return true; } int JSON_parser_get_last_error(JSON_parser jc) { return jc->error; } void init_JSON_config(JSON_config* config) { if (config) { memset(config, 0, sizeof(*config)); config->depth = JSON_PARSER_STACK_SIZE - 1; config->malloc = malloc; config->free = free; } } /* end file parser/JSON_parser.c */ /* begin file ./cson.c */ #include <assert.h> #include <stdlib.h> /* malloc()/free() */ #include <string.h> #ifdef _MSC_VER # if _MSC_VER >= 1400 /* Visual Studio 2005 and up */ # pragma warning( push ) # pragma warning(disable:4996) /* unsecure sscanf (but snscanf() isn't in c89) */ # pragma warning(disable:4244) /* complaining about data loss due to integer precision in the sqlite3 utf decoding routines */ # endif #endif #if 1 #include <stdio.h> #define MARKER if(1) printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); if(1) printf #else static void noop_printf(char const * fmt, ...) {} #define MARKER if(0) printf #endif #if defined(__cplusplus) extern "C" { #endif /** Type IDs corresponding to JavaScript/JSON types. */ enum cson_type_id { /** The special "null" value constant. Its value must be 0 for internal reasons. */ CSON_TYPE_UNDEF = 0, /** The special "null" value constant. */ CSON_TYPE_NULL = 1, /** The bool value type. */ CSON_TYPE_BOOL = 2, /** The integer value type, represented in this library by cson_int_t. */ CSON_TYPE_INTEGER = 3, /** The double value type, represented in this library by cson_double_t. */ CSON_TYPE_DOUBLE = 4, /** The immutable string type. This library stores strings as immutable UTF8. */ CSON_TYPE_STRING = 5, /** The "Array" type. */ CSON_TYPE_ARRAY = 6, /** The "Object" type. */ CSON_TYPE_OBJECT = 7 }; typedef enum cson_type_id cson_type_id; /** This type holds the "vtbl" for type-specific operations when working with cson_value objects. All cson_values of a given logical type share a pointer to a single library-internal instance of this class. */ struct cson_value_api { /** The logical JavaScript/JSON type associated with this object. */ const cson_type_id typeID; /** Must free any memory associated with self, but not free self. If self is NULL then this function must do nothing. */ void (*cleanup)( cson_value * self ); /** POSSIBLE TODOs: // Deep copy. int (*clone)( cson_value const * self, cson_value ** tgt ); // Using JS semantics for true/value char (*bool_value)( cson_value const * self ); // memcmp() return value semantics int (*compare)( cson_value const * self, cson_value const * other ); */ }; typedef struct cson_value_api cson_value_api; /** Empty-initialized cson_value_api object. */ #define cson_value_api_empty_m { \ CSON_TYPE_UNDEF/*typeID*/, \ NULL/*cleanup*/\ } /** Empty-initialized cson_value_api object. */ static const cson_value_api cson_value_api_empty = cson_value_api_empty_m; typedef unsigned int cson_counter_t; struct cson_value { /** The "vtbl" of type-specific operations. All instances of a given logical value type share a single api instance. Results are undefined if this value is NULL. */ cson_value_api const * api; /** The raw value. Its interpretation depends on the value of the api member. Some value types require dynamically-allocated memory, so one must always call cson_value_free() to destroy a value when it is no longer needed. For stack-allocated values (which client could SHOULD NOT USE unless they are intimately familiar with the memory management rules and don't mind an occasional leak or crash), use cson_value_clean() instead of cson_value_free(). */ void * value; /** We use this to allow us to store cson_value instances in multiple containers or multiple times within a single container (provided no cycles are introduced). Notes about the rc implementation: - The refcount is for the cson_value instance itself, not its value pointer. - Instances start out with a refcount of 0 (not 1). Adding them to a container will increase the refcount. Cleaning up the container will decrement the count. - cson_value_free() decrements the refcount (if it is not already 0) and cleans/frees the value only when the refcount is 0. - Some places in the internals add an "extra" reference to objects to avoid a premature deletion. Don't try this at home. */ cson_counter_t refcount; }; /** Empty-initialized cson_value object. */ #define cson_value_empty_m { &cson_value_api_empty/*api*/, NULL/*value*/, 0/*refcount*/ } /** Empty-initialized cson_value object. */ extern const cson_value cson_value_empty; const cson_value cson_value_empty = cson_value_empty_m; const cson_parse_opt cson_parse_opt_empty = cson_parse_opt_empty_m; const cson_output_opt cson_output_opt_empty = cson_output_opt_empty_m; const cson_object_iterator cson_object_iterator_empty = cson_object_iterator_empty_m; const cson_buffer cson_buffer_empty = cson_buffer_empty_m; const cson_parse_info cson_parse_info_empty = cson_parse_info_empty_m; static void cson_value_destroy_zero_it( cson_value * self ); static void cson_value_destroy_free( cson_value * self ); static void cson_value_destroy_object( cson_value * self ); static void cson_value_destroy_integer( cson_value * self ); /** If self is-a array then this function destroys its contents, else this function does nothing. */ static void cson_value_destroy_array( cson_value * self ); /** If self is-a string then this function destroys its contents, else this function does nothing. */ static void cson_value_destroy_string( cson_value * self ); static const cson_value_api cson_value_api_null = { CSON_TYPE_NULL, cson_value_destroy_zero_it }; static const cson_value_api cson_value_api_undef = { CSON_TYPE_UNDEF, cson_value_destroy_zero_it }; static const cson_value_api cson_value_api_bool = { CSON_TYPE_BOOL, cson_value_destroy_zero_it }; static const cson_value_api cson_value_api_integer = { CSON_TYPE_INTEGER, cson_value_destroy_integer }; static const cson_value_api cson_value_api_double = { CSON_TYPE_DOUBLE, cson_value_destroy_free }; static const cson_value_api cson_value_api_string = { CSON_TYPE_STRING, cson_value_destroy_string }; static const cson_value_api cson_value_api_array = { CSON_TYPE_ARRAY, cson_value_destroy_array }; static const cson_value_api cson_value_api_object = { CSON_TYPE_OBJECT, cson_value_destroy_object }; static const cson_value cson_value_undef = { &cson_value_api_undef, NULL, 0 }; static const cson_value cson_value_bool_empty = { &cson_value_api_bool, NULL, 0 }; static const cson_value cson_value_integer_empty = { &cson_value_api_integer, NULL, 0 }; static const cson_value cson_value_double_empty = { &cson_value_api_double, NULL, 0 }; static const cson_value cson_value_string_empty = { &cson_value_api_string, NULL, 0 }; static const cson_value cson_value_array_empty = { &cson_value_api_array, NULL, 0 }; static const cson_value cson_value_object_empty = { &cson_value_api_object, NULL, 0 }; struct cson_string { unsigned int length; }; #define cson_string_empty_m {0/*length*/} /** Holds special shared "constant" (though they are non-const) values. */ static struct CSON_EMPTY_HOLDER_ { char trueValue; cson_string stringValue; } CSON_EMPTY_HOLDER = { 1/*trueValue*/, cson_string_empty_m }; /** Indexes into the CSON_SPECIAL_VALUES array. If this enum changes in any way, makes damned sure that CSON_SPECIAL_VALUES is updated to match!!! */ enum CSON_INTERNAL_VALUES { CSON_VAL_UNDEF = 0, CSON_VAL_NULL = 1, CSON_VAL_TRUE = 2, CSON_VAL_FALSE = 3, CSON_VAL_INT_0 = 4, CSON_VAL_DBL_0 = 5, CSON_VAL_STR_EMPTY = 6, CSON_INTERNAL_VALUES_LENGTH }; /** Some "special" shared cson_value instances. These values MUST be initialized in the order specified by the CSON_INTERNAL_VALUES enum. Note that they are not const because they are used as shared-allocation objects in non-const contexts. However, the public API provides no way to modifying them, and clients who modify values directly are subject to The Wrath of Undefined Behaviour. */ static cson_value CSON_SPECIAL_VALUES[] = { { &cson_value_api_undef, NULL, 0 }, /* UNDEF */ { &cson_value_api_null, NULL, 0 }, /* NULL */ { &cson_value_api_bool, &CSON_EMPTY_HOLDER.trueValue, 0 }, /* TRUE */ { &cson_value_api_bool, NULL, 0 }, /* FALSE */ { &cson_value_api_integer, NULL, 0 }, /* INT_0 */ { &cson_value_api_double, NULL, 0 }, /* DBL_0 */ { &cson_value_api_string, &CSON_EMPTY_HOLDER.stringValue, 0 }, /* STR_EMPTY */ { 0, NULL, 0 } }; /** Returns non-0 (true) if m is one of our special "built-in" values, e.g. from CSON_SPECIAL_VALUES and some "empty" values. If this returns true, m MUST NOT be free()d! */ static char cson_value_is_builtin( void const * m ) { if((m >= (void const *)&CSON_EMPTY_HOLDER) && ( m < (void const *)(&CSON_EMPTY_HOLDER+1))) return 1; else return ((m > (void const *)&CSON_SPECIAL_VALUES[0]) && ( m < (void const *)&CSON_SPECIAL_VALUES[CSON_INTERNAL_VALUES_LENGTH]) ) ? 1 : 0; } char const * cson_rc_string(int rc) { if(0 == rc) return "OK"; #define CHECK(N) else if(cson_rc.N == rc ) return #N CHECK(OK); CHECK(ArgError); CHECK(RangeError); CHECK(TypeError); CHECK(IOError); CHECK(AllocError); CHECK(NYIError); CHECK(InternalError); CHECK(UnsupportedError); CHECK(NotFoundError); CHECK(UnknownError); CHECK(Parse_INVALID_CHAR); CHECK(Parse_INVALID_KEYWORD); CHECK(Parse_INVALID_ESCAPE_SEQUENCE); CHECK(Parse_INVALID_UNICODE_SEQUENCE); CHECK(Parse_INVALID_NUMBER); CHECK(Parse_NESTING_DEPTH_REACHED); CHECK(Parse_UNBALANCED_COLLECTION); CHECK(Parse_EXPECTED_KEY); CHECK(Parse_EXPECTED_COLON); else return "UnknownError"; #undef CHECK } /** If CSON_LOG_ALLOC is true then the cson_malloc/realloc/free() routines will log a message to stderr. */ #define CSON_LOG_ALLOC 0 /** A test/debug macro for simulating an OOM after the given number of bytes have been allocated. */ #define CSON_SIMULATE_OOM 0 #if CSON_SIMULATE_OOM static unsigned int cson_totalAlloced = 0; #endif /** Simple proxy for malloc(). descr is a description of the allocation. */ static void * cson_malloc( size_t n, char const * descr ) { #if CSON_LOG_ALLOC fprintf(stderr, "Allocating %u bytes [%s].\n", (unsigned int)n, descr); #endif #if CSON_SIMULATE_OOM cson_totalAlloced += n; if( cson_totalAlloced > CSON_SIMULATE_OOM ) { return NULL; } #endif return malloc(n); } /** Simple proxy for free(). descr is a description of the memory being freed. */ static void cson_free( void * p, char const * descr ) { #if CSON_LOG_ALLOC fprintf(stderr, "Freeing @%p [%s].\n", p, descr); #endif if( !cson_value_is_builtin(p) ) { free( p ); } } /** Simple proxy for realloc(). descr is a description of the (re)allocation. */ static void * cson_realloc( void * hint, size_t n, char const * descr ) { #if CSON_LOG_ALLOC fprintf(stderr, "%sllocating %u bytes [%s].\n", hint ? "Rea" : "A", (unsigned int)n, descr); #endif #if CSON_SIMULATE_OOM cson_totalAlloced += n; if( cson_totalAlloced > CSON_SIMULATE_OOM ) { return NULL; } #endif if( 0==n ) { cson_free(hint, descr); return NULL; } else { return realloc( hint, n ); } } #undef CSON_LOG_ALLOC #undef CSON_SIMULATE_OOM /** CLIENTS CODE SHOULD NEVER USE THIS because it opens up doors to memory leaks if it is not used in very controlled circumstances. Users must be very aware of how the underlying memory management works. Frees any resources owned by val, but does not free val itself (which may be stack-allocated). If !val or val->api or val->api->cleanup are NULL then this is a no-op. If v is a container type (object or array) its children are also cleaned up (BUT NOT FREED), recursively. After calling this, val will have the special "undefined" type. */ static void cson_value_clean( cson_value * val ); /** Increments cv's reference count by 1. As a special case, values for which cson_value_is_builtin() returns true are not modified. assert()s if (NULL==cv). */ static void cson_refcount_incr( cson_value * cv ) { assert( NULL != cv ); if( cson_value_is_builtin( cv ) ) { /* do nothing: we do not want to modify the shared instances. */ return; } else { ++cv->refcount; } } #if 0 int cson_value_refcount_set( cson_value * cv, unsigned short rc ) { if( NULL == cv ) return cson_rc.ArgError; else { cv->refcount = rc; return 0; } } #endif int cson_value_add_reference( cson_value * cv ) { if( NULL == cv ) return cson_rc.ArgError; else if( (cv->refcount+1) < cv->refcount ) { return cson_rc.RangeError; } else { cson_refcount_incr( cv ); return 0; } } /** If cv is NULL or cson_value_is_builtin(cv) returns true then this function does nothing and returns 0, otherwise... If cv->refcount is 0 or 1 then cson_value_clean(cv) is called, cv is freed, and 0 is returned. If cv->refcount is any other value then it is decremented and the new value is returned. */ static cson_counter_t cson_refcount_decr( cson_value * cv ) { if( (NULL == cv) || cson_value_is_builtin(cv) ) return 0; else if( (0 == cv->refcount) || (0 == --cv->refcount) ) { cson_value_clean(cv); cson_free(cv,"cson_value::refcount=0"); return 0; } else return cv->refcount; } /** Allocates a new cson_string object with enough space for the given number of bytes. A byte for a NUL terminator is added automatically. Use cson_string_str() to get access to the string bytes, which will be len bytes long. len may be 0, in which case the internal string is "", as opposed to null. This is because the string bytes and the cson_string are allocated in a single chunk of memory, and the cson_string object does not directly provide (or have) a pointer to the string bytes. */ static cson_string * cson_string_alloc(unsigned int len) { if( ! len ) return &CSON_EMPTY_HOLDER.stringValue; else { cson_string * s = NULL; const size_t msz = sizeof(cson_string) + len + 1 /*NUL*/; unsigned char * mem = NULL; if( msz < (sizeof(cson_string)+len) ) /*overflow*/ return NULL; mem = (unsigned char *)cson_malloc( msz, "cson_string_alloc" ); if( mem ) { memset( mem, 0, msz ); s = (cson_string *)mem; s->length = len; } return s; } } unsigned int cson_string_length_bytes( cson_string const * str ) { return str ? str->length : 0; } /** Fetches v's string value as a non-const string. cson_strings are supposed to be immutable, but this form provides access to the immutable bits, which are v->length bytes long. A length-0 string is returned as NULL from here, as opposed to "". (This is a side-effect of the string allocation mechanism.) Returns NULL if !v. */ static char * cson_string_str(cson_string *v) { /* See http://groups.google.com/group/comp.lang.c.moderated/browse_thread/thread/2e0c0df5e8a0cd6a */ #if 1 if( !v || (&CSON_EMPTY_HOLDER.stringValue == v) ) return NULL; else return (char *)((unsigned char *)( v+1 )); #else static char empty[2] = {0,0}; return ( NULL == v ) ? NULL : (v->length ? (char *) (((unsigned char *)v) + sizeof(cson_string)) : empty) ; #endif } /** Fetches v's string value as a const string. */ char const * cson_string_cstr(cson_string const *v) { /* See http://groups.google.com/group/comp.lang.c.moderated/browse_thread/thread/2e0c0df5e8a0cd6a */ #if 1 if( ! v ) return NULL; else if( v == &CSON_EMPTY_HOLDER.stringValue ) return ""; else return (char *)((unsigned char *)(v+1)); #else return (NULL == v) ? NULL : (v->length ? (char const *) ((unsigned char const *)(v+1)) : ""); #endif } #if 0 /** Just like strndup(3), in that neither are C89/C99-standard and both are documented in detail in strndup(3). */ static char * cson_strdup( char const * src, size_t n ) { char * rc = (char *)cson_malloc(n+1, "cson_strdup"); if( ! rc ) return NULL; memset( rc, 0, n+1 ); rc[n] = 0; return strncpy( rc, src, n ); } #endif /** Allocates a new cson_string() from the the first n bytes of src. Returns NULL on allocation error, else the caller owns the returned object and must eventually free() it. */ static cson_string * cson_string_strdup( char const * src, size_t n ) { cson_string * cs = cson_string_alloc(n); if( ! cs ) return NULL; else if( &CSON_EMPTY_HOLDER.stringValue == cs ) return cs; else { char * cstr = cson_string_str(cs); assert( cs->length == n ); if( cstr && n ) { strncpy( cstr, src, n ); } return cs; } } int cson_string_cmp_cstr_n( cson_string const * str, char const * other, unsigned int otherLen ) { if( ! other && !str ) return 0; else if( other && !str ) return 1; else if( str && !other ) return -1; else if( !otherLen ) return str->length ? 1 : 0; else if( !str->length ) return otherLen ? -1 : 0; else { unsigned const int max = (otherLen > str->length) ? otherLen : str->length; int const rc = strncmp( cson_string_cstr(str), other, max ); return ( (0 == rc) && (otherLen != str->length) ) ? (str->length < otherLen) ? -1 : 1 : rc; } } int cson_string_cmp_cstr( cson_string const * lhs, char const * rhs ) { return cson_string_cmp_cstr_n( lhs, rhs, (rhs&&*rhs) ? strlen(rhs) : 0 ); } int cson_string_cmp( cson_string const * lhs, cson_string const * rhs ) { return cson_string_cmp_cstr_n( lhs, cson_string_cstr(rhs), rhs ? rhs->length : 0 ); } /** If self is not NULL, *self is overwritten to have the undefined type. self is not cleaned up or freed. */ void cson_value_destroy_zero_it( cson_value * self ) { if( self ) { *self = cson_value_undef; } } /** If self is not null, free(self->value) is called. *self is then overwritten to have the undefined type. self is not freed. */ void cson_value_destroy_free( cson_value * self ) { if(self) { if( self->value ) { cson_free(self->value,"cson_value_destroy_free()"); } *self = cson_value_undef; } } /** A key/value pair collection. Each of these objects owns its key/value pointers, and they are cleaned up by cson_kvp_clean(). */ struct cson_kvp { cson_string * key; cson_value * value; }; #define cson_kvp_empty_m {NULL,NULL} static const cson_kvp cson_kvp_empty = cson_kvp_empty_m; /** @def CSON_OBJECT_PROPS_SORT If CSON_OBJECT_PROPS_SORT is set to a true value then qsort() and bsearch() are used to sort (upon insertion) and search cson_object::kvp property lists. This costs us a re-sort on each insertion but searching is O(log n) average/worst case (and O(1) best-case). i'm not yet convinced that the overhead of the qsort() justifies the potentially decreased search times - it has not been measured. Object property lists tend to be relatively short in JSON, and a linear search which uses the cson_string::length property as a quick check is quite fast when one compares it with the sort overhead required by the bsearch() approach. */ #define CSON_OBJECT_PROPS_SORT 0 /** @def CSON_OBJECT_PROPS_SORT_USE_LENGTH Don't use this - i'm not sure that it works how i'd like. If CSON_OBJECT_PROPS_SORT_USE_LENGTH is true then we use string lengths as quick checks when sorting property keys. This leads to a non-intuitive sorting order but "should" be faster. This is ignored if CSON_OBJECT_PROPS_SORT is false. */ #define CSON_OBJECT_PROPS_SORT_USE_LENGTH 0 #if CSON_OBJECT_PROPS_SORT #if 0 /* i would prefer case-insensitive sorting but keys need to be case-sensitive for search purposes. TODO? write a comparitor which reverses the default sort order of upper/lower-case. The current behaviour is a bit non-intuitive, where 'Z' < 'a'. */ static int cson_kvp_strcmp( char const * l, char const * r ) { char cl; char cr; for( ; *l && *r; ++l, ++r ) { cl = tolower(*l); cr = tolower(*r); if( cl < cr ) return -1; else if( cl > cr ) return 1; } if( !*l && !*r ) return 0; else return (*l) ? 1 : -1; } #endif /** cson_kvp comparator for use with qsort(). ALMOST compares with strcmp() semantics, but it uses the strings' lengths as a quicker approach. This might give non-intuitive results, but it's faster. */ static int cson_kvp_cmp( void const * lhs, void const * rhs ) { cson_kvp const * lk = *((cson_kvp const * const*)lhs); cson_kvp const * rk = *((cson_kvp const * const*)rhs); cson_string const * l = lk->key; cson_string const * r = rk->key; #if CSON_OBJECT_PROPS_SORT_USE_LENGTH if( l->length < r->length ) return -1; else if( l->length > r->length ) return 1; else return strcmp( cson_string_cstr( l ), cson_string_cstr( r ) ); #else return strcmp( cson_string_cstr( l ), cson_string_cstr( r ) ); #endif /*CSON_OBJECT_PROPS_SORT_USE_LENGTH*/ } #endif /*CSON_OBJECT_PROPS_SORT*/ #if CSON_OBJECT_PROPS_SORT /** A bsearch() comparison function which requires that lhs be a (char const *) and rhs be-a (cson_kvp const * const *). It compares lhs to rhs->key's value, using strcmp() semantics. */ static int cson_kvp_cmp_vs_cstr( void const * lhs, void const * rhs ) { char const * lk = (char const *)lhs; cson_kvp const * rk = *((cson_kvp const * const*)rhs) ; #if CSON_OBJECT_PROPS_SORT_USE_LENGTH unsigned int llen = strlen(lk); if( llen < rk->key->length ) return -1; else if( llen > rk->key->length ) return 1; else return strcmp( lk, cson_string_cstr( rk->key ) ); #else return strcmp( lk, cson_string_cstr( rk->key ) ); #endif /*CSON_OBJECT_PROPS_SORT_USE_LENGTH*/ } #endif /*CSON_OBJECT_PROPS_SORT*/ struct cson_kvp_list { cson_kvp ** list; unsigned int count; unsigned int alloced; }; typedef struct cson_kvp_list cson_kvp_list; #define cson_kvp_list_empty_m {NULL/*list*/,0/*count*/,0/*alloced*/} static const cson_kvp_list cson_kvp_list_empty = cson_kvp_list_empty_m; struct cson_object { cson_kvp_list kvp; }; /*typedef struct cson_object cson_object;*/ #define cson_object_empty_m { cson_kvp_list_empty_m/*kvp*/ } static const cson_object cson_object_empty = cson_object_empty_m; struct cson_value_list { cson_value ** list; unsigned int count; unsigned int alloced; }; typedef struct cson_value_list cson_value_list; #define cson_value_list_empty_m {NULL/*list*/,0/*count*/,0/*alloced*/} static const cson_value_list cson_value_list_empty = cson_value_list_empty_m; struct cson_array { cson_value_list list; }; /*typedef struct cson_array cson_array;*/ #define cson_array_empty_m { cson_value_list_empty_m/*list*/ } static const cson_array cson_array_empty = cson_array_empty_m; struct cson_parser { JSON_parser p; cson_value * root; cson_value * node; cson_array stack; cson_string * ckey; int errNo; unsigned int totalKeyCount; unsigned int totalValueCount; }; typedef struct cson_parser cson_parser; static const cson_parser cson_parser_empty = { NULL/*p*/, NULL/*root*/, NULL/*node*/, cson_array_empty_m/*stack*/, NULL/*ckey*/, 0/*errNo*/, 0/*totalKeyCount*/, 0/*totalValueCount*/ }; #if 1 /* The following funcs are declared in generated code (cson_lists.h), but we need early access to their decls for the Amalgamation build. */ static unsigned int cson_value_list_reserve( cson_value_list * self, unsigned int n ); static unsigned int cson_kvp_list_reserve( cson_kvp_list * self, unsigned int n ); static int cson_kvp_list_append( cson_kvp_list * self, cson_kvp * cp ); static void cson_kvp_list_clean( cson_kvp_list * self, void (*cleaner)(cson_kvp * obj) ); #if 0 static int cson_value_list_append( cson_value_list * self, cson_value * cp ); static void cson_value_list_clean( cson_value_list * self, void (*cleaner)(cson_value * obj)); static int cson_kvp_list_visit( cson_kvp_list * self, int (*visitor)(cson_kvp * obj, void * visitorState ), void * visitorState ); static int cson_value_list_visit( cson_value_list * self, int (*visitor)(cson_value * obj, void * visitorState ), void * visitorState ); #endif #endif #if 0 # define LIST_T cson_value_list # define VALUE_T cson_value * # define VALUE_T_IS_PTR 1 # define LIST_T cson_kvp_list # define VALUE_T cson_kvp * # define VALUE_T_IS_PTR 1 #else #endif /* Reminders to self: - 20110126: moved cson_value_new() and cson_value_set_xxx() out of the public API because: a) They can be easily mis-used to cause memory leaks, even when used in a manner which seems relatively intuitive. b) Having them in the API prohibits us from eventually doing certain allocation optimizations like not allocating Booleans, Integer/Doubles with the value 0, or empty Strings. The main problem is that cson_value_set_xxx() cannot be implemented properly if we add that type of optimization. */ /** Allocates a new value with the "undefined" value and transfers ownership of it to the caller. Use The cson_value_set_xxx() family of functions to assign a typed value to it. It must eventually be destroyed, by the caller or its owning container, by passing it to cson_value_free(). Returns NULL on allocation error. @see cson_value_new_array() @see cson_value_new_object() @see cson_value_new_string() @see cson_value_new_integer() @see cson_value_new_double() @see cson_value_new_bool() @see cson_value_free() */ static cson_value * cson_value_new(); /** Cleans any existing contents of val and sets its new value to the special NULL value. Returns 0 on success. */ #if 0 static int cson_value_set_null( cson_value * val ); #endif /** Cleans any existing contents of val and sets its new value to v. Returns 0 on success. */ #if 0 static int cson_value_set_bool( cson_value * val, char v ); #endif /** Cleans any existing contents of val and sets its new value to v. Returns 0 on success. */ static int cson_value_set_integer( cson_value * val, cson_int_t v ); /** Cleans any existing contents of val and sets its new value to v. Returns 0 on success. */ static int cson_value_set_double( cson_value * val, cson_double_t v ); /** Cleans any existing contents of val and sets its new value to str. On success, ownership of str is passed on to val. On error ownership is not changed. Returns 0 on success. If str is NULL, (!*str), or (!len) then this function does not allocate any memory for a new string, and cson_value_fetch_string() will return an empty string as opposed to a NULL string. */ static int cson_value_set_string( cson_value * val, char const * str, unsigned int len ); cson_value * cson_value_new() { cson_value * v = (cson_value *)cson_malloc(sizeof(cson_value),"cson_value_new"); if( v ) *v = cson_value_undef; return v; } void cson_value_free(cson_value *v) { cson_refcount_decr( v ); } #if 0 /* we might actually want this later on. */ /** Returns true if v is not NULL and has the given type ID. */ static char cson_value_is_a( cson_value const * v, cson_type_id is ) { return (v && v->api && (v->api->typeID == is)) ? 1 : 0; } #endif #if 0 cson_type_id cson_value_type_id( cson_value const * v ) { return (v && v->api) ? v->api->typeID : CSON_TYPE_UNDEF; } #endif char cson_value_is_undef( cson_value const * v ) { /** This special-case impl is needed because the underlying (generic) list operations do not know how to populate new entries */ return ( !v || !v->api || (v->api==&cson_value_api_undef)) ? 1 : 0; } #define ISA(T,TID) char cson_value_is_##T( cson_value const * v ) { \ /*return (v && v->api) ? cson_value_is_a(v,CSON_TYPE_##TID) : 0;*/ \ return (v && (v->api == &cson_value_api_##T)) ? 1 : 0; \ } static const char bogusPlaceHolderForEmacsIndention##TID = CSON_TYPE_##TID ISA(null,NULL); ISA(bool,BOOL); ISA(integer,INTEGER); ISA(double,DOUBLE); ISA(string,STRING); ISA(array,ARRAY); ISA(object,OBJECT); #undef ISA char cson_value_is_number( cson_value const * v ) { return cson_value_is_integer(v) || cson_value_is_double(v); } void cson_value_clean( cson_value * val ) { if( val && val->api && val->api->cleanup ) { if( ! cson_value_is_builtin( val ) ) { cson_counter_t const rc = val->refcount; val->api->cleanup(val); *val = cson_value_undef; val->refcount = rc; } } } static void cson_value_destroy_integer( cson_value * self ) { if( self ) { #if !CSON_VOID_PTR_IS_BIG cson_free(self->value,"cson_int_t"); #endif *self = cson_value_empty; } } static int cson_value_set_integer( cson_value * val, cson_int_t v ) { if( ! val ) return cson_rc.ArgError; else { #if CSON_VOID_PTR_IS_BIG cson_value_clean( val ); val->value = (void *)v; #else cson_int_t * iv = NULL; cson_value_clean( val ); iv = (cson_int_t*)cson_malloc(sizeof(cson_int_t), "cson_int_t"); if( ! iv ) return cson_rc.AllocError; *iv = v; val->value = iv; #endif val->api = &cson_value_api_integer; return 0; } } static int cson_value_set_double( cson_value * val, cson_double_t v ) { if( ! val ) return cson_rc.ArgError; else { cson_double_t * rv = NULL; cson_value_clean( val ); val->api = &cson_value_api_double; if( 0.0 != v ) { /* Reminder: we can't re-use val if it alreay is-a double because we have no reference counting. */ rv = (cson_double_t*)cson_malloc(sizeof(cson_double_t),"double"); if( ! rv ) return cson_rc.AllocError; } if(NULL != rv) *rv = v; val->value = rv; return 0; } } static cson_string * cson_string_shared_empty() { /** We have code in place elsewhere to avoid that cson_string_cstr(&bob) and cson_string_str(&bob) will misbehave by accessing the bytes directly after bob (which are undefined in this case). */ #if 0 static cson_string bob[2] = {cson_string_empty_m, cson_string_empty_m/*trick to 0-init bob[0]'s tail*/}; return &bob[0]; #else static cson_string bob = cson_string_empty_m; return &bob; #endif } static int cson_value_set_string( cson_value * val, char const * str, unsigned int len ) { cson_string * jstr = NULL; if( ! val ) return cson_rc.ArgError; cson_value_clean( val ); val->api = &cson_value_api_string; if( !str || !*str || !len ) { val->value = cson_string_shared_empty(); return 0; } else { jstr = cson_string_alloc( len ); if( NULL == jstr ) return cson_rc.AllocError; else { if( len ) { char * dest = cson_string_str( jstr ); val->value = jstr; strncpy( dest, str, len ); } /* else it's the empty string special value */ return 0; } } } static cson_value * cson_value_array_alloc() { cson_value * v = (cson_value*)cson_malloc(sizeof(cson_value),"cson_value_array"); if( NULL != v ) { cson_array * ar = (cson_array *)cson_malloc(sizeof(cson_array),"cson_array"); if( ! ar ) { cson_free(v,"cson_array"); v = NULL; } else { *ar = cson_array_empty; *v = cson_value_array_empty; v->value = ar; } } return v; } static cson_value * cson_value_object_alloc() { cson_value * v = (cson_value*)cson_malloc(sizeof(cson_value),"cson_value_object"); if( NULL != v ) { cson_object * obj = (cson_object*)cson_malloc(sizeof(cson_object),"cson_value"); if( ! obj ) { cson_free(v,"cson_value_object"); v = NULL; } else { *obj = cson_object_empty; *v = cson_value_object_empty; v->value = obj; } } return v; } cson_value * cson_value_new_object() { return cson_value_object_alloc(); } cson_value * cson_value_new_array() { return cson_value_array_alloc(); } /** Frees kvp->key and kvp->value and sets them to NULL, but does not free kvp. If !kvp then this is a no-op. */ static void cson_kvp_clean( cson_kvp * kvp ) { if( kvp ) { if(kvp->key) { cson_free(kvp->key,"cson_kvp::key"); kvp->key = NULL; } if(kvp->value) { cson_value_free( kvp->value ); kvp->value = NULL; } } } cson_string const * cson_kvp_key( cson_kvp const * kvp ) { return kvp ? kvp->key : NULL; } cson_value * cson_kvp_value( cson_kvp const * kvp ) { return kvp ? kvp->value : NULL; } /** Calls cson_kvp_clean(kvp) and then frees kvp. */ static void cson_kvp_free( cson_kvp * kvp ) { if( kvp ) { cson_kvp_clean(kvp); cson_free(kvp,"cson_kvp"); } } /** cson_value_api::destroy_value() impl for Object values. Cleans up self-owned memory and overwrites self to have the undefined value, but does not free self. If self->value == cson_string_shared_empty() then this function does not actually free it. */ static void cson_value_destroy_string( cson_value * self ) { if(self && self->value) { cson_string * obj = (cson_string *)self->value; if( obj != cson_string_shared_empty() ) { cson_free(self->value,"cson_string"); } *self = cson_value_undef; } } /** cson_value_api::destroy_value() impl for Object values. Cleans up self-owned memory and overwrites self to have the undefined value, but does not free self. */ static void cson_value_destroy_object( cson_value * self ) { if(self && self->value) { cson_object * obj = (cson_object *)self->value; assert( self->value == obj ); cson_kvp_list_clean( &obj->kvp, cson_kvp_free ); cson_free(self->value,"cson_object"); *self = cson_value_undef; } } /** Cleans up the contents of ar->list, but does not free ar. After calling this, ar will have a length of 0. If properlyCleanValues is 1 then cson_value_free() is called on each non-NULL item, otherwise the outer list is destroyed but the individual items are assumed to be owned by someone else and are not freed. */ static void cson_array_clean( cson_array * ar, char properlyCleanValues ) { if( ar ) { unsigned int i = 0; cson_value * val = NULL; for( ; i < ar->list.count; ++i ) { val = ar->list.list[i]; if(val) { ar->list.list[i] = NULL; if( properlyCleanValues ) { cson_value_free( val ); } } } cson_value_list_reserve(&ar->list,0); ar->list = cson_value_list_empty /* Pedantic note: reserve(0) already clears the list-specific fields, but we do this just in case we ever add new fields to cson_value_list which are not used in the reserve() impl. */ ; } } /** cson_value_api::destroy_value() impl for Array values. Cleans up self-owned memory and overwrites self to have the undefined value, but does not free self. */ static void cson_value_destroy_array( cson_value * self ) { cson_array * ar = cson_value_get_array(self); if(ar) { assert( self->value == ar ); cson_array_clean( ar, 1 ); cson_free(ar,"cson_array"); *self = cson_value_undef; } } #if 0 static void cson_kvp_list_item_clean( void * kvp ); static void cson_value_list_item_clean( void * val ); void cson_value_list_item_clean( void * val_ ) { cson_value * val = (cson_value*)val_; if( val ) { cson_value_clean(val); } } void cson_kvp_list_item_clean( void * val ) { cson_kvp * kvp = (cson_kvp *)val; if( kvp ) { cson_free(kvp->key,"cson_kvp::key"); cson_value_clean( &kvp->value ); } } #endif int cson_buffer_fill_from( cson_buffer * dest, cson_data_source_f src, void * state ) { int rc; enum { BufSize = 1024 * 4 }; char rbuf[BufSize]; size_t total = 0; unsigned int rlen = 0; if( ! dest || ! src ) return cson_rc.ArgError; dest->used = 0; while(1) { rlen = BufSize; rc = src( state, rbuf, &rlen ); if( rc ) break; total += rlen; if( dest->capacity < (total+1) ) { rc = cson_buffer_reserve( dest, total + 1); if( 0 != rc ) break; } memcpy( dest->mem + dest->used, rbuf, rlen ); dest->used += rlen; if( rlen < BufSize ) break; } if( !rc && dest->used ) { assert( dest->used < dest->capacity ); dest->mem[dest->used] = 0; } return rc; } int cson_data_source_FILE( void * state, void * dest, unsigned int * n ) { FILE * f = (FILE*) state; if( ! state || ! n || !dest ) return cson_rc.ArgError; else if( !*n ) return cson_rc.RangeError; *n = (unsigned int)fread( dest, 1, *n, f ); if( !*n ) { return feof(f) ? 0 : cson_rc.IOError; } return 0; } int cson_parse_FILE( cson_value ** tgt, FILE * src, cson_parse_opt const * opt, cson_parse_info * err ) { return cson_parse( tgt, cson_data_source_FILE, src, opt, err ); } int cson_value_fetch_bool( cson_value const * val, char * v ) { /** FIXME: move the to-bool operation into cson_value_api, like we do in the C++ API. */ if( ! val || !val->api ) return cson_rc.ArgError; else { int rc = 0; char b = 0; switch( val->api->typeID ) { case CSON_TYPE_ARRAY: case CSON_TYPE_OBJECT: b = 1; break; case CSON_TYPE_STRING: { char const * str = cson_string_cstr(cson_value_get_string(val)); b = (str && *str) ? 1 : 0; break; } case CSON_TYPE_UNDEF: case CSON_TYPE_NULL: break; case CSON_TYPE_BOOL: b = (NULL==val->value) ? 0 : 1; break; case CSON_TYPE_INTEGER: { cson_int_t i = 0; cson_value_fetch_integer( val, &i ); b = i ? 1 : 0; break; } case CSON_TYPE_DOUBLE: { cson_double_t d = 0.0; cson_value_fetch_double( val, &d ); b = (0.0==d) ? 0 : 1; break; } default: rc = cson_rc.TypeError; break; } if( v ) *v = b; return rc; } } char cson_value_get_bool( cson_value const * val ) { char i = 0; cson_value_fetch_bool( val, &i ); return i; } int cson_value_fetch_integer( cson_value const * val, cson_int_t * v ) { if( ! val || !val->api ) return cson_rc.ArgError; else { cson_int_t i = 0; int rc = 0; switch(val->api->typeID) { case CSON_TYPE_UNDEF: case CSON_TYPE_NULL: i = 0; break; case CSON_TYPE_BOOL: { char b = 0; cson_value_fetch_bool( val, &b ); i = b; break; } case CSON_TYPE_INTEGER: { #if CSON_VOID_PTR_IS_BIG i = (cson_int_t)val->value; #else cson_int_t const * x = (cson_int_t const *)val->value; i = x ? *x : 0; #endif break; } case CSON_TYPE_DOUBLE: { cson_double_t d = 0.0; cson_value_fetch_double( val, &d ); i = (cson_int_t)d; break; } case CSON_TYPE_STRING: case CSON_TYPE_ARRAY: case CSON_TYPE_OBJECT: default: break; } if(v) *v = i; return rc; } } cson_int_t cson_value_get_integer( cson_value const * val ) { cson_int_t i = 0; cson_value_fetch_integer( val, &i ); return i; } int cson_value_fetch_double( cson_value const * val, cson_double_t * v ) { if( ! val || !val->api ) return cson_rc.ArgError; else { cson_double_t d = 0.0; int rc = 0; switch(val->api->typeID) { case CSON_TYPE_UNDEF: case CSON_TYPE_NULL: d = 0; break; case CSON_TYPE_BOOL: { char b = 0; cson_value_fetch_bool( val, &b ); d = b ? 1.0 : 0.0; break; } case CSON_TYPE_INTEGER: { cson_int_t i = 0; cson_value_fetch_integer( val, &i ); d = i; break; } case CSON_TYPE_DOUBLE: { cson_double_t const* dv = (cson_double_t const *)val->value; d = dv ? *dv : 0.0; break; } default: rc = cson_rc.TypeError; break; } if(v) *v = d; return rc; } } cson_double_t cson_value_get_double( cson_value const * val ) { cson_double_t i = 0.0; cson_value_fetch_double( val, &i ); return i; } int cson_value_fetch_string( cson_value const * val, cson_string const ** dest ) { if( ! val || ! dest ) return cson_rc.ArgError; else if( ! cson_value_is_string(val) ) return cson_rc.TypeError; else { if( dest ) *dest = (cson_string const *)val->value; return 0; } } cson_string const * cson_value_get_string( cson_value const * val ) { cson_string const * rc = NULL; cson_value_fetch_string( val, &rc ); return rc; } char const * cson_value_get_cstr( cson_value const * val ) { return cson_string_cstr( cson_value_get_string(val) ); } int cson_value_fetch_object( cson_value const * val, cson_object ** obj ) { if( ! val ) return cson_rc.ArgError; else if( ! cson_value_is_object(val) ) return cson_rc.TypeError; else { if(obj) *obj = (cson_object*)val->value; return 0; } } cson_object * cson_value_get_object( cson_value const * v ) { cson_object * obj = NULL; cson_value_fetch_object( v, &obj ); return obj; } int cson_value_fetch_array( cson_value const * val, cson_array ** ar) { if( ! val ) return cson_rc.ArgError; else if( ! cson_value_is_array(val) ) return cson_rc.TypeError; else { if(ar) *ar = (cson_array*)val->value; return 0; } } cson_array * cson_value_get_array( cson_value const * v ) { cson_array * ar = NULL; cson_value_fetch_array( v, &ar ); return ar; } cson_kvp * cson_kvp_alloc() { cson_kvp * kvp = (cson_kvp*)cson_malloc(sizeof(cson_kvp),"cson_kvp"); if( kvp ) { *kvp = cson_kvp_empty; } return kvp; } int cson_array_append( cson_array * ar, cson_value * v ) { if( !ar || !v ) return cson_rc.ArgError; else if( (ar->list.count+1) < ar->list.count ) return cson_rc.RangeError; else { if( !ar->list.alloced || (ar->list.count == ar->list.alloced-1)) { unsigned int const n = ar->list.count ? (ar->list.count*2) : 7; if( n > cson_value_list_reserve( &ar->list, n ) ) { return cson_rc.AllocError; } } return cson_array_set( ar, ar->list.count, v ); } } #if 0 /** Removes and returns the last value from the given array, shrinking its size by 1. Returns NULL if ar is NULL, ar->list.count is 0, or the element at that index is NULL. If removeRef is true then cson_value_free() is called to remove ar's reference count for the value. In that case NULL is returned, even if the object still has live references. If removeRef is false then the caller takes over ownership of that reference count point. If removeRef is false then the caller takes over ownership of the return value, otherwise ownership is effectively determined by any remaining references for the returned value. */ static cson_value * cson_array_pop_back( cson_array * ar, char removeRef ) { if( !ar ) return NULL; else if( ! ar->list.count ) return NULL; else { unsigned int const ndx = --ar->list.count; cson_value * v = ar->list.list[ndx]; ar->list.list[ndx] = NULL; if( removeRef ) { cson_value_free( v ); v = NULL; } return v; } } #endif cson_value * cson_value_new_bool( char v ) { return v ? &CSON_SPECIAL_VALUES[CSON_VAL_TRUE] : &CSON_SPECIAL_VALUES[CSON_VAL_FALSE]; } cson_value * cson_value_true() { return &CSON_SPECIAL_VALUES[CSON_VAL_TRUE]; } cson_value * cson_value_false() { return &CSON_SPECIAL_VALUES[CSON_VAL_FALSE]; } cson_value * cson_value_null() { return &CSON_SPECIAL_VALUES[CSON_VAL_NULL]; } cson_value * cson_value_new_integer( cson_int_t v ) { if( 0 == v ) return &CSON_SPECIAL_VALUES[CSON_VAL_INT_0]; else { cson_value * c = cson_value_new(); if( c ) { if( 0 != cson_value_set_integer( c, v ) ) { cson_value_free(c); c = NULL; } } return c; } } cson_value * cson_value_new_double( cson_double_t v ) { if( 0.0 == v ) return &CSON_SPECIAL_VALUES[CSON_VAL_DBL_0]; else { cson_value * c = cson_value_new(); if( c ) { if( 0 != cson_value_set_double( c, v ) ) { cson_value_free(c); c = NULL; } } return c; } } cson_value * cson_value_new_string( char const * str, unsigned int len ) { if( !str || !len ) return &CSON_SPECIAL_VALUES[CSON_VAL_STR_EMPTY]; else { cson_value * c = cson_value_new(); if( c ) { if( 0 != cson_value_set_string( c, str, len ) ) { cson_value_free(c); c = NULL; } } return c; } } int cson_array_value_fetch( cson_array const * ar, unsigned int pos, cson_value ** v ) { if( !ar) return cson_rc.ArgError; if( pos >= ar->list.count ) return cson_rc.RangeError; else { if(v) *v = ar->list.list[pos]; return 0; } } cson_value * cson_array_get( cson_array const * ar, unsigned int pos ) { cson_value *v = NULL; cson_array_value_fetch(ar, pos, &v); return v; } int cson_array_length_fetch( cson_array const * ar, unsigned int * v ) { if( ! ar || !v ) return cson_rc.ArgError; else { if(v) *v = ar->list.count; return 0; } } unsigned int cson_array_length_get( cson_array const * ar ) { unsigned int i = 0; cson_array_length_fetch(ar, &i); return i; } int cson_array_reserve( cson_array * ar, unsigned int size ) { if( ! ar ) return cson_rc.ArgError; else if( size <= ar->list.alloced ) { /* We don't want to introduce a can of worms by trying to handle the cleanup from here. */ return 0; } else { return (ar->list.alloced > cson_value_list_reserve( &ar->list, size )) ? cson_rc.AllocError : 0 ; } } int cson_array_set( cson_array * ar, unsigned int ndx, cson_value * v ) { if( !ar || !v ) return cson_rc.ArgError; else if( (ndx+1) < ndx) /* overflow */return cson_rc.RangeError; else { unsigned const int len = cson_value_list_reserve( &ar->list, ndx+1 ); if( len <= ndx ) return cson_rc.AllocError; else { cson_value * old = ar->list.list[ndx]; if( old ) { if(old == v) return 0; else cson_value_free(old); } cson_refcount_incr( v ); ar->list.list[ndx] = v; if( ndx >= ar->list.count ) { ar->list.count = ndx+1; } return 0; } } } /** @internal Searchs for the given key in the given object. Returns the found item on success, NULL on error. If ndx is not NULL, it is set to the index (in obj->kvp.list) of the found item. *ndx is not modified if no entry is found. */ static cson_kvp * cson_object_search_impl( cson_object const * obj, char const * key, unsigned int * ndx ) { if( obj && key && *key && obj->kvp.count) { #if CSON_OBJECT_PROPS_SORT cson_kvp ** s = (cson_kvp**) bsearch( key, obj->kvp.list, obj->kvp.count, sizeof(cson_kvp*), cson_kvp_cmp_vs_cstr ); if( ndx && s ) { /* index of found record is required by cson_object_unset(). Calculate the offset based on s...*/ #if 0 *ndx = (((unsigned char const *)s - ((unsigned char const *)obj->kvp.list)) / sizeof(cson_kvp*)); #else *ndx = s - obj->kvp.list; #endif } return s ? *s : NULL; #else cson_kvp_list const * li = &obj->kvp; unsigned int i = 0; cson_kvp * kvp; const unsigned int klen = strlen(key); for( ; i < li->count; ++i ) { kvp = li->list[i]; assert( kvp && kvp->key ); if( kvp->key->length != klen ) continue; else if(0==strcmp(key,cson_string_cstr(kvp->key))) { if(ndx) *ndx = i; return kvp; } } #endif } return NULL; } cson_value * cson_object_get( cson_object const * obj, char const * key ) { cson_kvp * kvp = cson_object_search_impl( obj, key, NULL ); return kvp ? kvp->value : NULL; } #if CSON_OBJECT_PROPS_SORT static void cson_object_sort_props( cson_object * obj ) { assert( NULL != obj ); if( obj->kvp.count ) { qsort( obj->kvp.list, obj->kvp.count, sizeof(cson_kvp*), cson_kvp_cmp ); } } #endif int cson_object_unset( cson_object * obj, char const * key ) { if( ! obj || !key || !*key ) return cson_rc.ArgError; else { unsigned int ndx = 0; cson_kvp * kvp = cson_object_search_impl( obj, key, &ndx ); if( ! kvp ) { return cson_rc.NotFoundError; } assert( obj->kvp.count > 0 ); assert( obj->kvp.list[ndx] == kvp ); cson_kvp_free( kvp ); obj->kvp.list[ndx] = NULL; { /* if my brain were bigger i'd use memmove(). */ unsigned int i = ndx; for( ; i < obj->kvp.count; ++i ) { obj->kvp.list[i] = (i < (obj->kvp.alloced-1)) ? obj->kvp.list[i+1] : NULL; } } obj->kvp.list[--obj->kvp.count] = NULL; #if CSON_OBJECT_PROPS_SORT cson_object_sort_props( obj ); #endif return 0; } } int cson_object_set( cson_object * obj, char const * key, cson_value * v ) { if( ! obj || !key || !*key ) return cson_rc.ArgError; else if( NULL == v ) { return cson_object_unset( obj, key ); } else { cson_kvp * kvp = cson_object_search_impl( obj, key, NULL ); if( kvp ) { /* "I told 'em we've already got one!" */ if( v == kvp->value ) return 0 /* actually a usage error */; else { cson_value_free( kvp->value ); cson_refcount_incr( v ); kvp->value = v; return 0; } } if( !obj->kvp.alloced || (obj->kvp.count == obj->kvp.alloced-1)) { unsigned int const n = obj->kvp.count ? (obj->kvp.count*2) : 7; if( n > cson_kvp_list_reserve( &obj->kvp, n ) ) { return cson_rc.AllocError; } } { /* insert new item... */ int rc = 0; cson_string * keycp = cson_string_strdup(key, strlen(key)); if( ! keycp ) { return cson_rc.AllocError; } kvp = cson_kvp_alloc(); if( ! kvp ) { cson_free(keycp,"cson_parser::key"); return cson_rc.AllocError; } kvp->key = keycp /* transfer ownership */; rc = cson_kvp_list_append( &obj->kvp, kvp ); if( 0 != rc ) { cson_kvp_free(kvp); } else { cson_refcount_incr( v ); kvp->value = v /* transfer ownership */; #if CSON_OBJECT_PROPS_SORT cson_object_sort_props( obj ); #endif } return 0; } } } cson_value * cson_object_take( cson_object * obj, char const * key ) { if( ! obj || !key || !*key ) return NULL; else { /* FIXME: this is 90% identical to cson_object_unset(), only with different refcount handling. Consolidate them. */ unsigned int ndx = 0; cson_kvp * kvp = cson_object_search_impl( obj, key, &ndx ); cson_value * rc = NULL; if( ! kvp ) { return NULL; } assert( obj->kvp.count > 0 ); assert( obj->kvp.list[ndx] == kvp ); rc = kvp->value; assert( rc ); kvp->value = NULL; cson_kvp_free( kvp ); assert( rc->refcount > 0 ); --rc->refcount; obj->kvp.list[ndx] = NULL; { /* if my brain were bigger i'd use memmove(). */ unsigned int i = ndx; for( ; i < obj->kvp.count; ++i ) { obj->kvp.list[i] = (i < (obj->kvp.alloced-1)) ? obj->kvp.list[i+1] : NULL; } } obj->kvp.list[--obj->kvp.count] = NULL; #if CSON_OBJECT_PROPS_SORT cson_object_sort_props( obj ); #endif return rc; } } /** @internal If p->node is-a Object then value is inserted into the object using p->key. In any other case cson_rc.InternalError is returned. Returns cson_rc.AllocError if an allocation fails. Returns 0 on success. On error, parsing must be ceased immediately. Ownership of val is ALWAYS TRANSFERED to this function. If this function fails, val will be cleaned up and destroyed. (This simplifies error handling in the core parser.) */ static int cson_parser_set_key( cson_parser * p, cson_value * val ) { assert( p && val ); if( p->ckey && cson_value_is_object(p->node) ) { int rc; cson_object * obj = cson_value_get_object(p->node); cson_kvp * kvp = NULL; assert( obj && (p->node->value == obj) ); /** FIXME? Use cson_object_set() instead of our custom finagling with the object? We do it this way to avoid an extra alloc/strcpy of the key data. */ if( !obj->kvp.alloced || (obj->kvp.count == obj->kvp.alloced-1)) { if( obj->kvp.alloced > cson_kvp_list_reserve( &obj->kvp, obj->kvp.count ? (obj->kvp.count*2) : 5 ) ) { cson_value_free(val); return cson_rc.AllocError; } } kvp = cson_kvp_alloc(); if( ! kvp ) { cson_value_free(val); return cson_rc.AllocError; } kvp->key = p->ckey/*transfer ownership*/; p->ckey = NULL; kvp->value = val; cson_refcount_incr( val ); rc = cson_kvp_list_append( &obj->kvp, kvp ); if( 0 != rc ) { cson_kvp_free( kvp ); } else { ++p->totalValueCount; } return rc; } else { if(val) cson_value_free(val); return p->errNo = cson_rc.InternalError; } } /** @internal Pushes val into the current object/array parent node, depending on the internal state of the parser. Ownership of val is always transfered to this function, regardless of success or failure. Returns 0 on success. On error, parsing must be ceased immediately. */ static int cson_parser_push_value( cson_parser * p, cson_value * val ) { if( p->ckey ) { /* we're in Object mode */ assert( cson_value_is_object( p->node ) ); return cson_parser_set_key( p, val ); } else if( cson_value_is_array( p->node ) ) { /* we're in Array mode */ cson_array * ar = cson_value_get_array( p->node ); int rc; assert( ar && (ar == p->node->value) ); rc = cson_array_append( ar, val ); if( 0 != rc ) { cson_value_free(val); } else { ++p->totalValueCount; } return rc; } else { /* WTF? */ assert( 0 && "Internal error in cson_parser code" ); return p->errNo = cson_rc.InternalError; } } /** Callback for JSON_parser API. Reminder: it returns 0 (meaning false) on error! */ static int cson_parse_callback( void * cx, int type, JSON_value const * value ) { cson_parser * p = (cson_parser *)cx; int rc = 0; #define ALLOC_V(T,V) cson_value * v = cson_value_new_##T(V); if( ! v ) { rc = cson_rc.AllocError; break; } switch(type) { case JSON_T_ARRAY_BEGIN: case JSON_T_OBJECT_BEGIN: { cson_value * obja = (JSON_T_ARRAY_BEGIN == type) ? cson_value_new_array() : cson_value_new_object(); if( ! obja ) { p->errNo = cson_rc.AllocError; return 0; } if( 0 != rc ) break; if( ! p->root ) { p->root = p->node = obja; rc = cson_array_append( &p->stack, obja ); if( 0 != rc ) { /* work around a (potential) corner case in the cleanup code. */ cson_value_free( p->root ); p->root = NULL; } else { cson_refcount_incr( p->root ) /* simplifies cleanup later on. */ ; ++p->totalValueCount; } } else { rc = cson_array_append( &p->stack, obja ); if( 0 == rc ) rc = cson_parser_push_value( p, obja ); if( 0 == rc ) p->node = obja; } break; } case JSON_T_ARRAY_END: case JSON_T_OBJECT_END: { if( 0 == p->stack.list.count ) { rc = cson_rc.RangeError; break; } #if CSON_OBJECT_PROPS_SORT if( cson_value_is_object(p->node) ) {/* kludge: the parser uses custom cson_object property insertion as a malloc/strcpy-reduction optimization. Because of that, we have to sort the property list ourselves... */ cson_object * obj = cson_value_get_object(p->node); assert( NULL != obj ); cson_object_sort_props( obj ); } #endif #if 1 /* Reminder: do not use cson_array_pop_back( &p->stack ) because that will clean up the object, and we don't want that. We just want to forget this reference to it. The object is either the root or was pushed into an object/array in the parse tree (and is owned by that object/array). */ --p->stack.list.count; assert( p->node == p->stack.list.list[p->stack.list.count] ); cson_refcount_decr( p->node ) /* p->node might be owned by an outer object but we need to remove the list's reference. For the root node we manually add a reference to avoid a special case here. Thus when we close the root node, its refcount is still 1. */; p->stack.list.list[p->stack.list.count] = NULL; if( p->stack.list.count ) { p->node = p->stack.list.list[p->stack.list.count-1]; } else { p->node = p->root; } #else /* Causing a leak? */ cson_array_pop_back( &p->stack, 1 ); if( p->stack.list.count ) { p->node = p->stack.list.list[p->stack.list.count-1]; } else { p->node = p->root; } assert( p->node && (1==p->node->refcount) ); #endif break; } case JSON_T_INTEGER: { ALLOC_V(integer, value->vu.integer_value ); rc = cson_parser_push_value( p, v ); break; } case JSON_T_FLOAT: { ALLOC_V(double, value->vu.float_value ); rc = cson_parser_push_value( p, v ); break; } case JSON_T_NULL: { rc = cson_parser_push_value( p, cson_value_null() ); break; } case JSON_T_TRUE: { rc = cson_parser_push_value( p, cson_value_true() ); break; } case JSON_T_FALSE: { rc = cson_parser_push_value( p, cson_value_false() ); break; } case JSON_T_KEY: { assert(!p->ckey); p->ckey = cson_string_strdup( value->vu.str.value, value->vu.str.length ); if( ! p->ckey ) { rc = cson_rc.AllocError; break; } ++p->totalKeyCount; break; } case JSON_T_STRING: { cson_value * v = cson_value_new_string( value->vu.str.value, value->vu.str.length ); rc = ( NULL == v ) ? cson_rc.AllocError : cson_parser_push_value( p, v ); break; } default: assert(0); rc = cson_rc.InternalError; break; } #undef ALLOC_V return ((p->errNo = rc)) ? 0 : 1; } /** Converts a JSON_error code to one of the cson_rc values. */ static int cson_json_err_to_rc( JSON_error jrc ) { switch(jrc) { case JSON_E_NONE: return 0; case JSON_E_INVALID_CHAR: return cson_rc.Parse_INVALID_CHAR; case JSON_E_INVALID_KEYWORD: return cson_rc.Parse_INVALID_KEYWORD; case JSON_E_INVALID_ESCAPE_SEQUENCE: return cson_rc.Parse_INVALID_ESCAPE_SEQUENCE; case JSON_E_INVALID_UNICODE_SEQUENCE: return cson_rc.Parse_INVALID_UNICODE_SEQUENCE; case JSON_E_INVALID_NUMBER: return cson_rc.Parse_INVALID_NUMBER; case JSON_E_NESTING_DEPTH_REACHED: return cson_rc.Parse_NESTING_DEPTH_REACHED; case JSON_E_UNBALANCED_COLLECTION: return cson_rc.Parse_UNBALANCED_COLLECTION; case JSON_E_EXPECTED_KEY: return cson_rc.Parse_EXPECTED_KEY; case JSON_E_EXPECTED_COLON: return cson_rc.Parse_EXPECTED_COLON; case JSON_E_OUT_OF_MEMORY: return cson_rc.AllocError; default: return cson_rc.InternalError; } } /** @internal Cleans up all contents of p but does not free p. To properly take over ownership of the parser's root node on a successful parse: - Copy p->root's pointer and set p->root to NULL. - Eventually free up p->root with cson_value_free(). If you do not set p->root to NULL, p->root will be freed along with any other items inserted into it (or under it) during the parsing process. */ static int cson_parser_clean( cson_parser * p ) { if( ! p ) return cson_rc.ArgError; else { if( p->p ) { delete_JSON_parser(p->p); p->p = NULL; } cson_free( p->ckey, "cson_parser::key" ); cson_array_clean( &p->stack, 1 ); if( p->root ) { cson_value_free( p->root ); } *p = cson_parser_empty; return 0; } } int cson_parse( cson_value ** tgt, cson_data_source_f src, void * state, cson_parse_opt const * opt_, cson_parse_info * info_ ) { unsigned char ch[2] = {0,0}; cson_parse_opt const opt = opt_ ? *opt_ : cson_parse_opt_empty; int rc = 0; unsigned int len = 1; cson_parse_info info = info_ ? *info_ : cson_parse_info_empty; cson_parser p = cson_parser_empty; if( ! tgt || ! src ) return cson_rc.ArgError; { JSON_config jopt = {0}; init_JSON_config( &jopt ); jopt.allow_comments = opt.allowComments; jopt.depth = opt.maxDepth; jopt.callback_ctx = &p; jopt.handle_floats_manually = 0; jopt.callback = cson_parse_callback; p.p = new_JSON_parser(&jopt); if( ! p.p ) { return cson_rc.AllocError; } } do { /* FIXME: buffer the input in multi-kb chunks. */ len = 1; ch[0] = 0; rc = src( state, ch, &len ); if( 0 != rc ) break; else if( !len /* EOF */ ) break; ++info.length; if('\n' == ch[0]) { ++info.line; info.col = 0; } if( ! JSON_parser_char(p.p, ch[0]) ) { rc = cson_json_err_to_rc( JSON_parser_get_last_error(p.p) ); if(0==rc) rc = p.errNo; if(0==rc) rc = cson_rc.InternalError; info.errorCode = rc; break; } if( '\n' != ch[0]) ++info.col; } while(1); if( info_ ) { info.totalKeyCount = p.totalKeyCount; info.totalValueCount = p.totalValueCount; *info_ = info; } if( 0 != rc ) { cson_parser_clean(&p); return rc; } if( ! JSON_parser_done(p.p) ) { rc = cson_json_err_to_rc( JSON_parser_get_last_error(p.p) ); cson_parser_clean(&p); if(0==rc) rc = p.errNo; if(0==rc) rc = cson_rc.InternalError; } else { cson_value * root = p.root; p.root = NULL; cson_parser_clean(&p); if( root ) { assert( (1 == root->refcount) && "Detected memory mismanagement in the parser." ); root->refcount = 0 /* HUGE KLUDGE! Avoids having one too many references in some client code, leading to a leak. Here we're accommodating a memory management workaround in the parser code which manually adds a reference to the root node to keep it from being cleaned up prematurely. */; *tgt = root; } else { /* then can happen on empty input. */ rc = cson_rc.UnknownError; } } return rc; } /** The UTF code was originally taken from sqlite3's public-domain source code (http://sqlite.org), modified only slightly for use here. This code generates some "possible data loss" warnings on MSVC, but if this code is good enough for sqlite3 then it's damned well good enough for me, so we disable that warning for Windows builds. */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ static const unsigned char cson_utfTrans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00 }; /* ** Translate a single UTF-8 character. Return the unicode value. ** ** During translation, assume that the byte that zTerm points ** is a 0x00. ** ** Write a pointer to the next unread byte back into *pzNext. ** ** Notes On Invalid UTF-8: ** ** * This routine never allows a 7-bit character (0x00 through 0x7f) to ** be encoded as a multi-byte character. Any multi-byte character that ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. ** ** * This routine never allows a UTF16 surrogate value to be encoded. ** If a multi-byte character attempts to encode a value between ** 0xd800 and 0xe000 then it is rendered as 0xfffd. ** ** * Bytes in the range of 0x80 through 0xbf which occur as the first ** byte of a character are interpreted as single-byte characters ** and rendered as themselves even though they are technically ** invalid characters. ** ** * This routine accepts an infinite number of different UTF8 encodings ** for unicode values 0x80 and greater. It do not change over-length ** encodings to 0xfffd as some systems recommend. */ #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = cson_utfTrans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } static int cson_utf8Read( const unsigned char *z, /* First byte of UTF-8 character */ const unsigned char *zTerm, /* Pretend this byte is 0x00 */ const unsigned char **pzNext /* Write first byte past UTF-8 char here */ ){ int c; READ_UTF8(z, zTerm, c); *pzNext = z; return c; } #undef READ_UTF8 #if defined(_WIN32) # pragma warning( pop ) #endif unsigned int cson_string_length_utf8( cson_string const * str ) { if( ! str ) return 0; else { char unsigned const * pos = (char unsigned const *)cson_string_cstr(str); char unsigned const * end = pos + str->length; unsigned int rc = 0; for( ; (pos < end) && cson_utf8Read(pos, end, &pos); ++rc ) { }; return rc; } } /** Escapes the first len bytes of the given string as JSON and sends it to the given output function (which will be called often - once for each logical character). The output is also surrounded by double-quotes. A NULL str will be escaped as an empty string, though we should arguably export it as "null" (without quotes). We do this because in JavaScript (typeof null === "object"), and by outputing null here we would effectively change the data type from string to object. */ static int cson_str_to_json( char const * str, unsigned int len, char escapeFwdSlash, cson_data_dest_f f, void * state ) { if( NULL == f ) return cson_rc.ArgError; else if( !str || !*str || (0 == len) ) { /* special case for 0-length strings. */ return f( state, "\"\"", 2 ); } else { unsigned char const * pos = (unsigned char const *)str; unsigned char const * end = (unsigned char const *)(str ? (str + len) : NULL); unsigned char const * next = NULL; int ch; unsigned char clen = 0; char escChar[3] = {'\\',0,0}; enum { UBLen = 8 }; char ubuf[UBLen]; int rc = 0; rc = f(state, "\"", 1 ); for( ; (pos < end) && (0 == rc); pos += clen ) { ch = cson_utf8Read(pos, end, &next); if( 0 == ch ) break; assert( next > pos ); clen = next - pos; assert( clen ); if( 1 == clen ) { /* ASCII */ assert( *pos == ch ); escChar[1] = 0; switch(ch) { case '\t': escChar[1] = 't'; break; case '\r': escChar[1] = 'r'; break; case '\n': escChar[1] = 'n'; break; case '\f': escChar[1] = 'f'; break; case '\b': escChar[1] = 'b'; break; case '/': /* Regarding escaping of forward-slashes. See the main exchange below... -------------- From: Douglas Crockford <douglas@crockford.com> To: Stephan Beal <sgbeal@googlemail.com> Subject: Re: Is escaping of forward slashes required? It is allowed, not required. It is allowed so that JSON can be safely embedded in HTML, which can freak out when seeing strings containing "</". JSON tolerates "<\/" for this reason. On 4/8/2011 2:09 PM, Stephan Beal wrote: > Hello, Jsonites, > > i'm a bit confused on a small grammatic detail of JSON: > > if i'm reading the grammar chart on http://www.json.org/ correctly, > forward slashes (/) are supposed to be escaped in JSON. However, the > JSON class provided with my browsers (Chrome and FF, both of which i > assume are fairly standards/RFC-compliant) do not escape such characters. > > Is backslash-escaping forward slashes required? If so, what is the > justification for it? (i ask because i find it unnecessary and hard to > look at.) -------------- */ if( escapeFwdSlash ) escChar[1] = '/'; break; case '\\': escChar[1] = '\\'; break; case '"': escChar[1] = '"'; break; default: break; } if( escChar[1]) { rc = f(state, escChar, 2); } else { rc = f(state, (char const *)pos, clen); } continue; } else { /* UTF: transform it to \uXXXX */ memset(ubuf,0,UBLen); rc = sprintf(ubuf, "\\u%04x",ch); if( rc != 6 ) { rc = cson_rc.RangeError; break; } rc = f( state, ubuf, 6 ); continue; } } if( 0 == rc ) { rc = f(state, "\"", 1 ); } return rc; } } int cson_object_iter_init( cson_object const * obj, cson_object_iterator * iter ) { if( ! obj || !iter ) return cson_rc.ArgError; else { iter->obj = obj; iter->pos = 0; return 0; } } cson_kvp * cson_object_iter_next( cson_object_iterator * iter ) { if( ! iter || !iter->obj ) return NULL; else if( iter->pos >= iter->obj->kvp.count ) return NULL; else { cson_kvp * rc = iter->obj->kvp.list[iter->pos++]; while( (NULL==rc) && (iter->pos < iter->obj->kvp.count)) { rc = iter->obj->kvp.list[iter->pos++]; } return rc; } } static int cson_output_null( cson_data_dest_f f, void * state ) { if( !f ) return cson_rc.ArgError; else { return f(state, "null", 4); } } static int cson_output_bool( cson_value const * src, cson_data_dest_f f, void * state ) { if( !f ) return cson_rc.ArgError; else { char const v = cson_value_get_bool(src); return f(state, v ? "true" : "false", v ? 4 : 5); } } static int cson_output_integer( cson_value const * src, cson_data_dest_f f, void * state ) { if( !f ) return cson_rc.ArgError; else if( !cson_value_is_integer(src) ) return cson_rc.TypeError; else { enum { BufLen = 100 }; char b[BufLen]; int rc; memset( b, 0, BufLen ); rc = sprintf( b, "%"CSON_INT_T_PFMT, cson_value_get_integer(src) ) /* Reminder: snprintf() is C99 */ ; return ( rc<=0 ) ? cson_rc.RangeError : f( state, b, (unsigned int)rc ) ; } } static int cson_output_double( cson_value const * src, cson_data_dest_f f, void * state ) { if( !f ) return cson_rc.ArgError; else if( !cson_value_is_double(src) ) return cson_rc.TypeError; else { enum { BufLen = 128 /* this must be relatively large or huge doubles can cause us to overrun here, resulting in stack-smashing errors. */}; char b[BufLen]; int rc; memset( b, 0, BufLen ); rc = sprintf( b, "%"CSON_DOUBLE_T_PFMT, cson_value_get_double(src) ) /* Reminder: snprintf() is C99 */ ; if( rc<=0 ) return cson_rc.RangeError; else if(1) { /* Strip trailing zeroes before passing it on... */ unsigned int urc = (unsigned int)rc; char * pos = b + urc - 1; for( ; ('0' == *pos) && urc && (*(pos-1) != '.'); --pos, --urc ) { *pos = 0; } assert(urc && *pos); return f( state, b, urc ); } else { unsigned int urc = (unsigned int)rc; return f( state, b, urc ); } return 0; } } static int cson_output_string( cson_value const * src, char escapeFwdSlash, cson_data_dest_f f, void * state ) { if( !f ) return cson_rc.ArgError; else if( ! cson_value_is_string(src) ) return cson_rc.TypeError; else { cson_string const * str = cson_value_get_string(src); assert( NULL != str ); return cson_str_to_json(cson_string_cstr(str), str->length, escapeFwdSlash, f, state); } } /** Outputs indention spacing to f(). blanks: (0)=no indentation, (1)=1 TAB per/level, (>1)=n spaces/level depth is the current depth of the output tree, and determines how much indentation to generate. If blanks is 0 this is a no-op. Returns non-0 on error, and the error code will always come from f(). */ static int cson_output_indent( cson_data_dest_f f, void * state, unsigned char blanks, unsigned int depth ) { if( 0 == blanks ) return 0; else { #if 0 /* FIXME: stuff the indention into the buffer and make a single call to f(). */ enum { BufLen = 200 }; char buf[BufLen]; #endif unsigned int i; unsigned int x; char const ch = (1==blanks) ? '\t' : ' '; int rc = f(state, "\n", 1 ); for( i = 0; (i < depth) && (0 == rc); ++i ) { for( x = 0; (x < blanks) && (0 == rc); ++x ) { rc = f(state, &ch, 1); } } return rc; } } static int cson_output_array( cson_value const * src, cson_data_dest_f f, void * state, cson_output_opt const * fmt, unsigned int level ); static int cson_output_object( cson_value const * src, cson_data_dest_f f, void * state, cson_output_opt const * fmt, unsigned int level ); /** Main cson_output() implementation. Dispatches to a different impl depending on src->api->typeID. Returns 0 on success. */ static int cson_output_impl( cson_value const * src, cson_data_dest_f f, void * state, cson_output_opt const * fmt, unsigned int level ) { if( ! src || !f || !src->api ) return cson_rc.ArgError; else { int rc = 0; assert(fmt); switch( src->api->typeID ) { case CSON_TYPE_UNDEF: case CSON_TYPE_NULL: rc = cson_output_null(f, state); break; case CSON_TYPE_BOOL: rc = cson_output_bool(src, f, state); break; case CSON_TYPE_INTEGER: rc = cson_output_integer(src, f, state); break; case CSON_TYPE_DOUBLE: rc = cson_output_double(src, f, state); break; case CSON_TYPE_STRING: rc = cson_output_string(src, fmt->escapeForwardSlashes, f, state); break; case CSON_TYPE_ARRAY: rc = cson_output_array( src, f, state, fmt, level ); break; case CSON_TYPE_OBJECT: rc = cson_output_object( src, f, state, fmt, level ); break; default: rc = cson_rc.TypeError; break; } return rc; } } static int cson_output_array( cson_value const * src, cson_data_dest_f f, void * state, cson_output_opt const * fmt, unsigned int level ) { if( !src || !f || !fmt ) return cson_rc.ArgError; else if( ! cson_value_is_array(src) ) return cson_rc.TypeError; else if( level > fmt->maxDepth ) return cson_rc.RangeError; else { int rc; unsigned int i; cson_value const * v; char doIndent = fmt->indentation ? 1 : 0; cson_array const * ar = cson_value_get_array(src); assert( NULL != ar ); if( 0 == ar->list.count ) { return f(state, "[]", 2 ); } else if( (1 == ar->list.count) && !fmt->indentSingleMemberValues ) doIndent = 0; rc = f(state, "[", 1); ++level; if( doIndent ) { rc = cson_output_indent( f, state, fmt->indentation, level ); } for( i = 0; (i < ar->list.count) && (0 == rc); ++i ) { v = ar->list.list[i]; if( v ) { rc = cson_output_impl( v, f, state, fmt, level ); } else { rc = cson_output_null( f, state ); } if( 0 == rc ) { if(i < (ar->list.count-1)) { rc = f(state, ",", 1); if( 0 == rc ) { rc = doIndent ? cson_output_indent( f, state, fmt->indentation, level ) : f( state, " ", 1 ); } } } } --level; if( doIndent && (0 == rc) ) { rc = cson_output_indent( f, state, fmt->indentation, level ); } return (0 == rc) ? f(state, "]", 1) : rc; } } static int cson_output_object( cson_value const * src, cson_data_dest_f f, void * state, cson_output_opt const * fmt, unsigned int level ) { if( !src || !f || !fmt ) return cson_rc.ArgError; else if( ! cson_value_is_object(src) ) return cson_rc.TypeError; else if( level > fmt->maxDepth ) return cson_rc.RangeError; else { int rc; unsigned int i; cson_kvp const * kvp; char doIndent = fmt->indentation ? 1 : 0; cson_object const * obj = cson_value_get_object(src); assert( (NULL != obj) && (NULL != fmt)); if( 0 == obj->kvp.count ) { return f(state, "{}", 2 ); } else if( (1 == obj->kvp.count) && !fmt->indentSingleMemberValues ) doIndent = 0; rc = f(state, "{", 1); ++level; if( doIndent ) { rc = cson_output_indent( f, state, fmt->indentation, level ); } for( i = 0; (i < obj->kvp.count) && (0 == rc); ++i ) { kvp = obj->kvp.list[i]; if( kvp && kvp->key ) { rc = cson_str_to_json(cson_string_cstr(kvp->key), kvp->key->length, fmt->escapeForwardSlashes, f, state); if( 0 == rc ) { rc = fmt->addSpaceAfterColon ? f(state, ": ", 2 ) : f(state, ":", 1 ) ; } if( 0 == rc) { rc = ( kvp->value ) ? cson_output_impl( kvp->value, f, state, fmt, level ) : cson_output_null( f, state ); } } else { assert( 0 && "Possible internal error." ); continue /* internal error? */; } if( 0 == rc ) { if(i < (obj->kvp.count-1)) { rc = f(state, ",", 1); if( 0 == rc ) { rc = doIndent ? cson_output_indent( f, state, fmt->indentation, level ) : f( state, " ", 1 ); } } } } --level; if( doIndent && (0 == rc) ) { rc = cson_output_indent( f, state, fmt->indentation, level ); } return (0 == rc) ? f(state, "}", 1) : rc; } } int cson_output( cson_value const * src, cson_data_dest_f f, void * state, cson_output_opt const * fmt ) { int rc; if(! fmt ) fmt = &cson_output_opt_empty; rc = cson_output_impl(src, f, state, fmt, 0 ); if( (0 == rc) && fmt->addNewline ) { rc = f(state, "\n", 1); } return rc; } int cson_data_dest_FILE( void * state, void const * src, unsigned int n ) { if( ! state ) return cson_rc.ArgError; else if( !src || !n ) return 0; else { return ( 1 == fwrite( src, n, 1, (FILE*) state ) ) ? 0 : cson_rc.IOError; } } int cson_output_FILE( cson_value const * src, FILE * dest, cson_output_opt const * fmt ) { int rc = 0; if( fmt ) { rc = cson_output( src, cson_data_dest_FILE, dest, fmt ); } else { /* We normally want a newline on FILE output. */ cson_output_opt opt = cson_output_opt_empty; opt.addNewline = 1; rc = cson_output( src, cson_data_dest_FILE, dest, &opt ); } if( 0 == rc ) { fflush( dest ); } return rc; } int cson_output_filename( cson_value const * src, char const * dest, cson_output_opt const * fmt ) { if( !src || !dest ) return cson_rc.ArgError; else { FILE * f = fopen(dest,"wb"); if( !f ) return cson_rc.IOError; else { int const rc = cson_output_FILE( src, f, fmt ); fclose(f); return rc; } } } int cson_parse_filename( cson_value ** tgt, char const * src, cson_parse_opt const * opt, cson_parse_info * err ) { if( !src || !tgt ) return cson_rc.ArgError; else { FILE * f = fopen(src, "r"); if( !f ) return cson_rc.IOError; else { int const rc = cson_parse_FILE( tgt, f, opt, err ); fclose(f); return rc; } } } /** Internal type to hold state for a JSON input string. */ typedef struct cson_data_source_StringSource_ { /** Start of input string. */ char const * str; /** Current iteration position. Must initially be == str. */ char const * pos; /** Logical EOF, one-past-the-end of str. */ char const * end; } cson_data_source_StringSource_t; /** A cson_data_source_f() implementation which requires the state argument to be a properly populated (cson_data_source_StringSource_t*). */ static int cson_data_source_StringSource( void * state, void * dest, unsigned int * n ) { if( !state || !n || !dest ) return cson_rc.ArgError; else if( !*n ) return 0 /* ignore this */; else { unsigned int i; cson_data_source_StringSource_t * ss = (cson_data_source_StringSource_t*) state; unsigned char * tgt = (unsigned char *)dest; for( i = 0; (i < *n) && (ss->pos < ss->end); ++i, ++ss->pos, ++tgt ) { *tgt = *ss->pos; } *n = i; return 0; } } int cson_parse_string( cson_value ** tgt, char const * src, unsigned int len, cson_parse_opt const * opt, cson_parse_info * err ) { if( ! tgt || !src ) return cson_rc.ArgError; else if( !*src || (len<2/*2==len of {} and []*/) ) return cson_rc.RangeError; else { cson_data_source_StringSource_t ss; ss.str = ss.pos = src; ss.end = src + len; return cson_parse( tgt, cson_data_source_StringSource, &ss, opt, err ); } } int cson_parse_buffer( cson_value ** tgt, cson_buffer const * buf, cson_parse_opt const * opt, cson_parse_info * err ) { return ( !tgt || !buf || !buf->mem || !buf->used ) ? cson_rc.ArgError : cson_parse_string( tgt, (char const *)buf->mem, buf->used, opt, err ); } int cson_buffer_reserve( cson_buffer * buf, cson_size_t n ) { if( ! buf ) return cson_rc.ArgError; else if( 0 == n ) { cson_free(buf->mem, "cson_buffer::mem"); *buf = cson_buffer_empty; return 0; } else if( buf->capacity >= n ) { return 0; } else { unsigned char * x = (unsigned char *)realloc( buf->mem, n ); if( ! x ) return cson_rc.AllocError; memset( x + buf->used, 0, n - buf->used ); buf->mem = x; buf->capacity = n; ++buf->timesExpanded; return 0; } } cson_size_t cson_buffer_fill( cson_buffer * buf, char c ) { if( !buf || !buf->capacity || !buf->mem ) return 0; else { memset( buf->mem, c, buf->capacity ); return buf->capacity; } } /** cson_data_dest_f() implementation, used by cson_output_buffer(). arg MUST be a (cson_buffer*). This function appends n bytes at position arg->used, expanding the buffer as necessary. */ static int cson_data_dest_cson_buffer( void * arg, void const * data_, unsigned int n ) { if( ! arg || (n<0) ) return cson_rc.ArgError; else if( ! n ) return 0; else { cson_buffer * sb = (cson_buffer*)arg; char const * data = (char const *)data_; cson_size_t npos = sb->used + n; unsigned int i; if( npos >= sb->capacity ) { const cson_size_t oldCap = sb->capacity; const cson_size_t asz = npos * 2; if( asz < npos ) return cson_rc.ArgError; /* overflow */ else if( 0 != cson_buffer_reserve( sb, asz ) ) return cson_rc.AllocError; assert( (sb->capacity > oldCap) && "Internal error in memory buffer management!" ); /* make sure it gets NULL terminated. */ memset( sb->mem + oldCap, 0, (sb->capacity - oldCap) ); } for( i = 0; i < n; ++i, ++sb->used ) { sb->mem[sb->used] = data[i]; } return 0; } } int cson_output_buffer( cson_value const * v, cson_buffer * buf, cson_output_opt const * opt ) { int rc = cson_output( v, cson_data_dest_cson_buffer, buf, opt ); if( 0 == rc ) { /* Ensure that the buffer is null-terminated. */ rc = cson_buffer_reserve( buf, buf->used + 1 ); if( 0 == rc ) { buf->mem[buf->used] = 0; } } return rc; } /** @internal Tokenizes an input string on a given separator. Inputs are: - (inp) = is a pointer to the pointer to the start of the input. - (separator) = the separator character - (end) = a pointer to NULL. i.e. (*end == NULL) This function scans *inp for the given separator char or a NULL char. Successive separators at the start of *inp are skipped. The effect is that, when this function is called in a loop, all neighboring separators are ignored. e.g. the string "aa.bb...cc" will tokenize to the list (aa,bb,cc) if the separator is '.' and to (aa.,...cc) if the separator is 'b'. Returns 0 (false) if it finds no token, else non-0 (true). Output: - (*inp) will be set to the first character of the next token. - (*end) will point to the one-past-the-end point of the token. If (*inp == *end) then the end of the string has been reached without finding a token. Post-conditions: - (*end == *inp) if no token is found. - (*end > *inp) if a token is found. It is intolerant of NULL values for (inp, end), and will assert() in debug builds if passed NULL as either parameter. */ static char cson_next_token( char const ** inp, char separator, char const ** end ) { char const * pos = NULL; assert( inp && end && *inp ); if( *inp == *end ) return 0; pos = *inp; if( !*pos ) { *end = pos; return 0; } for( ; *pos && (*pos == separator); ++pos) { /* skip preceeding splitters */ } *inp = pos; for( ; *pos && (*pos != separator); ++pos) { /* find next splitter */ } *end = pos; return (pos > *inp) ? 1 : 0; } int cson_object_fetch_sub( cson_object const * obj, cson_value ** tgt, char const * path, char sep ) { if( ! obj || !path ) return cson_rc.ArgError; else if( !*path || !sep ) return cson_rc.RangeError; else { char const * beg = path; char const * end = NULL; int rc; unsigned int i, len; unsigned int tokenCount = 0; cson_value * cv = NULL; cson_object const * curObj = obj; enum { BufSize = 128 }; char buf[BufSize]; memset( buf, 0, BufSize ); rc = cson_rc.RangeError; while( cson_next_token( &beg, sep, &end ) ) { if( beg == end ) break; else { ++tokenCount; beg = end; end = NULL; } } if( 0 == tokenCount ) return cson_rc.RangeError; beg = path; end = NULL; for( i = 0; i < tokenCount; ++i, beg=end, end=NULL ) { rc = cson_next_token( &beg, sep, &end ); assert( 1 == rc ); assert( beg != end ); assert( end > beg ); len = end - beg; if( len > (BufSize-1) ) return cson_rc.RangeError; memset( buf, 0, len + 1 ); memcpy( buf, beg, len ); buf[len] = 0; cv = cson_object_get( curObj, buf ); if( NULL == cv ) return cson_rc.NotFoundError; else if( i == (tokenCount-1) ) { if(tgt) *tgt = cv; return 0; } else if( cson_value_is_object(cv) ) { curObj = cson_value_get_object(cv); assert((NULL != curObj) && "Detected mis-management of internal memory!"); } /* TODO: arrays. Requires numeric parsing for the index. */ else { return cson_rc.NotFoundError; } } assert( i == tokenCount ); return cson_rc.NotFoundError; } } cson_value * cson_object_get_sub( cson_object const * obj, char const * path, char sep ) { cson_value * v = NULL; cson_object_fetch_sub( obj, &v, path, sep ); return v; } static cson_value * cson_value_clone_array( cson_value const * orig ) { unsigned int i = 0; cson_array const * asrc = cson_value_get_array( orig ); unsigned int alen = cson_array_length_get( asrc ); cson_value * destV = NULL; cson_array * destA = NULL; assert( orig && asrc ); destV = cson_value_new_array(); if( NULL == destV ) return NULL; destA = cson_value_get_array( destV ); assert( destA ); if( 0 != cson_array_reserve( destA, alen ) ) { cson_value_free( destV ); return NULL; } for( ; i < alen; ++i ) { cson_value * ch = cson_array_get( asrc, i ); if( NULL != ch ) { cson_value * cl = cson_value_clone( ch ); if( NULL == cl ) { cson_value_free( destV ); return NULL; } if( 0 != cson_array_set( destA, i, cl ) ) { cson_value_free( cl ); cson_value_free( destV ); return NULL; } } } return destV; } static cson_value * cson_value_clone_object( cson_value const * orig ) { cson_object const * src = cson_value_get_object( orig ); cson_value * destV = NULL; cson_object * dest = NULL; cson_kvp const * kvp = NULL; cson_object_iterator iter = cson_object_iterator_empty; assert( orig && src ); if( 0 != cson_object_iter_init( src, &iter ) ) { cson_value_free( destV ); return NULL; } destV = cson_value_new_object(); if( NULL == destV ) return NULL; dest = cson_value_get_object( destV ); assert( dest ); while( (kvp = cson_object_iter_next( &iter )) ) { cson_string const * key = cson_kvp_key( kvp ); cson_value const * val = cson_kvp_value( kvp ); if( 0 != cson_object_set( dest, cson_string_cstr( key ), cson_value_clone( val ) ) ) { cson_value_free( destV ); return NULL; } } return destV; } cson_value * cson_value_clone( cson_value const * orig ) { if( NULL == orig ) return NULL; else { switch( orig->api->typeID ) { case CSON_TYPE_UNDEF: return cson_value_new(); case CSON_TYPE_NULL: return cson_value_null(); case CSON_TYPE_BOOL: return cson_value_new_bool( cson_value_get_bool( orig ) ); case CSON_TYPE_INTEGER: return cson_value_new_integer( cson_value_get_integer( orig ) ); break; case CSON_TYPE_DOUBLE: return cson_value_new_double( cson_value_get_double( orig ) ); break; case CSON_TYPE_STRING: { cson_string const * str = cson_value_get_string( orig ); return cson_value_new_string( cson_string_cstr( str ), cson_string_length_bytes( str ) ); } case CSON_TYPE_ARRAY: return cson_value_clone_array( orig ); case CSON_TYPE_OBJECT: return cson_value_clone_object( orig ); } assert( 0 && "We can't get this far." ); return NULL; } } #if 0 /* i'm not happy with this... */ char * cson_pod_to_string( cson_value const * orig ) { if( ! orig ) return NULL; else { enum { BufSize = 64 }; char * v = NULL; switch( orig->api->typeID ) { case CSON_TYPE_BOOL: { char const bv = cson_value_get_bool(orig); v = cson_strdup( bv ? "true" : "false", bv ? 4 : 5 ); break; } case CSON_TYPE_UNDEF: case CSON_TYPE_NULL: { v = cson_strdup( "null", 4 ); break; } case CSON_TYPE_STRING: { cson_string const * jstr = cson_value_get_string(orig); unsigned const int slen = cson_string_length_bytes( jstr ); assert( NULL != jstr ); v = cson_strdup( cson_string_cstr( jstr ), slen ); break; } case CSON_TYPE_INTEGER: { char buf[BufSize] = {0}; if( 0 < sprintf( v, "%"CSON_INT_T_PFMT, cson_value_get_integer(orig)) ) { v = cson_strdup( buf, strlen(buf) ); } break; } case CSON_TYPE_DOUBLE: { char buf[BufSize] = {0}; if( 0 < sprintf( v, "%"CSON_DOUBLE_T_PFMT, cson_value_get_double(orig)) ) { v = cson_strdup( buf, strlen(buf) ); } break; } default: break; } return v; } } #endif #if 0 /* i'm not happy with this... */ char * cson_pod_to_string( cson_value const * orig ) { if( ! orig ) return NULL; else { enum { BufSize = 64 }; char * v = NULL; switch( orig->api->typeID ) { case CSON_TYPE_BOOL: { char const bv = cson_value_get_bool(orig); v = cson_strdup( bv ? "true" : "false", bv ? 4 : 5 ); break; } case CSON_TYPE_UNDEF: case CSON_TYPE_NULL: { v = cson_strdup( "null", 4 ); break; } case CSON_TYPE_STRING: { cson_string const * jstr = cson_value_get_string(orig); unsigned const int slen = cson_string_length_bytes( jstr ); assert( NULL != jstr ); v = cson_strdup( cson_string_cstr( jstr ), slen ); break; } case CSON_TYPE_INTEGER: { char buf[BufSize] = {0}; if( 0 < sprintf( v, "%"CSON_INT_T_PFMT, cson_value_get_integer(orig)) ) { v = cson_strdup( buf, strlen(buf) ); } break; } case CSON_TYPE_DOUBLE: { char buf[BufSize] = {0}; if( 0 < sprintf( v, "%"CSON_DOUBLE_T_PFMT, cson_value_get_double(orig)) ) { v = cson_strdup( buf, strlen(buf) ); } break; } default: break; } return v; } } #endif #if defined(__cplusplus) } /*extern "C"*/ #endif #undef MARKER #undef CSON_OBJECT_PROPS_SORT #undef CSON_OBJECT_PROPS_SORT_USE_LENGTH /* end file ./cson.c */ /* begin file ./cson_lists.h */ /* Auto-generated from cson_list.h. Edit at your own risk! */ unsigned int cson_value_list_reserve( cson_value_list * self, unsigned int n ) { if( !self ) return 0; else if(0 == n) { if(0 == self->alloced) return 0; cson_free(self->list, "cson_value_list_reserve"); self->list = NULL; self->alloced = self->count = 0; return 0; } else if( self->alloced >= n ) { return self->alloced; } else { size_t const sz = sizeof(cson_value *) * n; cson_value * * m = (cson_value **)cson_realloc( self->list, sz, "cson_value_list_reserve" ); if( ! m ) return self->alloced; memset( m + self->alloced, 0, (sizeof(cson_value *)*(n-self->alloced))); self->alloced = n; self->list = m; return n; } } int cson_value_list_append( cson_value_list * self, cson_value * cp ) { if( !self || !cp ) return cson_rc.ArgError; else if( self->alloced > cson_value_list_reserve(self, self->count+1) ) { return cson_rc.AllocError; } else { self->list[self->count++] = cp; return 0; } } int cson_value_list_visit( cson_value_list * self, int (*visitor)(cson_value * obj, void * visitorState ), void * visitorState ) { int rc = cson_rc.ArgError; if( self && visitor ) { unsigned int i = 0; for( rc = 0; (i < self->count) && (0 == rc); ++i ) { cson_value * obj = self->list[i]; if(obj) rc = visitor( obj, visitorState ); } } return rc; } void cson_value_list_clean( cson_value_list * self, void (*cleaner)(cson_value * obj) ) { if( self && cleaner && self->count ) { unsigned int i = 0; for( ; i < self->count; ++i ) { cson_value * obj = self->list[i]; if(obj) cleaner(obj); } } cson_value_list_reserve(self,0); } unsigned int cson_kvp_list_reserve( cson_kvp_list * self, unsigned int n ) { if( !self ) return 0; else if(0 == n) { if(0 == self->alloced) return 0; cson_free(self->list, "cson_kvp_list_reserve"); self->list = NULL; self->alloced = self->count = 0; return 0; } else if( self->alloced >= n ) { return self->alloced; } else { size_t const sz = sizeof(cson_kvp *) * n; cson_kvp * * m = (cson_kvp **)cson_realloc( self->list, sz, "cson_kvp_list_reserve" ); if( ! m ) return self->alloced; memset( m + self->alloced, 0, (sizeof(cson_kvp *)*(n-self->alloced))); self->alloced = n; self->list = m; return n; } } int cson_kvp_list_append( cson_kvp_list * self, cson_kvp * cp ) { if( !self || !cp ) return cson_rc.ArgError; else if( self->alloced > cson_kvp_list_reserve(self, self->count+1) ) { return cson_rc.AllocError; } else { self->list[self->count++] = cp; return 0; } } int cson_kvp_list_visit( cson_kvp_list * self, int (*visitor)(cson_kvp * obj, void * visitorState ), void * visitorState ) { int rc = cson_rc.ArgError; if( self && visitor ) { unsigned int i = 0; for( rc = 0; (i < self->count) && (0 == rc); ++i ) { cson_kvp * obj = self->list[i]; if(obj) rc = visitor( obj, visitorState ); } } return rc; } void cson_kvp_list_clean( cson_kvp_list * self, void (*cleaner)(cson_kvp * obj) ) { if( self && cleaner && self->count ) { unsigned int i = 0; for( ; i < self->count; ++i ) { cson_kvp * obj = self->list[i]; if(obj) cleaner(obj); } } cson_kvp_list_reserve(self,0); } /* end file ./cson_lists.h */ /* begin file ./cson_session.c */ #include <string.h> /* strlen() */ #include <stdlib.h> /* memcpy() */ #include <assert.h> /** Maximum name length for cson_sessmgr_register(), including the trailing NUL. */ enum { CsonSessionNameLen = 32 }; typedef struct cson_sessmgr_reg cson_sessmgr_reg; /** Holds name-to-factory mappings for cson_sessmgr implementations. */ struct cson_sessmgr_reg { char name[CsonSessionNameLen]; cson_sessmgr_factory_f factory; }; #if !CSON_ENABLE_CPDO int cson_sessmgr_cpdo( cson_sessmgr ** tgt, cson_object const * opt ) { return cson_rc.UnsupportedError; } #endif #if !CSON_ENABLE_WHIO int cson_sessmgr_whio_ht( cson_sessmgr ** tgt, cson_object const * opt ) { return cson_rc.UnsupportedError; } int cson_sessmgr_whio_epfs( cson_sessmgr ** tgt, cson_object const * opt ) { return cson_rc.UnsupportedError; } #endif /** Holds the list of registered cson_sessmgr implementations. Used by cson_sessmgr_register(), cson_sessmgr_load(), and cson_sessmgr_names(). Maintenance reminder: the API docs promise that at least 10 slots are initially available. */ static cson_sessmgr_reg CsonSessionReg[] = { {{'f','i','l','e',0},cson_sessmgr_file}, #if CSON_ENABLE_CPDO {{'c','p','d','o',0},cson_sessmgr_cpdo}, #endif #if CSON_ENABLE_WHIO {{'w','h','i','o','_','h','t',0},cson_sessmgr_whio_ht}, {{'w','h','i','o','_','e','p','f','s',0},cson_sessmgr_whio_epfs}, #endif #define REG {{0},NULL} REG,REG,REG,REG,REG, REG,REG,REG,REG,REG #undef REG }; static const unsigned int CsonSessionRegLen = sizeof(CsonSessionReg)/sizeof(CsonSessionReg[0]); int cson_sessmgr_register( char const * name, cson_sessmgr_factory_f f ) { if( ! name || !*name || !f ) return cson_rc.ArgError; else { cson_sessmgr_reg * r = CsonSessionReg; unsigned int nlen = strlen(name); unsigned int i = 0; if( nlen >= CsonSessionNameLen ) return cson_rc.RangeError; for( ; i < CsonSessionRegLen; ++i, ++r ) { if( r->name[0] ) continue; memcpy( r->name, name, nlen ); r->name[nlen] = 0; r->factory = f; return 0; } return cson_rc.RangeError; } } int cson_sessmgr_load( char const * name, cson_sessmgr ** tgt, cson_object const * opt ) { if( ! name || !*name || !tgt ) return cson_rc.ArgError; else { cson_sessmgr_reg const * r = CsonSessionReg; unsigned int i = 0; for( ; i < CsonSessionRegLen; ++i, ++r ) { if( ! r->name[0] ) break /* end of list */; else if( 0 != strcmp( r->name, name ) ) continue; else { assert( NULL != r->factory ); return r->factory( tgt, opt ); } } return cson_rc.UnsupportedError; } } char const * const * cson_sessmgr_names() { static char const * names[sizeof(CsonSessionReg)/sizeof(CsonSessionReg[0])+1]; unsigned int i = 0; cson_sessmgr_reg const * r = CsonSessionReg; for( ; i < CsonSessionRegLen; ++i, ++r ) { /* pedantic threading note: as long as this function is not used concurrently with cson_sessmgr_register(), the worst we will do here if this function is called, or its results used, concurrently is overwrite in-use values with the same values. */ names[i] = r->name[0] ? r->name : NULL; } names[i] = NULL; return names; } /* end file ./cson_session.c */ /* begin file ./cson_session_file.c */ #if !defined(_WIN32) # if !defined(_POSIX_VERSION) # define _POSIX_VERSION 200112L /* chmod(), unlink() */ # endif # define ENABLE_POSIX_FILE_OPS 1 #else # define ENABLE_POSIX_FILE_OPS 0 #endif #include <stdlib.h> #include <string.h> #include <assert.h> #if ENABLE_POSIX_FILE_OPS # include <unistd.h> /* unlink() */ # include <sys/stat.h> /* chmod() */ #endif static int cson_session_file_load( cson_sessmgr * self, cson_value ** tgt, char const * id ); static int cson_session_file_save( cson_sessmgr * self, cson_value const * root, char const * id ); static int cson_session_file_remove( cson_sessmgr * self, char const * id ); static void cson_session_file_finalize( cson_sessmgr * self ); static const cson_sessmgr_api cson_sessmgr_api_file = { cson_session_file_load, cson_session_file_save, cson_session_file_remove, cson_session_file_finalize }; typedef struct cson_sessmgr_file_impl cson_sessmgr_file_impl; struct cson_sessmgr_file_impl { char * dir; char * prefix; char * suffix; }; static const cson_sessmgr cson_sessmgr_file_empty = { &cson_sessmgr_api_file, NULL }; static char * cson_session_file_strdup( char const * src ) { size_t const n = src ? strlen(src) : 0; char * rc = src ? (char *)calloc(1, n+1) : NULL; if( ! rc ) return NULL; memcpy( rc, src, n ); return rc; } /* Helper macro for varios cson_sessmgr_api member implementations. */ #define IMPL_DECL(RC) \ cson_sessmgr_file_impl * impl = (self && (self->api == &cson_sessmgr_api_file)) \ ? (cson_sessmgr_file_impl*)self->impl \ : NULL; \ if( NULL == impl ) return RC static int cson_session_file_name( cson_sessmgr_file_impl * impl, char const * id, char * buf, unsigned int bufLen ) { char const * dir = impl->dir ? impl->dir : "."; char const * pre = impl->prefix ? impl->prefix : ""; char const * suf = impl->suffix ? impl->suffix : ""; char * pos = NULL /* current write possition. */; unsigned int flen = 0 /* length of the next token. */; unsigned int olen = 0 /* total number of bytes written so far. */; if( ! id || !*id ) return cson_rc.ArgError; #define CHECKLEN if(olen >= bufLen) return cson_rc.RangeError; assert( pos < (buf+bufLen) ) pos = buf; #define PUSH(FIELD) \ flen = strlen(FIELD); \ olen += flen; \ CHECKLEN; \ strncpy( pos, FIELD, flen ); \ pos += flen PUSH(dir); ++olen; CHECKLEN; #if defined(_WIN32) *(pos++) = '\\'; #else *(pos++) = '/'; #endif PUSH(pre); PUSH(id); PUSH(suf); if( pos >= (buf + bufLen) ) return cson_rc.RangeError; *pos = 0; return 0; #undef PUSH #undef CHECKLEN } static int cson_session_file_load( cson_sessmgr * self, cson_value ** root, char const * id ) { enum { BufSize = 1024 }; char fname[BufSize]; FILE * fh = NULL; int rc; IMPL_DECL(cson_rc.ArgError); if( !root || !id || !*id ) return cson_rc.ArgError; memset( fname, 0, BufSize ); rc = cson_session_file_name( impl, id, fname, BufSize ); if( 0 != rc ) return rc; fh = fopen( fname, "r" ); if( ! fh ) return cson_rc.IOError; rc = cson_parse_FILE( root, fh, NULL, NULL ); fclose( fh ); return rc; } static int cson_session_file_save( cson_sessmgr * self, cson_value const * root, char const * id ) { enum { BufSize = 1024 }; char fname[BufSize]; FILE * fh = NULL; int rc; IMPL_DECL(cson_rc.ArgError); if( !root || !id || !*id ) return cson_rc.ArgError; memset( fname, 0, BufSize ); rc = cson_session_file_name( impl, id, fname, BufSize ); if( 0 != rc ) return rc; fh = fopen( fname, "w" ); if( ! fh ) return cson_rc.IOError; #if ENABLE_POSIX_FILE_OPS chmod( fname, 0600 ); #endif rc = cson_output_FILE( root, fh, NULL ); fclose( fh ); #if ENABLE_POSIX_FILE_OPS if( rc ) { unlink( fname ); } #endif return rc; } void cson_session_file_finalize( cson_sessmgr * self ) { if( self && (self->api == &cson_sessmgr_api_file) ) { cson_sessmgr_file_impl * impl = (cson_sessmgr_file_impl *)self->impl; free( impl->dir ); free( impl->prefix ); free( impl->suffix ); free( impl ); *self = cson_sessmgr_file_empty; free( self ); } } static int cson_session_file_remove( cson_sessmgr * self, char const * id ) { enum { BufSize = 1024 }; char fname[BufSize]; int rc; IMPL_DECL(cson_rc.ArgError); if( !id || !*id ) return cson_rc.ArgError; memset( fname, 0, BufSize ); rc = cson_session_file_name( impl, id, fname, BufSize ); if( 0 != rc ) return rc; #if ENABLE_POSIX_FILE_OPS rc = unlink( fname ); #else # error "unlink not implemented for this platform." #endif return (0==rc) ? 0 : cson_rc.IOError; } int cson_sessmgr_file( cson_sessmgr ** tgt, cson_object const * opt ) { int rc; cson_sessmgr * m = tgt ? (cson_sessmgr *)malloc(sizeof(cson_sessmgr)) : NULL; cson_sessmgr_file_impl * impl = m ? (cson_sessmgr_file_impl *)malloc(sizeof(cson_sessmgr_file_impl)) : NULL; if( ! m ) return tgt ? cson_rc.AllocError : cson_rc.ArgError; else if( ! impl ) { free(m); return cson_rc.AllocError; } *m = cson_sessmgr_file_empty; m->impl = impl; if( opt ) { cson_string const * jstr; #define CP(KEY) \ jstr = cson_value_get_string( cson_object_get( opt, # KEY ) ); \ if( jstr ) { \ impl->KEY = cson_session_file_strdup( cson_string_cstr( jstr ) ); \ if( ! impl->KEY ) { \ rc = cson_rc.AllocError; \ goto error_clean; \ } \ } (void)0 CP(dir); CP(prefix); CP(suffix); #undef CP } #define CP(KEY,VAL) if( ! impl->KEY ) { \ impl->KEY = cson_session_file_strdup(VAL); \ if( ! impl->KEY ) { \ rc = cson_rc.AllocError; \ goto error_clean; \ } \ } (void)0 #if ENABLE_POSIX_FILE_OPS CP(dir,"/tmp"); #else CP(dir,"."); #endif CP(prefix,"cson-session-"); CP(suffix,".json"); #undef CP *tgt = m; return 0; error_clean: m->api->finalize( m ); return rc; } #undef IMPL_DECL #undef ENABLE_POSIX_FILE_OPS /* end file ./cson_session_file.c */ /* begin file ./cson_sqlite3.c */ /** @file cson_sqlite3.c This file contains the implementation code for the cson sqlite3-to-JSON API. License: the same as the cson core library. Author: Stephan Beal (http://wanderinghorse.net/home/stephan) */ #if CSON_ENABLE_SQLITE3 /* we do this here for the sake of the amalgamation build */ #include <assert.h> #include <string.h> /* strlen() */ #if 0 #include <stdio.h> #define MARKER if(1) printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); if(1) printf #else #define MARKER if(0) printf #endif #if defined(__cplusplus) extern "C" { #endif static cson_value * cson_sqlite3_stmt_to_value( sqlite3_stmt * st, int col ) { if( ! st ) return NULL; else { #if 0 sqlite3_value * val = sqlite3_column_type(st,col); int const vtype = val ? sqlite3_value_type(val) : -1; if( ! val ) return cson_value_null(); #else int const vtype = sqlite3_column_type(st,col); #endif switch( vtype ) { case SQLITE_NULL: return cson_value_null(); case SQLITE_INTEGER: { return cson_value_new_integer( (cson_int_t) sqlite3_column_int64(st, col) ); } case SQLITE_FLOAT: return cson_value_new_double( sqlite3_column_double(st, col) ); case SQLITE_BLOB: /* arguably fall through... */ case SQLITE_TEXT: { char const * str = (char const *)sqlite3_column_text(st,col); return cson_value_new_string(str, str ? strlen(str) : 0); } default: return NULL; } } } /** st must be a valid prepared statement. This function creates a JSON array containing its columns, in order. Returns a new array value on success, which the caller owns. On error NULL is returned. st is not traversed or freed by this function - only the column count and names are read. */ static cson_value * cson_sqlite3_stmt_cols( sqlite3_stmt * st ) { cson_value * aryV = NULL; cson_array * ary = NULL; char const * colName = NULL; int i = 0; int rc = 0; int colCount = 0; assert(st); colCount = sqlite3_column_count(st); if( colCount <= 0 ) return NULL; aryV = cson_value_new_array(); if( ! aryV ) return NULL; ary = cson_value_get_array(aryV); assert(ary); for( i = 0; (0 ==rc) && (i < colCount); ++i ) { colName = sqlite3_column_name( st, i ); if( ! colName ) rc = cson_rc.AllocError; else { rc = cson_array_set( ary, (unsigned int)i, cson_value_new_string(colName, strlen(colName)) ); } } if( 0 == rc ) return aryV; else { cson_value_free(aryV); return NULL; } } /** Internal impl of cson_sqlite3_stmt_to_json() when the 'fat' parameter is non-0. */ static int cson_sqlite3_stmt_to_json_fat( sqlite3_stmt * st, cson_value ** tgt ) { #define RETURN(RC) { if(rootV) cson_value_free(rootV); return RC; } if( ! tgt || !st ) return cson_rc.ArgError; else { cson_value * rootV = NULL; cson_object * root = NULL; cson_value * colsV = NULL; cson_value * rowsV = NULL; cson_array * rows = NULL; cson_value * objV = NULL; cson_object * obj = NULL; cson_value * currentValue = NULL; char const * colName = NULL; int rc = 0; int i = 0; int const colCount = sqlite3_column_count(st); if( colCount <= 0 ) return cson_rc.ArgError; rootV = cson_value_new_object(); if( ! rootV ) return cson_rc.AllocError; colsV = cson_sqlite3_stmt_cols(st); if( ! colsV ) { cson_value_free( rootV ); RETURN(cson_rc.AllocError); } root = cson_value_get_object(rootV); rc = cson_object_set( root, "columns", colsV ); if( rc ) { cson_value_free( colsV ); RETURN(rc); } colsV = NULL; rowsV = cson_value_new_array(); if( ! rowsV ) RETURN(cson_rc.AllocError); rc = cson_object_set( root, "rows", rowsV ); if( rc ) { cson_value_free( rowsV ); RETURN(rc); } rows = cson_value_get_array(rowsV); assert(rows); while( SQLITE_ROW == sqlite3_step(st) ) { objV = cson_value_new_object(); if( ! objV ) RETURN(cson_rc.AllocError); rc = cson_array_append( rows, objV ); if( rc ) { cson_value_free( objV ); RETURN(rc); } obj = cson_value_get_object(objV); for( i = 0; i < colCount; ++i ) { colName = sqlite3_column_name( st, i ); if( ! colName ) RETURN(cson_rc.AllocError); currentValue = cson_sqlite3_stmt_to_value(st,i); if( ! currentValue ) currentValue = cson_value_null(); rc = cson_object_set( obj, colName, currentValue ); if( 0 != rc ) { cson_value_free( currentValue ); RETURN(rc); } } } *tgt = rootV; return 0; } #undef RETURN } /** Internal impl of cson_sqlite3_stmt_to_json() when the 'fat' parameter is 0. */ static int cson_sqlite3_stmt_to_json_slim( sqlite3_stmt * st, cson_value ** tgt ) { #define RETURN(RC) { if(rootV) cson_value_free(rootV); return RC; } if( ! tgt || !st ) return cson_rc.ArgError; else { cson_value * rootV = NULL; cson_object * root = NULL; cson_value * aryV = NULL; cson_array * ary = NULL; cson_value * rowsV = NULL; cson_array * rows = NULL; cson_value * colV = NULL; int rc = 0; int i = 0; int const colCount = sqlite3_column_count(st); if( colCount <= 0 ) return cson_rc.ArgError; rootV = cson_value_new_object(); if( ! rootV ) return cson_rc.AllocError; aryV = cson_sqlite3_stmt_cols(st); if( ! aryV ) { cson_value_free( rootV ); RETURN(cson_rc.AllocError); } root = cson_value_get_object(rootV); rc = cson_object_set( root, "columns", aryV ); if( rc ) { cson_value_free( aryV ); RETURN(rc); } aryV = NULL; ary = NULL; rowsV = cson_value_new_array(); if( ! rowsV ) RETURN(cson_rc.AllocError); rc = cson_object_set( root, "rows", rowsV ); if( 0 != rc ) { cson_value_free( rowsV ); RETURN(rc); } rows = cson_value_get_array(rowsV); assert(rows); while( SQLITE_ROW == sqlite3_step(st) ) { aryV = cson_value_new_array(); if( ! aryV ) RETURN(cson_rc.AllocError); rc = cson_array_append( rows, aryV ); if( 0 != rc ) { cson_value_free( aryV ); RETURN(rc); } ary = cson_value_get_array(aryV); rc = cson_array_reserve(ary, (unsigned int) colCount ); if( 0 != rc ) RETURN(rc); for( i = 0; i < colCount; ++i ) { colV = cson_sqlite3_stmt_to_value(st,i); if( ! colV ) colV = cson_value_null(); rc = cson_array_set( ary, i, colV ); if( 0 != rc ) { cson_value_free( colV ); RETURN(rc); } } } *tgt = rootV; return 0; } #undef RETURN } int cson_sqlite3_stmt_to_json( sqlite3_stmt * st, cson_value ** tgt, char fat ) { return fat ? cson_sqlite3_stmt_to_json_fat(st,tgt) : cson_sqlite3_stmt_to_json_slim(st,tgt) ; } int cson_sqlite3_sql_to_json( sqlite3 * db, cson_value ** tgt, char const * sql, char fat ) { if( !db || !tgt || !sql || !*sql ) return cson_rc.ArgError; else { sqlite3_stmt * st = NULL; int rc = sqlite3_prepare_v2( db, sql, -1, &st, NULL ); if( 0 != rc ) return cson_rc.IOError /* FIXME: Better error code? */; rc = cson_sqlite3_stmt_to_json( st, tgt, fat ); sqlite3_finalize( st ); return rc; } } #if defined(__cplusplus) } /*extern "C"*/ #endif #undef MARKER #endif /* CSON_ENABLE_SQLITE3 */ /* end file ./cson_sqlite3.c */ /* begin file cgi/whuuid.h */ #if !defined(WANDERGINHORSE_NET_WHUUID_H_INCLUDED) #define WANDERGINHORSE_NET_WHUUID_H_INCLUDED 1 #include <stdio.h> /* only for decl of FILE. */ /************************************************************************ An experiment in creating random UUIDs (http://wikipedia.org/wiki/Uuid). Author: Stephan Beal (http://wanderinghorse.net/home/stephan/) License: Public Domain Features: - Small API. Only two relevant classes and a handful of functions. - Uses a client-specified RNG source. Two are provided with the library. The RNG source may be arbitrarily stateful, and each may have instance-specific data. - State objects have a uniform cleanup interface, but each implementation defines which cleanup behaviours need to be performed (e.g. closing an input file). - Fairly fast, assuming your RNG is. (My 2.6GHz PC can generate, and send them to stdout, just over 1.3 million UUIDs per second.) Misfeatures: - Does not support a specific version of UUID, as detailed at [http://wikipedia.org/wiki/Uuid]. Its UUIDs have random data in all positions, as opposed to reserving certain positions for specific values or using specified algorithms to generate the values. Thus the UUIDs it generates are similar to Version 4 UUIDs except that no bytes are reserved for specific values. PS: i don't really consider that to be a mis-feature. IMHO UUIDs should be completely random, with no reserved bytes. ------------------------------------------------------------------------ TIP: checking for duplicate UUIDs The sqlite3 tool can be used for checking for duplicate UUIDs. Simply print the UUIDs, one per line, and feed them into sqlite3 like so: @code sqlite3> create table ids (id,unide(id)); sqlite3> .import myUUIDListFile ids @endcode If sqlite3 does not complain, there were no duplicates. You can also test by sorting the list, removing duplicates, and checking the length of the list. e.g. assume we have a file named "1m" containing 1 million UUIDs. From a Unix shell we could do: @code ~> sort -u < 1m > 1ms ~> ls -la 1m 1ms @endcode If the files have the same size then there were no duplicates. In my tests i have not encountered duplicates except when testing a deterministic RNG with a specific seed. ************************************************************************/ /** @def WHUUID_CONFIG_KEEP_METRICS If WHUUID_CONFIG_KEEP_METRICS is a true value then the library keeps track of how many times a given hex digit value is generated by the whuuid_rng class. It has a minimal performance hit, but if the data will never be used then it can be turned off. */ #define WHUUID_CONFIG_KEEP_METRICS 1 /** @enum whuuid_constants A list of constant values used by the whuuid API. */ enum whuuid_constants { /** The length of a UUID canonical-form string, not including a trailing NULL bytes. e.g.: 00000000-0000-0000-0000-000000000000 */ whuuid_length_canonical = 36, /** The length of a UUID in canonical form, including a trailing NULL byte. */ whuuid_length_cstring = whuuid_length_canonical + 1, /** The number of bytes of data necessary to store a UUID in "raw" form. */ whuuid_length_bytes = 16 }; /** Represents a single UUID. */ struct whuuid_t { unsigned char bytes[whuuid_length_bytes]; }; typedef struct whuuid_t whuuid_t; /** A zero-initialized whuiid_t initialization object. */ extern const whuuid_t whuuid_t_empty; /** A class holding RNG information. Each instance manages a single RNG source, which is used to populate any number of whuiid_t objects with random data. They may or may not need to dynamically allocate resources (e.g. open a file containing random data), depending on the implementation. They should normally be initialized via factory functions, and those functions should: a) Allocate any private resources the object needs and store them in self->impl. b) Set the cleanup() member function to a function which knows how to clean up any resources stored in self->impl. c) Set the rand() member to a function which knows how to use the private state to generate random data. The most basic usage looks something like this: @code whuuid_rng st = whuuid_rng_lcrng; // a Linear Congruent RNG whuuid_t u = whuuid_t_empty; char buffer[whuuid_length_canonical+1]; // buffer for UUID string buffer[whuuid_length_canonical] = 0; // add trailing NULL for( int i =0; i < 100; ++i ) {// generate 100 UUIDs to print them whuuid_fill_rand( &u, &st ); // generate UUID using st->rand() whuuid_to_string( &u, buffer ); puts(buffer); } st.cleanup(&st); // see below. @endcode In that particular case the state object has no state which needs cleaning, but we could also set up a FILE as an input source, in which case we need to clean up the object: @code st = whuuid_rng_FILE; st.impl = fopen("/dev/urandom", "r"); ... use st ... st.cleanup(&st); // will fclose() the file @endcode If a state object is dynamically allocated then it should be freed after calling its cleanup() member to free any implementation-specific resources. */ struct whuuid_rng { /** Must set *tgt to sizeof(unsigned int) random bytes. Must return 0 on success or non-zero if something goes wrong (e.g. the input source has failed or run out of numbers). How it uses (or ignores) the self argument is implementation-specific. */ int (*rand)( struct whuuid_rng * self, unsigned int * tgt ); /** Must clean up self, but not free self itself. How it does this is implementation-specific. If it has no private state, this function may be NULL. whuuid_rng objects can be allocated on the stack or via arbitrary mechanisms, so the cleanup routine must not free the self object. How it is freed (after it is cleaned up) depends on how it was allocated. */ void (*cleanup)( struct whuuid_rng * self ); /** Implementations may store any private state here. This member is not for public use. */ void * impl; /** Stores the distribution of values created by this state object. whuuid_fill_rand() updates these values. */ unsigned long distribution[whuuid_length_bytes]; }; /** Convenience typedef. */ typedef struct whuuid_rng whuuid_rng; /** A zero-initialized whuiid_state initialization object. */ extern const whuuid_rng whuuid_rng_empty; /** An almost-empty whuiid_state initialization object with its rand() member set to whuuid_lc_rand. */ extern const whuuid_rng whuuid_rng_lcrng; /** A whuuid_state initialization object with its rand() member set to whuuid_FILE_rand and its cleanup() member set to whuuid_FILE_cleanup. Clients may copy this then set the impl member to point it to an opened FILE handle. The FILE handle will be closed when the cleanup() member is called. If the state object should not close the file when it cleans up, set the cleanup() member to NULL. */ extern const whuuid_rng whuuid_rng_FILE; /** Implements the whuuid_rng::rand() interface. This implementaion uses/abuses st->impl to store a numeric state value for a linear congruent RNG. If st->impl is NULL then a seed value is generated using some external source (we malloc() a few bytes to get a random address, and we use that address as a seed). The state value is stored directly in st->impl and does not need to be cleaned up. (The memory malloc()ed to get the initial seed is free()d immediately after it is malloc()ed.) Returns 0 on success, non-zero on error. The only error conditions are !st or !tgt. A malloc() error on the initial seeding will not cause an error (but causes a determinate (but unspecified) seed value to be used). In my (informal/unscientific) tests, this RNG works very well for generating UUIDs, out-performing /dev/urandom in terms of even numeric distribution most of the time. */ int whuuid_lc_rand( whuuid_rng * st, unsigned int *tgt ); /** Implements the whuuid_rng::rand() interface. If st->impl is not NULL it is assumed to be-a (FILE*) and sizeof(unsigned int) bytes are read from it and returned via the tgt argument. Returns non-zero if !st or !st->impl, or if reading from the file fails. Results are undefined if st->impl is non-null but is-not-a FILE. Note that this implementation does nothing fancy like buffering some larger amount of random input. Each call reads sizeof(int) bytes. If performance is of a concern, create an implementation which stores a struct containing the FILE and the buffer somewhere in st->impl and reads the input in larger blocks. Also implement a cleanup function which can free the buffer. @see whuuid_FILE_cleanup() @see whuuid_rng_FILE */ int whuuid_FILE_rand( whuuid_rng * st, unsigned int * tgt ); /** Implements the whuuid_rng::cleanup() interface for state objects where obj->impl is-a FILE handle opened via fopen() (or equivalent). Assumes self->impl is-a (FILE*) and calls fclose() on it. */ void whuuid_FILE_cleanup( whuuid_rng * self ); /** Converts src->bytes to a canonical-form UUID string. dest must be valid memory at least whuuid_length_canonical bytes long, and on success exactly whuuid_length_canonical bytes will be written to it. No terminating null is added. Returns 0 on success, non-zero on error. The only error conditions are (!src) or (!dest). */ int whuuid_to_string( whuuid_t const * src, char * dest ); /** Populates all of dest->bytes, using st->rand() to collect the random bytes. It calls st->rand() enough times to collect whuuid_length_bytes bytes. Returns 0 on success, non-0 on error. The error conditions are: - !st or !dest - st->rand() returns non-0, in which case that error code is passed back to the caller. st->distribution is modified by this function to record the number of times any given digit (hex 0..f) is generated via a call to rand() (but note that each call to st->rand() is used to generate (sizeof(unsigning int)*2) digits). This routine does not guaranty that the bytes returned by st->rand() are used in the exact same order as they are returned. */ int whuuid_fill_rand( whuuid_t * dest, whuuid_rng * st ); /** Copies whuuid_length_bytes bytes from src to dest->bytes. Returns 0 on success. The only error cases are !dest or !src. */ int whuuid_fill( whuuid_t * dest, unsigned char const * src ); /** Compares lhs->bytes and rhs->bytes and returns 0, less than 0, or greater than 0 depending on whether lhs equals, is less than, or is greater to rhs, respectively. i.e. it behaves like memcmp(3). A NULL value for lhs or rhs compares as less-than any other value except NULL, to which it compares equal. */ short whuuid_compare( whuuid_t const * lhs, whuuid_t const * rhs ); /** Debugging/testing function which dumps the RNG distribution counts of st to the given FILE handle. The stats are updated on each call to whuuid_fill_rand() IF the WHUUID_CONFIG_KEEP_METRICS macro is set to a true value when the library is built. If full is non-zero then a full list of metrics is dumped, otherwise just an overview. Returns 0 on success, non-zero on error (!dest, !st, or WHUUID_CONFIG_KEEP_METRICS is false). */ int whuuid_dump_distribution( whuuid_rng const * st, short full, FILE * dest ); #endif /* WANDERGINHORSE_NET_WHUUID_H_INCLUDED */ /* end file cgi/whuuid.h */ /* begin file cgi/whuuid.c */ #include <assert.h> #include <string.h> /* memset() */ #include <stdlib.h> /* malloc(), free() */ #if WHUUID_CONFIG_KEEP_METRICS # include <stdio.h> /* fprintf(), FILE */ #endif const whuuid_t whuuid_t_empty = { {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}/*bytes*/ }; static void whuuid_noop_cleanup( whuuid_rng * self ) { /* does nothing */ } /** An almost-empty-initialized whuuid_rng object which uses whuuid_rand_uuint() as its random data source. It has no resources associated with it. */ const whuuid_rng whuuid_rng_empty = { NULL/*rand*/, whuuid_noop_cleanup/*cleanup*/, NULL/*impl*/, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}/*distribution*/ }; const whuuid_rng whuuid_rng_lcrng = { whuuid_lc_rand/*rand*/, whuuid_noop_cleanup/*cleanup*/, NULL/*impl*/, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}/*distribution*/ }; const whuuid_rng whuuid_rng_FILE = { whuuid_FILE_rand/*rand*/, whuuid_FILE_cleanup/*cleanup*/, NULL/*impl*/, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}/*distribution*/ }; /** BITS2CHAR(X) expects (X<=15). Returns the hex-code char for it ('0'..'f'), or 0 if X is out of range. */ #define BITS2CHAR(X) ( ((X)<=0x09) ? ('0'+(X)) : (((X)<=0xF) ? ('a'+((X)-10)) : 0)) void whuuid_FILE_cleanup( whuuid_rng * self ) { if( self && self->impl ) { fclose( (FILE*)self->impl ); self->impl = 0; } } int whuuid_FILE_rand( whuuid_rng * st, unsigned int * tgt ) { if( st && st->impl ) { unsigned int d = 0; if( 1 != fread( &d, sizeof(d), 1, (FILE*)st->impl ) ) { return -1; } *tgt = d; return 0; } return -1; } #include <time.h> int whuuid_lc_rand( whuuid_rng * st, unsigned int * tgt ) { typedef unsigned long NumType; NumType num = (NumType)st->impl; if( ! st || ! tgt ) return -1; #define RNG(SEED) (NumType)( (NumType)((NumType)(SEED) * (NumType)1103515245) + 12345) /* ^^^^^ This RNG Works very well for this use case (comparable with /dev/urandom on my box). Algo found in Angband sources. */ if( ! num ) { void * x; num = (NumType) st; /* Generate a unique seed. */ x = malloc( (num % 13)+9 ); free(x); num = (NumType)(RNG(x) ^ num) >> 6 /* The bitshift part is to work around the problem that the left-most byte of generated UUIDs always have the same starting sequences. */ ; } else { num = RNG(num); } #undef RNG st->impl = (void *)num; *tgt = num; return 0; } int whuuid_to_string( whuuid_t const * src, char * dest ) { unsigned int i = 0; int part = 1; int span = 0; char byte = 0; char nibble = 0; if( ! src || ! dest ) return -1; for( i = 0; i < whuuid_length_bytes; ) { int x; if( 1 == part ) span = 8; else if( (part>1) && (part<5) ) span = 4; else if( 5 == part ) span = 12; for( x = 0; x < (span/2); ++x ) { byte = src->bytes[i++]; nibble = (byte >> 4) & 0x0F; *(dest++) = BITS2CHAR(nibble); nibble = (byte & 0x0F); *(dest++) = BITS2CHAR(nibble); } if( part < 5 ) { *(dest++) = '-'; ++part; } else break; } return 0; } int whuuid_fill( whuuid_t * dest, unsigned char const * src ) { if( ! dest || ! src ) return -1; else { memcpy( dest, src, whuuid_length_bytes ); return 0; } } int whuuid_fill_rand( whuuid_t * dest, whuuid_rng * st ) { unsigned int i = 0, x = 0; unsigned char * c = 0; unsigned int r; unsigned char nibble; int rc = 0; if( ! st || ! dest ) return -1; if( ! dest ) return -1; for( ; i < whuuid_length_bytes; ) { rc = st->rand(st, &r); if( rc ) break; c = (unsigned char *)&r; for( x = sizeof(r); (x > 0) && (i < whuuid_length_bytes); --x, ++i, ++c ) { dest->bytes[i] = *c; #if WHUUID_CONFIG_KEEP_METRICS nibble = (*c >> 4) & 0x0F; ++st->distribution[nibble]; nibble = (*c & 0x0F); ++st->distribution[nibble]; #endif } } return rc; } short whuuid_compare( whuuid_t const * lhs, whuuid_t const * rhs ) { if( ! lhs ) return rhs ? -1 : 0; else if( ! rhs ) return 1; else if( lhs == rhs ) return 0; else { #if 0 unsigned int i = 0; unsigned char const * l = lhs->bytes; unsigned char const * r = rhs->bytes; unsigned char bl = 0, br = 0; /* current byte of lhs/rhs*/ unsigned char nl = 0, nr = 0;/* 4-bit part of bl/br*/ for( ; i < whuuid_length_bytes; ++i ) { bl = l[i]; br = r[i]; nl = (bl >> 4); nr = (br >> 4); if( nl < nr ) return -1; else if( nl > nr ) return 1; nl = (bl & 0x0F); nr = (br & 0x0F); if( nl < nr ) return -1; else if( nl > nr ) return 1; } return 0; #else return memcmp( lhs->bytes, rhs->bytes, whuuid_length_bytes ); #endif } } int whuuid_dump_distribution( whuuid_rng const * st, short full, FILE * dest ) { #if ! WHUUID_CONFIG_KEEP_METRICS fprintf("WHUUID_CONFIG_KEEP_METRICS is false, so whuuid_dump_distribution() cannot work!\n"); return -1; #else unsigned short i = 0; double total = 0; unsigned long int max = 0, min = st->distribution[0]; unsigned long int x = 0; char minL = 0, maxL = 0; if( full ) { fprintf(dest,"Random number distribution:\nDigit:\tCount:\n"); } for( ; i < 16; ++i ) { x = st->distribution[i]; total += x; if( max < x ) { max = x; maxL = BITS2CHAR(i); } else if( min >= x ) { min = x; minL = BITS2CHAR(i); } } if( full ) { for( i = 0; i < 16; ++i ) { x = st->distribution[i]; fprintf(dest,"%c\t%lu (%0.6f%%)\n", BITS2CHAR(i), x, (x/ total) *100 ); } } fprintf(dest,"Least Hits: '%c' (%lu)\nMost Hits: '%c' (%lu)\n", minL, min, maxL, max ); if( max == min ) { fprintf(dest,"Least==Most == best possible random distribution!\n" ); } else { fprintf(dest,"Max-Min diff = %lu (%0.4f%% of Max)\n", max - min, ((max - min)/(double)max)*100 ); } fprintf(dest,"Total random 4-bit UUID digits: %0.0f\n\n",total); return 0; #endif } #undef BITS2CHAR /* end file cgi/whuuid.c */ /* begin file cgi/cson_cgi.c */ #include <assert.h> #include <stdlib.h> /* environ, getenv(), atexit() */ #include <ctype.h> /* isspace() */ #include <string.h> /* strlen() */ #include <stdarg.h> #include <time.h> #include <locale.h> /* setlocale(), needed for JSON parser. */ #define CSON_CGI_USE_SIGNALS 1 /* If RNG_FILENAME evaluates to true then we use that file for getting random bytes for session IDs. FIXME: we effectively leak a file handle if this is enabled. */ #if 0 # define RNG_FILENAME "/dev/urandom" #else # define RNG_FILENAME NULL #endif #if 1 #define MARKER if(1) printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); if(1) printf #else static void noop_printf(char const * fmt, ...) {} #define MARKER if(0) printf #endif #if CSON_CGI_USE_SIGNALS # include <signal.h> /* signal() */ #endif const cson_cgi_init_opt cson_cgi_init_opt_empty = cson_cgi_init_opt_empty_m; /** Some cson_cgi-internal value keys. */ static const struct { char const * ENV_GET; char const * ENV_POST; char const * ENV_COOKIE; char const * ENV_SYS; char const * ENV_APP; char const * ENV_ARGV; char const * ENV_CONFIG; char const * ENV_SESSION; char const * RESPONSE_HEADERS; } cson_cgi_keys = { "$GET", "$POST", "$COOKIE", "$ENV", "$APP", "$ARGV", "$CONFIG", "$SESSION", "response.headers" }; /** Shared state used by the cson_cgi API. */ const cson_cgi_cx cson_cgi_cx_empty = cson_cgi_cx_empty_m; static int cson_cgi_printf(cson_cgi_cx * cx, char const * fmt, ... ) { if( ! fmt ) return 0; else { int rc; va_list vargs; assert( NULL != cx->opt.outStream ); va_start( vargs, fmt ); rc = vfprintf( cx->opt.outStream, fmt, vargs ); /*if( rc > 0 ) fflush( cx->opt.outStream );*/ va_end( vargs ); return rc; } } static int cson_cgi_puts(cson_cgi_cx * cx, char const * str) { size_t const slen = str ? strlen(str) : 0; if( slen ) { if( 1 != fwrite( str, slen, 1, cx->opt.outStream ) ) { return -1; } } if( 1 != fwrite( "\n", 1, 1, cx->opt.outStream ) ) { return -2; } return (int) (slen + 1); } static int cson_cgi_putchar(cson_cgi_cx * cx, char ch) { return ( 1 == fwrite( &ch, 1, 1, cx->opt.outStream ) ) ? 1 : -1; } cson_value * cson_cgi_argv(cson_cgi_cx *cx) { return cx ? cx->argv.jval : NULL; } cson_array * cson_cgi_argv_array(cson_cgi_cx * cx) { return cx ? cson_value_get_array( cx->argv.jval ) : NULL; } int cson_cgi_gc_add( cson_cgi_cx * cx, char const * key, cson_value * v, char freeOnError ) { int const rc = cson_object_set( cx->gc.jobj, key, v ); if( (0 != rc) && freeOnError ) { cson_value_free( v ); } return rc; } int cson_cgi_response_root_set( cson_cgi_cx * cx, cson_value * v ) { if( ! cx ) return cson_rc.ArgError; else if( v && !cson_value_is_object(v) && !cson_value_is_array(v) ) { return cson_rc.TypeError; } else if( cx->response.root != v ) { int rc = 0; rc = cson_cgi_gc_add(cx, "response.root", v, 0 ) /** TODO: confirm that cson_object_set() does not clean up the original object if insertion fails. If it does, we've just hosed the root node. */ ; if( 0 != rc ) { return rc; } else { cx->response.root = v; return 0; } } else { return 0; } } cson_value * cson_cgi_response_root_get( cson_cgi_cx * cx, char createMode ) { if( ! cx ) return NULL; else if( cx->response.root ) return cx->response.root; else { if( 0 != createMode ) { if( createMode > 0 ) { cx->response.root = cson_value_new_object(); } else if( createMode < 0 ) { cx->response.root = cson_value_new_array(); } if( cx->response.root && (0 != cson_cgi_gc_add(cx, "response.root", cx->response.root, 1 )) ) { cx->response.root = NULL /* was cleaned up by cson_cgi_gc_add() */; } } return cx->response.root; } } /** @internal Tokenizes an input string on a given separator. Inputs are: - (inp) = is a pointer to the pointer to the start of the input. - (separator) = the separator character - (end) = a pointer to NULL. i.e. (*end == NULL) This function scans *inp for the given separator char or a NULL char. Successive separators at the start of *inp are skipped. The effect is that, when this function is called in a loop, all neighboring separators are ignored. e.g. the string "aa.bb...cc" will tokenize to the list (aa,bb,cc) if the separator is '.' and to (aa.,...cc) if the separator is 'b'. Returns 0 (false) if it finds no token, else non-0 (true). Output: - (*inp) will be set to the first character of the next token. - (*end) will point to the one-past-the-end point of the token. If (*inp == *end) then the end of the string has been reached without finding a token. Post-conditions: - (*end == *inp) if no token is found. - (*end > *inp) if a token is found. It is intolerant of NULL values for (inp, end), and will assert() in debug builds if passed NULL as either parameter. When looping, one must be sure to re-set the inp and end parameters. For example: @code char const * head = input; char const * tail = NULL; while( cson_cgi_next_token( &inp, '/', &tail ) ) { ... head = tail; tail = NULL; } @endcode If the loop calls 'continue', it must be careful to ensure that the parameters are re-set, to avoid an endless loop. This can be simplified with a goto: @code while( cson_cgi_next_token( &inp, '/', &tail ) ) { if( some condition ) { ... do something ... goto next_iter; } else { .... } next_iter; head = tail; tail = NULL; } @endcode */ char cson_cgi_next_token( char const ** inp, char separator, char const ** end ) { char const * pos = NULL; assert( inp && end && *inp ); if( ! inp || !end ) return 0; else if( *inp == *end ) return 0; pos = *inp; if( !*pos ) { *end = pos; return 0; } for( ; *pos && (*pos == separator); ++pos) { /* skip preceeding splitters */ } *inp = pos; for( ; *pos && (*pos != separator); ++pos) { /* find next splitter */ } *end = pos; return (pos > *inp) ? 1 : 0; } /** If map->jval is NULL then map->jval is created using cson_value_new_object() and map->jobj is assigned to its object reference. The newly-created map->jval is appended to cx->gc to ensure that map->jval lives a full life (as opposed to potentially being prematurly GC'd if a client later adds map->jval to his own container). If map->jval is not NULL then this function is a no-op. This function will assert() if map is NULL. Returns 0 on success, else cson_rc.AllocError. On error map->jval will be NULL after this call. On success, ownership of map->jval is transfered to (or potentially shared with) cx->gc. */ static int cson_cgi_init_env_map( cson_cgi_cx * cx, char const * gckey, cson_cgi_env_map * map ) { int rc = 0; assert( NULL != map ); if( NULL == map->jval ) { assert( NULL == map->jobj ); map->jval = cson_value_new_object(); if( NULL == map->jval ) return cson_rc.AllocError; rc = cson_cgi_gc_add( cx, gckey, map->jval, 1 ) /* We do this to avoid a corner case in cleanup logic if the client stores this object in another container. */; if( 0 != rc ) { map->jval = NULL /* was cleaned up by cson_cgi_gc_add() */; } else { map->jobj = cson_value_get_object( map->jval ); assert( NULL != map->jobj ); } } return rc; } char const * cson_cgi_getenv_cstr( cson_cgi_cx * cx, char const * where, char const * key ) { return cson_string_cstr( cson_value_get_string( cson_cgi_getenv(cx, where, key) ) ); } cson_value * cson_cgi_path_part( cson_cgi_cx * cx, unsigned short ndx ) { cson_value * piV = cson_cgi_getenv( cx, "e", "PATH_INFO_SPLIT" ); if( ! piV ) return NULL; else { unsigned int alen; cson_array * ar = cson_value_get_array(piV); assert( NULL != ar ); alen = cson_array_length_get( ar ); return ( ndx >= alen ) ? NULL : cson_array_get( ar, ndx ); } } char const * cson_cgi_path_part_cstr( cson_cgi_cx * cx, unsigned short ndx ) { return cson_string_cstr( cson_value_get_string( cson_cgi_path_part( cx, ndx ) ) ); } /** cson_cgi_hexchar_to_int(): For 'a'-'f', 'A'-'F' and '0'-'9', returns the appropriate decimal number. For any other character it returns -1. */ static int cson_cgi_hexchar_to_int( int ch ) { if( (ch>='a' && ch<='f') ) return ch-'a'+10; else if( (ch>='A' && ch<='F') ) return ch-'A'+10; else if( (ch>='0' && ch<='9') ) return ch-'0'; return -1; } /** Replaces %XX patterns in str with their equivalent character and '+' characters with a single whitespace. %XX patterns which are not hexidecimal values are not translated. str must be NULL or a NUL-terminated string. If it is NULL or the first byte is NUL then 0 is returned and this function has no side-effects. BUGS(?): URL-decoding might have a few bugs/corner cases. */ static int cson_cgi_urldecode_inline( char * str ) { unsigned char ch = 0; unsigned char cx1 = 0; unsigned char cx2 = 0; int decoded; unsigned char * pos = (unsigned char *)str; unsigned char * out = pos; unsigned char const * end; size_t slen = (str && *str) ? strlen(str) : 0; if( !slen ) return 0; end = pos + slen; for( ; pos < end; ++pos ) { ch = *pos; if( ch == '%' ) { cx1 = *(pos+1); /* FIXME: with only minor refactoring we can remove the isxdigit() calls and use cson_cgi_hexchar_to_int() instead, checking for a negative return value. That would potentially save us 2 extra function calls here. */ if( isxdigit(cx1) ) { cx2 = *(pos+2); if( isxdigit(cx2) ) { decoded = (cson_cgi_hexchar_to_int( cx1 ) * 16) + cson_cgi_hexchar_to_int( cx2 ); *(out++) = (char)decoded; pos += 2; continue; } /* else fall through... */ } /* else fall through... */ } else if( ch == '+' ) { *(out++) = ' '; continue; } *(out++) = ch; } *out = 0; return 0; } /** If PATH_INFO is set, this function splits it on '/' characters and creates an array out of the elements. The array is stored as $ENV["PATH_INFO_SPLIT"]. Returns non-0 on error. If PATH_INFO is not set, 0 is returned. If it is set but has no entries, an empty array is created. A return value of cson_rc.RangeError probably means that a path element was longer than our internal buffer size, in which case processing ends and PATH_INFO_SPLIT is not set. That error can probably be ignored by the caller, but all others are probably serious (e.g. AllocError). */ static int cson_cgi_import_path_info(cson_cgi_cx *cx) { char const * pi = cson_cgi_getenv_cstr(cx, "e","PATH_INFO"); if( NULL == pi ) return 0; else { cson_value * arV = cson_value_new_array(); cson_array * ar; char const * head = pi; char const * tail = NULL; if( ! arV ) return cson_rc.AllocError; else { enum { BufSize = 128 }; char buf[BufSize]; cson_value * partV; unsigned int slen; int rc = 0; ar = cson_value_get_array(arV); while( cson_cgi_next_token( &head, '/', &tail ) ) { slen = (tail-head); if( slen >= BufSize ) { rc = cson_rc.RangeError; goto end_clean; } memcpy( buf, head, slen ); buf[slen] = 0; cson_cgi_urldecode_inline( buf ); partV = cson_value_new_string( buf, strlen(buf) ); if( ! partV ) { rc = cson_rc.AllocError; goto end_clean; } rc = cson_array_append( ar, partV ); if( rc ) { cson_value_free( partV ); goto end_clean; } partV = NULL; head = tail; tail = NULL; } assert( 0 == rc ); rc = cson_object_set( cx->request.env.jobj, "PATH_INFO_SPLIT", arV ); end_clean: if( rc ) { cson_value_free( arV ); } return rc; } } } /** Imports (extern char ** environ) into cx->request.env, initializing cx->request.env if needed. If called multiple times the environment is re-read each time, but old entries which are no longer in the new environment are not removed from cx->request.env. Returns 0 on success. */ static int cson_cgi_import_environ(cson_cgi_cx * cx) { extern char ** environ; int i = 0; char const * e = environ[0]; char const * v = NULL; enum { KeyBufSize = 512 }; char keybuf[KeyBufSize]; char * kpos = NULL; int rc = 0; cson_value * jv = NULL; rc = cson_cgi_init_env_map( cx, cson_cgi_keys.ENV_SYS, &cx->request.env ); if( 0 != rc ) return rc; for( ; e && *e; e = environ[++i] ) { v = NULL; memset( keybuf, 0, KeyBufSize ); kpos = keybuf; for( ; *e && ('=' != *e); ++e ) { *(kpos++) = *e; assert( kpos < (keybuf+KeyBufSize) ); if( kpos >= (keybuf+KeyBufSize) ) { return cson_rc.RangeError; } } if( '=' == *e ) { v = e+1; } else { v = ""; } jv = cson_value_new_string( v, strlen(v) ); if( NULL == jv ) { rc = cson_rc.AllocError; break; } rc = cson_object_set( cx->request.env.jobj, keybuf, jv ); if( 0 != rc ) break; } if( 0 == rc ) { rc = cson_cgi_import_path_info(cx); } return rc; } /** Tries to save the current session data, if any, using the configured session manager. Returns 0 on success. If the environment has no session, it is treated as success but nothing is actually saved. If no session manager has been configured then cson_rc.UnsupportedError is returned. */ static int cson_cgi_session_save(cson_cgi_cx * cx) { if( ! cx->session.mgr ) { return cson_rc.UnsupportedError; } else if( !cx->session.id || !cx->session.env.jval ) { return 0; } else { return cx->session.mgr->api->save( cx->session.mgr, cx->session.env.jval, cx->session.id ); } } cson_cgi_cx * cson_cgi_cx_alloc() { cson_cgi_cx * rc = (cson_cgi_cx *)malloc(sizeof(cson_cgi_cx)); if( rc ) { *rc = cson_cgi_cx_empty; rc->misc.allocStamp = rc; } return rc; } char cson_cgi_cx_clean( cson_cgi_cx * cx ) { if( !cx ) return 0; else { void const * allocStamp = NULL; if( cx->session.mgr ) { cson_cgi_session_save(cx) /* ignoring error code */; cx->session.mgr->api->finalize( cx->session.mgr ); cx->session.mgr = NULL; } if(NULL != cx->gc.jval) { cson_value_free( cx->gc.jval ); cx->gc.jval = NULL; cx->gc.jobj = NULL; } if( cx->session.id ) { free( cx->session.id ); cx->session.id = NULL; } cson_buffer_reserve( &cx->tmpBuf, 0 ); allocStamp = cx->misc.allocStamp; if( cx->opt.inStream && (stdin != cx->opt.inStream) ) fclose(cx->opt.inStream); if( cx->opt.outStream && (stderr == cx->opt.outStream) && (stdout != cx->opt.outStream) ) fclose(cx->opt.outStream); if( cx->opt.errStream && (stderr == cx->opt.errStream) && (stdout != cx->opt.errStream) ) fclose(cx->opt.errStream); *cx = cson_cgi_cx_empty; return ( allocStamp == cx ) ? (free( cx ), 1) : 0; } } cson_value * cson_cgi_env_get_val( cson_cgi_cx * cx, char which, char createIfNeeded ) { cson_cgi_env_map * map = NULL; cson_value * v = NULL; char const * gckey = NULL; switch( which ) { case 'c': case 'C': map = &cx->request.cookie; gckey = cson_cgi_keys.ENV_COOKIE; break; case 'e': case 'E': gckey = cson_cgi_keys.ENV_SYS; map = &cx->request.env; break; case 'g': case 'G': gckey = cson_cgi_keys.ENV_GET; map = &cx->request.get; break; case 'f': case 'F': gckey = cson_cgi_keys.ENV_CONFIG; map = &cx->config; break; case 'p': case 'P': gckey = cson_cgi_keys.ENV_POST; map = &cx->request.post; break; case 'a': case 'A': gckey = cson_cgi_keys.ENV_APP; map = &cx->clientEnv; break; case 's': case 'S': gckey = cson_cgi_keys.ENV_SESSION; map = &cx->session.env; break; default: break; } if( map ) { v = map->jval; if( !v && createIfNeeded ) { assert( NULL != gckey ); cson_cgi_init_env_map( cx, gckey, map ); v = map->jval; } } return v; } cson_object * cson_cgi_env_get_obj( cson_cgi_cx * cx, char which, char createIfNeeded ) { return cson_value_get_object( cson_cgi_env_get_val( cx, which, createIfNeeded ) ); } /** Sets a variable in one of the environment objects. env must be the conventional character representation (case-insensitive) for on of the following environment objects: - g = GET - p = POST - e = ENV - c = COOKIE - u = USER On success 0 is returned and ownership of v is transfered to (or shared with) the appropriate environment object. On error non-zero is returned and ownership of v is not modified. */ static int cson_cgi_setenv_x( cson_cgi_cx * cx, char env, char const * key, cson_value * v ) { if( ! key || !*key ) return cson_rc.ArgError; else { cson_object * jo = cson_cgi_env_get_obj( cx, env, 1 ); return ( NULL == jo ) ? cson_rc.RangeError /* FIXME: expand the above code so we can distinguish between invalid env and allocation error. (Except that there is no allocation on get_obj().*/ : cson_object_set( jo, key, v ); } } int cson_cgi_setenv( cson_cgi_cx * cx, char const * key, cson_value * v ) { return cson_cgi_setenv_x( cx, 'a', key, v ); } int cson_cgi_cookie_set( cson_cgi_cx * cx, char const * key, cson_value * v ) { if( ! key || !*key ) return cson_rc.ArgError; else { cson_object * jo = cson_cgi_env_get_obj( cx, 'c', 1 ); return (NULL == jo) ? cson_rc.AllocError : cson_object_set( jo, key, v ? v : cson_value_null() ); } } int cson_cgi_cookie_set2( cson_cgi_cx * cx, char const * key, cson_value * v, char const * domain, char const * path, unsigned int expires, char secure, char httponly ) { if( ! key || !*key ) return cson_rc.ArgError; else { int rc; cson_value * jv = cson_value_new_object(); cson_object * jo = cson_value_get_object(jv); cson_value * x = NULL; if( ! jo ) return cson_rc.AllocError; if( ! v ) v = cson_value_null() /* reminder: does not allocate */; #define SET(KEY) if( 0 != (rc = cson_object_set( jo, KEY, x) ) ) { \ cson_value_free(x); \ cson_value_free( jv ); \ return rc; \ } if( NULL != domain ) { x = cson_value_new_string( domain, strlen(domain) ); SET("domain"); } if( NULL != path ) { x = cson_value_new_string( path, strlen(path) ); SET("path"); } if( cson_value_is_null(v) ) { x = cson_value_new_integer( 1 ); SET("expires"); } else if( expires ) { x = cson_value_new_integer( (cson_int_t) expires ); SET("expires"); } if( secure ) { x = cson_value_new_bool(secure); SET("secure"); } if( httponly ) { x = cson_value_new_bool(httponly); SET("httponly"); } #undef SET rc = cson_cgi_cookie_set( cx, key, jv ); if( 0 != rc ) { cson_value_free( jv ); } else { /* set "value" last so that we can avoid tricky ownership/lifetime problems in error cases. */ if( 0 != (rc = cson_object_set( jo, "value", v) ) ) { /* remove the cookie. Note that this particular case does not remove it from the HTTP client. In order to do that we have to keep the existing path/domain/etc info. */ cson_object * cookies = cson_cgi_env_get_obj( cx, 'c', 0 ); if( cookies ) { cson_object_set( cookies, key, cson_value_null() ) /* Ignore error code, since we have no fallback and cson_value_null() does not allocate. Worst-case is that removing it fails, but when we emit the cookie headers that cookie will be skipped because it has no "value" field. */ ; } } } return rc; } } cson_value * cson_cgi_getenv( cson_cgi_cx * cx, char const * fromWhere, char const * key ) { cson_value * jv = NULL; cson_object * map = NULL; if( (NULL == fromWhere) || !*fromWhere ) fromWhere = CSON_CGI_GETENV_DEFAULT; if( !key || !*key ) return NULL; for( ; *fromWhere ; ++fromWhere ) { map = cson_cgi_env_get_obj( cx, *fromWhere, 0 ); if( (NULL == map) && (('r'==*fromWhere)||('R'==*fromWhere)) ) { jv = cson_cgi_getenv( cx, "gpc", key ); } if( NULL != jv ) /* only in 'R' case */ break; else if( NULL == map ) continue /* invalid character or NULL map */; jv = cson_object_get( map, key ); if( NULL != jv ) break; } return jv; } int cson_cgi_response_header_add( cson_cgi_cx * cx, char const * key, cson_value * v ) { int rc = 0; if( !cx || ! key || !*key ) return cson_rc.ArgError; rc = cson_cgi_init_env_map( cx, cson_cgi_keys.RESPONSE_HEADERS, &cx->response.headers ); if( 0 == rc ) { assert( NULL != cx->response.headers.jobj ); rc = cson_object_set( cx->response.headers.jobj, key, v ); } return rc; } char cson_cgi_is_jsonp(cson_cgi_cx * cx) { if( ! cx ) return 0; else if( cx->misc.isJSONP < 0 ) { /* guess */ cx->misc.isJSONP = (NULL == cson_cgi_getenv( cx, "agp", CSON_CGI_KEY_JSONP )) ? 0 : 1; } return cx->misc.isJSONP; } void cson_cgi_enable_jsonp( cson_cgi_cx * cx, char b ) { if( cx ) cx->misc.isJSONP = b ? 1 : 0; } char const * cson_cgi_guess_content_type(cson_cgi_cx * cx) { char const * cset; char doUtf8; cset = getenv("HTTP_ACCEPT_CHARSET"); doUtf8 = ((NULL == cset) || (NULL!=strstr("utf-8",cset))) ? 1 : 0; if( cson_cgi_is_jsonp(cx) ) { return doUtf8 ? "application/javascript; charset=utf-8" : "application/javascript"; } else { /* Content-type If the browser does not sent an ACCEPT for application/json then we fall back to text/plain. */ char const * cstr; cstr = getenv("HTTP_ACCEPT"); if( NULL == cstr ) { return doUtf8 ? "application/json; charset=utf-8" : "application/json"; } else { if( strstr( cstr, "application/json" ) || strstr( cstr, "*/*" ) ) { return doUtf8 ? "application/json; charset=utf-8" : "application/json"; } else { return "text/plain"; } } } } /** URL-encodes src to dest and NUL-terminates it. dest must be at least *destLen bytes long. Upon a successful return, *destLen will be modified to hold the new string's length. Returns 0 on success. On error dest might be partially populated. Returns cson_rc.RangeError if dest is not long enough to hold the conversion and a terminating NUL. */ static int cson_cgi_urlencode( char const * src, char * dest_, size_t * destLen ) { #define needs_escape \ ( (ch >= 32 && ch <=47) \ || ( ch>=58 && ch<=64) \ || ( ch>=91 && ch<=96) \ || ( ch>=123 && ch<=126) \ || ( ch<32 || ch>=127) \ ) char const * pos = src; char ch; size_t dpos = 0; char * dest = dest_; static char const * hex = "0123456789ABCDEF"; if( ! dest || !destLen ) return cson_rc.RangeError; for( ; pos && *pos; ++pos ) { ch = *pos; if( ! needs_escape ) { if( ++dpos >= *destLen ) return cson_rc.RangeError; *(dest++) = ch; continue; } else { if( (dpos+=3) >= *destLen ) return cson_rc.RangeError; *(dest++) = '%'; *(dest++) = hex[((ch>>4)&0xf)]; *(dest++) = hex[(ch&0xf)]; } } if( ++dpos >= *destLen ) return cson_rc.RangeError; *dest = 0; *destLen = dest - dest_; return 0; #undef needs_escape } /** If orig is one of the types (string,double,bool,undef,null) then a pointer to its string representation is returned, else NULL is returned. For non-string types, dest must be at least destLen bytes of memory, and if destLen is not long enough to hold the string form then NULL is returned. On success a pointer to a string is returned. It will be one of: - if orig is-a string then it's underlying string. - for (double,integer,bool,undef,null), dest will be returned. The encoded form is decimal for (double,integer), the number 0 or 1 for bool, and the number 0 for (undef,null). Ownership of dest is not modified by this call. The returned value is valid until either orig or dest are modified. On error dest is not modified. Dest is also not modified if orig is-a string, as its own string bytes are returned instead. */ static char const * cson_cgi_pod_to_string( cson_value const * orig, char * dest, unsigned int destLen ) { if( ! orig || !dest || !destLen ) return NULL; else {/* FIXME? use cson's output support for the numeric types. i _think_ those bits might not be in the public API, though. We could use it for serializing objects/arrays, in any case. */ enum { NumBufSize = 80 }; if( cson_value_is_string(orig) ) { cson_string const * jstr = cson_value_get_string(orig); assert( NULL != jstr ); return cson_string_cstr( jstr ); } else if( cson_value_is_integer(orig) ) { char tmp[NumBufSize] = {0}; int const sc = sprintf( tmp, "%"CSON_INT_T_PFMT, cson_value_get_integer(orig)); if( sc <= 0 ) return NULL; else if( (unsigned int)sc >= destLen ) return NULL; else { strcpy( dest, tmp ); return dest; } } else if( cson_value_is_double(orig) ) { char tmp[NumBufSize] = {0}; int const sc = sprintf( tmp, "%"CSON_DOUBLE_T_PFMT, cson_value_get_double(orig)); if( sc <= 0 ) return NULL; else if( (unsigned int)sc >= destLen ) return NULL; else { strcpy( dest, tmp ); if(1) { /* Strip trailing zeroes... */ unsigned int urc = strlen(dest); char * pos = dest + urc - 1; for( ; ('0' == *pos) && urc && (*(pos-1) != '.'); --pos, --urc ) { *pos = 0; } assert(urc && *pos); } return dest; } } else if( cson_value_is_bool( orig ) ) { char const bv = cson_value_get_bool(orig); if( destLen < 2 ) return NULL; *dest = bv ? '1' : '0'; *(dest+1) = 0; return dest; } else if( cson_value_is_null( orig ) || cson_value_is_undef( orig ) ) { if( destLen < 2 ) return NULL; *dest = '0'; *(dest+1) = 0; return dest; } else { return NULL; } } } /** Writes an RFC822 timestamp string to dest, which must be at least destLen bytes long. On success returns dest, else NULL. destLen must be at least 31. */ static char * cson_cgi_rfc822_timedate( time_t now, char * dest, unsigned int destLen ) { static const char * dayNames[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", 0 }; static const char * monthNames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", 0}; struct tm * t = (dest && (destLen>30)) ? gmtime(&now) : NULL; if( ! t || (destLen<31) ) return NULL; else { int const rc = sprintf( dest, "%s, %d %s %02d %02d:%02d:%02d GMT", dayNames[t->tm_wday], t->tm_mday, monthNames[t->tm_mon], t->tm_year+1900, t->tm_hour, t->tm_min, t->tm_sec ); assert( (rc>0) && ((unsigned int)rc) < destLen ); return dest; } } /** Outputs the cookie-specific HTTP headers. Returns 0 on success. */ static int cson_cgi_response_output_cookies(cson_cgi_cx * cx) { cson_kvp * kvp = NULL; cson_object * jo = NULL; cson_object_iterator iter = cson_object_iterator_empty; assert(cx); jo = cx->request.cookie.jobj; if( ! jo ) return 0; else { enum { CookieBufSize = 1024 * 8, ValBufSize = 1024 * 4, TSBufSize = 32 }; char cookieBuf[CookieBufSize] = {0} /* buffer for whole cookie string */; char valBuf[ValBufSize] = {0} /* buffer for value encoding */; char urlBuf[ValBufSize] = {0} /* buffer for urlencoding */; char tsBuf[TSBufSize] = {0} /* buffer for expiry timestamp */; int rc = cson_object_iter_init( jo, &iter ); assert( CookieBufSize > ValBufSize ); if( 0 != rc ) return rc; while( (kvp = cson_object_iter_next(&iter)) ) { cson_string const * key = cson_kvp_key(kvp); cson_value const * val = cson_kvp_value(kvp); if( cson_value_is_null(val) ) { cson_cgi_printf(cx,"Set-Cookie: %s=null; expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n", cson_string_cstr(key)); continue; } if( cson_value_is_object(val) ) { /* Accept in Object in the form: { value: VALUE, domain: string, path: string, secure: bool, httponly: bool, expires: integer } */ cson_object const * obj = cson_value_get_object( val ); cson_value const * cv = cson_object_get( obj, "value" ); char const * valstr = NULL; char const isNull = !cv || cson_value_is_null( cv ); if( isNull ) { cson_cgi_printf(cx, "Set-Cookie: %s=0", cson_string_cstr(key)); } else { /* FIXME: streamify urlencode so we can get around fixed buffer size. */ valstr = cson_cgi_pod_to_string( cv, valBuf, ValBufSize ); if( ! valstr ) continue; else { size_t bSize = ValBufSize; memset( urlBuf, 0, ValBufSize ); if( 0 != cson_cgi_urlencode( valstr, urlBuf, &bSize ) ) { /* buffer is too small. Skip it. */ continue; } assert( bSize <= ValBufSize ); cson_cgi_printf(cx, "Set-Cookie: %s=%s", cson_string_cstr(key), urlBuf); } } #define DOPART(KEY,KEY2) cv = cson_object_get( obj, KEY ); \ if( cv ) { \ valstr = cson_cgi_pod_to_string( cv, valBuf, ValBufSize ); \ if( valstr ) { \ cson_cgi_printf( cx, "; "KEY2"=%s", valstr ); \ } } (void)0 DOPART("domain","Domain"); DOPART("path","Path"); #undef DOPART cv = cson_object_get( obj, "expires" ); if( cv || isNull ) { cson_int_t const intVal = isNull ? 1 : cson_value_get_integer(cv); if( intVal ) { valstr = cson_cgi_rfc822_timedate( (time_t)intVal, tsBuf, TSBufSize ); if( valstr ) { cson_cgi_printf( cx, "; Expires=%s", valstr ); } } #if 0 else if( cson_value_is_string(cv) ) { /* TODO?: assume it's already propery formatted. */ } else { /* skip it.*/ } #endif } cv = cson_object_get( obj, "secure" ); if( cson_value_get_bool(cv) ) { cson_cgi_printf( cx, "; Secure" ); } cv = cson_object_get( obj, "httponly" ); if( cson_value_get_bool(cv) ) { cson_cgi_printf( cx, "; HttpOnly" ); } cson_cgi_puts(cx, "\r"); } else { char const * valstr; memset( valBuf, 0, ValBufSize ); valstr = cson_cgi_pod_to_string( val, valBuf, ValBufSize ); if( ! valstr ) continue; else { size_t bSize = CookieBufSize; memset( cookieBuf, 0, CookieBufSize ); rc = cson_cgi_urlencode( valstr, cookieBuf, &bSize ); if( 0 != rc ) { /* too beaucoup. skip it */ continue; } assert( bSize < CookieBufSize ); cson_cgi_printf(cx,"Set-Cookie: %s=%s\r\n", cson_string_cstr(key), cookieBuf); } } } return 0; } } int cson_cgi_response_output_headers(cson_cgi_cx * cx) { enum { BufSize = 64 }; cson_object * jo = NULL; int rc; rc = cson_cgi_printf(cx, "Content-type: %s\r\n", cson_cgi_guess_content_type(cx) ); if( rc <= 0 ) return rc; rc = cson_cgi_puts(cx, "Status: 200 OK\r"); if( rc <= 0 ) return rc; jo = cx->response.headers.jobj; if( jo ) { char buf[BufSize] = {0}; cson_object_iterator iter = cson_object_iterator_empty; cson_kvp * kvp; cson_string const * key; cson_value const * val; char const * valcstr; rc = cson_object_iter_init( jo, &iter ); if( 0 != rc ) return rc; while( (kvp = cson_object_iter_next(&iter)) ) { key = cson_kvp_key(kvp); val = cson_kvp_value(kvp); valcstr = cson_cgi_pod_to_string( val, buf, BufSize ); if( ! valcstr ) continue; assert( NULL != key ); assert( NULL != val ); cson_cgi_printf(cx, "%s: %s\r\n", cson_string_cstr(key), valcstr ? valcstr : ""); } } rc = cson_cgi_response_output_cookies(cx); return rc; } int cson_cgi_response_output_root(cson_cgi_cx * cx) { return ( !cx || !cx->response.root ) ? cson_rc.ArgError : cson_output_FILE( cx->response.root, cx->opt.outStream, &cx->opt.outOpt ); } int cson_cgi_response_output_all(cson_cgi_cx * cx) { int rc = 0; char isJP = 0; char doHeaders = cx->opt.httpHeadersMode; if( NULL == cx->response.root ) { return cson_rc.ArgError; } isJP = cson_cgi_is_jsonp(cx); if( doHeaders < 0 ) { if( NULL!=getenv("GATEWAY_INTERFACE") ) { doHeaders = 1; } } if( doHeaders > 0 ) { rc = cson_cgi_response_output_headers(cx); if( 0 == rc ) { cson_cgi_puts(cx,"\r")/*yes, putS, not putCHAR!*/; } else return rc; } if( isJP ) { cson_cgi_printf(cx,"%s(", "FIXME_JSONP_CALLBACK_NAME" ); } rc = cson_cgi_response_output_root(cx); if( 0 == rc ) { if( isJP ) { cson_cgi_putchar(cx,')'); } cson_cgi_putchar(cx,'\n'); fflush( cx->opt.outStream ); } return rc; } /** Parses inp as a delimited list, separated by the given separator character. Each item in the list is treated as a key/value pair in the form KEY=VALUE, and inserted into the target cson_object (which must not be NULL). This is intended for parsing HTTP GET-style parameter lists. If doUrlDecode is true (non-zero) then the VALUE part of the key/value pair gets url-decoded before insertion. (FIXME? Also decode the keys?) If firstOneWins is non-0 then if a given key in the parameters is duplicated, entries after the first are ignored. If it is 0 then the "last one wins." This is basically a workaround for when we have multiple session ID cookies hanging around :/. On success it returns 0. If a given key contains the string "[]", that part is stripped and the entry is treated like an array element. e.g. a query string of "a[]=3&a[]=7" would result in an array property named "a" with the (string) entries ("3", "7"). */ static int cson_cgi_parse_param_list( cson_cgi_cx * cx, cson_object * tgt, char const * inp, char separator, char doUrlDecode, char firstOneWins) { if( ! tgt || !separator ) return cson_rc.ArgError; else if( !inp || !*inp ) return 0; else { char const * head = inp; char const * tail = NULL; char * out = NULL; unsigned int inLen = strlen( inp ); unsigned int valLen; cson_value * jval = NULL; cson_value * listV = NULL; cson_array * list = NULL; int rc = cson_buffer_reserve( &cx->tmpBuf, inLen+1 ); if( 0 != rc ) return rc; while( cson_cgi_next_token( &head, separator, &tail ) ) { char const * key = head; char * value = NULL; rc = 0; if( head == tail ) break; out = (char *)cx->tmpBuf.mem; memset( cx->tmpBuf.mem, 0, cx->tmpBuf.capacity ); for( ; (key<tail) && *key && isspace(*key); ++key ) { /* strip leading spaces in the key name (happens in cookie values). */ } if( key==tail ) break; else if( '='==*key ) { /* all-space key. Just skip it. */ goto next_iter; } /* Write the key part to the buffer... */ for( ; (key<tail) && *key && ('='!=*key); ++key ) { *(out++) = *key; } *(out++) = 0; if( '=' == *key ) { ++key; } value = out; valLen = 0; /* Write the value part to the buffer... */ for( ; (key<tail) && *key; ++key, ++valLen ) { *(out++) = *key; } key = (char const *)cx->tmpBuf.mem; if( firstOneWins && (NULL != cson_object_get( tgt, key )) ) { goto next_iter; } if( doUrlDecode && valLen ) { cson_cgi_urldecode_inline( value ); } /*MARKER("key=[%s], valLen=%u, value=[%s]\n", key, valLen, value );*/ jval = cson_value_new_string( value, valLen ); if( NULL == jval ) { rc = cson_rc.AllocError; goto the_end; } if( NULL != (out = strstr(key,"[]")) ) { /* Treat key as an array entry, like PHP does... */ cson_value * freeThisOnErr = NULL; *out = 0; list = NULL; listV = cson_object_get( tgt, key ); if( listV ) { if( ! cson_value_is_array( listV ) ) { /* skip it to avoid hosing a different entry. */ cson_value_free( jval ); jval = NULL; goto next_iter; } } else { /* create a new array to hold the value */ listV = cson_value_new_array(); if( ! listV ) { cson_value_free( jval ); rc = cson_rc.AllocError; goto the_end; } rc = cson_object_set( tgt, key, listV ); if( 0 != rc ) { cson_value_free( listV ); cson_value_free( jval ); goto the_end; } freeThisOnErr = listV; } list = cson_value_get_array( listV ); assert( NULL != list ); rc = cson_array_append( list, jval ); if( 0 != rc ) { cson_value_free( jval ); cson_value_free( freeThisOnErr ); goto the_end; } } else { rc = cson_object_set( tgt, key, jval ); if( 0 != rc ) { cson_value_free( jval ); goto the_end; } } next_iter: head = tail; tail = NULL; } the_end: cson_buffer_reserve( &cx->tmpBuf, 0 ); return rc; } } /** Parses key/value pairs from a QUERY_STRING-formatted string. Returns 0 on success. The "most likely" error condition, in terms of potential code paths, is is an allocation error. TODO: if the key part of any entry ends with "[]", treat it as an array entry, like PHP does. */ static int cson_cgi_parse_query_string( cson_cgi_cx * cx, char const * qstr ) { cson_object * env = NULL; if( !qstr || !*qstr ) return 0; assert(cx); env = cson_cgi_env_get_obj( cx, 'g', 1 ); if( NULL == env ) return cson_rc.AllocError /* guess! */; return cson_cgi_parse_param_list( cx, env, qstr, '&', 1, 0 ); } #if CSON_CGI_ENABLE_POST_FORM_URLENCODED static int cson_cgi_parse_post_urlencoded( cson_cgi_cx * cx, char const * qstr ) { cson_object * env = NULL; if( !qstr || !*qstr ) return 0; assert(cx); env = cson_cgi_env_get_obj( cx, 'p', 1 ); if( NULL == env ) return cson_rc.AllocError /* guess! */; return cson_cgi_parse_param_list( cx, env, qstr, '&', 1, 0 ); } #endif /** Like cson_cgi_parse_query_string(), but expects qstr to be in COOKIE format. */ static int cson_cgi_parse_cookies( cson_cgi_cx * cx, char const * qstr ) { cson_object * env = NULL; if( !qstr || !*qstr ) return 0; assert(cx); env = cson_cgi_env_get_obj(cx, 'c', 1 ); if( NULL == env ) return cson_rc.AllocError /* guess! */; return cson_cgi_parse_param_list( cx, env, qstr, ';', 1, 1 ); } /** Initializes cx->argv.jval and cx->argv.jarr, adds them to the garbage collector, then copies argv to cx->argv.jarr as an array of JSON strings. Returns 0 on success. Results are undefined if argv is not a properly initialized array of NUL-terminated strings with at least argc entries. If argc is 0 or less then cx->argv is still initialized but has a length of 0. After the first call, further arguments are appended to the current list. */ static int cson_cgi_init_argv( cson_cgi_cx * cx, int argc, char const * const * argv ) { int rc = 0; int i; assert( NULL != cx->gc.jobj ); if( cx->argv.jval == NULL ) { cson_value * v = cson_value_new_array(); if( NULL == v ) return cson_rc.AllocError; rc = cson_cgi_gc_add( cx, cson_cgi_keys.ENV_ARGV, v, 1 ); if( 0 != rc ) { /* reminder: v was freed by cson_cgi_gc_add() */ return rc; } cx->argv.jval = v; cx->argv.jarr = cson_value_get_array( v ); assert( NULL != cx->argv.jarr ); } for( i = 0; i < argc; ++i ) { char const * arg = argv[i]; cson_value * vstr = cson_value_new_string( arg ? arg : "", arg ? strlen(arg) : 0 ); if( NULL == vstr ) return cson_rc.AllocError; rc = cson_array_append( cx->argv.jarr, vstr ); if( 0 != rc ) { cson_value_free( vstr ); break; } } return rc; } typedef struct CgiPostReadState_ { FILE * fh; unsigned int len; unsigned int pos; } CgiPostReadState; static int cson_data_source_FILE_n( void * state, void * dest, unsigned int * n ) { if( ! state || !dest || !n ) return cson_rc.ArgError; else { CgiPostReadState * st = (CgiPostReadState *)state; if( st->pos >= st->len ) { *n = 0; return 0; } else if( !*n || ((st->pos + *n) > st->len) ) return cson_rc.RangeError; else { unsigned int rsz = (unsigned int)fread( dest, 1, *n, st->fh ); if( ! rsz ) { *n = rsz; return feof(st->fh) ? 0 : cson_rc.IOError; } else { *n = rsz; st->pos += *n; return 0; } } } } static int cson_cgi_parse_POST_JSON(cson_cgi_cx * cx, FILE * src, unsigned int contentLen) { cson_value * jv = NULL; int rc = 0; CgiPostReadState state; cson_parse_info pinfo = cson_parse_info_empty; assert( 0 != contentLen ); assert( NULL == cx->request.post.jval ); state.fh = src; state.len = contentLen; state.pos = 0; rc = cson_parse( &jv, cson_data_source_FILE_n, &state, NULL, &pinfo ); if( rc ) { #if 0 fprintf(stderr, "%s: Parsing POST as JSON failed: code=%d (%s) line=%u, col=%u\n", __FILE__, rc, cson_rc_string(rc), pinfo.line, pinfo.col ); #endif return rc; } rc = cson_cgi_gc_add( cx, cson_cgi_keys.ENV_POST, jv, 1 ); if( 0 == rc ) { cx->request.post.jval = jv; cx->request.post.jobj = cson_value_get_object( jv ); assert( cx->request.post.jobj && "FIXME: also support an Array as POST data node." ); } return rc; } static int cson_cgi_init_POST(cson_cgi_cx * cx) { if( ! cx || !cx->opt.inStream ) return cson_rc.ArgError; else { FILE * src = cx->opt.inStream; char const * ctype = cson_string_cstr( cson_value_get_string( cson_cgi_getenv( cx, "e", "CONTENT_TYPE" ) ) ); if( NULL == ctype ) return 0; else { char const * clen = cson_string_cstr( cson_value_get_string( cson_cgi_getenv( cx, "e", "CONTENT_LENGTH" ) ) ); if( NULL == clen ) return cson_rc.ArgError; else { char * endpt = NULL; long len = strtol( clen, &endpt, 10 ); if( (endpt && *endpt) || (len<=0) ) return cson_rc.RangeError; #if CSON_CGI_ENABLE_POST_FORM_URLENCODED else if( 0 == strncmp(ctype,"application/x-www-form-urlencoded",33) ) { cson_buffer buf = cson_buffer_empty; int rc = cson_buffer_fill_from( &buf, cson_data_source_FILE, src ); if( rc ) { goto end_clean; return rc; } if( buf.mem && buf.used ) { #if 1 if( strlen((char const *)buf.mem) != buf.used ) { /* assume bad/malicious input. */ rc = cson_rc.RangeError; goto end_clean; } #endif rc = cson_cgi_parse_post_urlencoded( cx, (char const *)buf.mem ); } end_clean: cson_buffer_reserve( &buf, 0 ); return rc; } #endif else if( (0 == strncmp(ctype,"application/json",16)) || (0 == strncmp(ctype,"text/plain",10)) || (0 == strncmp(ctype,"application/javascript",22)) ) { return cson_cgi_parse_POST_JSON(cx, src, len); } else { return cson_rc.TypeError; } } } } } static int cson_cgi_init_config( cson_cgi_cx * cx, char const * fname ) { int rc; cson_value * root = NULL; rc = cson_parse_filename( &root, fname, NULL, NULL ); if( 0 == rc ) { assert( NULL != root ); if( ! cson_value_is_object(root) ) { cson_value_free( root ); rc = cson_rc.TypeError; } else { rc = cson_cgi_gc_add( cx,cson_cgi_keys.ENV_CONFIG, root, 1 ); if( 0 == rc ) { cx->config.jval = root; cx->config.jobj = cson_value_get_object( root ); assert( NULL != cx->config.jobj ); } } } return rc; } static char * cson_cgi_strdup( char const * src ) { size_t const n = src ? strlen(src) : 0; char * rc = src ? (char *)malloc(n+1) : NULL; if( ! rc ) return NULL; memcpy( rc, src, n ); rc[n] = 0; return rc; } /** Writes a 36-byte (plus one NUL byte) UUID value to dest. dest must be at least 37 bytes long. If dest is NULL this function has no side effects. Not thread-safe. */ void cson_cgi_generate_uuid( cson_cgi_cx * cx, char * dest ) { static whuuid_rng rng = { NULL/*rand*/, NULL/*cleanup*/, NULL/*impl*/ #if WHUUID_CONFIG_KEEP_METRICS ,{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}/*distribution*/ #endif }; whuuid_t u = whuuid_t_empty; if( NULL == dest ) return; else if( (NULL==rng.rand) && (NULL != RNG_FILENAME) ) { /* try to open rng file... */ /* FIXME: we're missing a cleanup handler for the RNG_FILENAME case. */ FILE * f = fopen(RNG_FILENAME, "rb"); if( NULL != f ) { rng = whuuid_rng_FILE; rng.impl = f; } } if( NULL == rng.rand ) { /* fall back to LC rng */ extern char ** environ; void * addr; unsigned long seed; rng = whuuid_rng_lcrng; addr = malloc( (((unsigned long)environ) % 13) + 9 ); free(addr) /* but keep the address as a seed value */; seed = (unsigned long)addr * (unsigned long)time(NULL); rng.impl = (void *)seed; } whuuid_fill_rand( &u, &rng ); whuuid_to_string( &u, dest ); } char const * cson_cgi_session_id(cson_cgi_cx * cx) { return cx ? cx->session.id : NULL; } static int cson_cgi_init_session_mgr(cson_cgi_cx * cx) { /* Check for this config structure: { manager:"mgrID", managers:{ mgrID:{ sessionDriver: "back-end-name" (e.g. "cpdo" or "file"), ... back-end-specific options ... }, otherManager: { ... } } */ cson_object const * conf = cson_cgi_env_get_obj(cx, 'f', 0 ); cson_string const * aString; cson_value const * optV = NULL; cson_object const * optObj = NULL; if( NULL == conf ) return 0; assert( cx && !cx->session.mgr ); /* get "manager" part... */ aString = cson_value_get_string( cson_object_get_sub( conf, "session.manager", '.' ) ); if( NULL == aString ) return 0; /* Fetch that manager config ... */ optV = cson_object_get_sub( conf, "session.managers", '.' ); if( optV ) { optV = cson_object_get( cson_value_get_object( optV ), cson_string_cstr( aString ) ); } optObj = cson_value_get_object( optV ); if( ! optObj ) return 0; /* Get the "sessionDriver" part ... */ aString = cson_value_get_string( cson_object_get( optObj, "sessionDriver" ) ); if( NULL == aString ) return 0; return cson_sessmgr_load( cson_string_cstr(aString), &cx->session.mgr, optObj ); } static char const * cson_cgi_get_session_key(cson_cgi_cx * cx) { cson_object const * conf = cson_cgi_env_get_obj( cx, 'f', 0 ); char const * sessKey = CSON_CGI_KEY_SESSION; assert( NULL != cx ); if( conf ) { cson_string const * k = cson_value_get_string( cson_object_get_sub( conf, "session.cookieName", '.' ) ); char const * ck = k ? cson_string_cstr(k) : NULL; if( ck ) sessKey = ck; } return sessKey; } static int cson_cgi_gen_session_id(cson_cgi_cx * cx) { char buf[37] = {0}; if( cx->session.id ) { free( cx->session.id ); cx->session.id = NULL; } cson_cgi_generate_uuid( cx, buf ); cx->session.id = cson_cgi_strdup( buf ); return ( NULL == cx->session.id ) ? cson_rc.AllocError : 0; } static int cson_cgi_init_session( cson_cgi_cx * cx, char const * forceID ) { char const * idstr; char const * sessKey; int rc = cson_cgi_init_session_mgr(cx); if( 0 != rc ) return rc; else if( NULL == cx->session.mgr ) return 0 /* treat as non-fatal error */; sessKey = cson_cgi_get_session_key(cx); assert( sessKey && *sessKey ); /* Try to get the session ID ... */ idstr = (forceID && *forceID) ? forceID : cson_string_cstr( cson_value_get_string( cson_cgi_getenv( cx, "cegp", sessKey ) ) ); if( NULL == idstr ) { /* Generate a session ID but defer creation of the session object until the client does it. If they never use it, we won't bother saving the session. */ rc = cson_cgi_gen_session_id(cx); if( 0 != rc ) return rc; } else { /* try to load the session */ cson_value * sessV = NULL; free( cx->session.id ); cx->session.id = cson_cgi_strdup( idstr ); if( ! cx->session.id ) return cson_rc.AllocError; rc = cx->session.mgr->api->load( cx->session.mgr, &sessV, cx->session.id ); if( (0 == rc) && sessV ) { rc = cson_cgi_gc_add( cx, cson_cgi_keys.ENV_SESSION, sessV, 1 ); if( 0 != rc ) { /* almost certainly an alloc error */ return rc; } cx->session.env.jval = sessV; cx->session.env.jobj = cson_value_get_object( sessV ); } else { if( !forceID || !*forceID ) { /* On load error, assume the session ID is stale. Re-generate it to avoid potential future collisions. This heuristic will cause us intermittent grief when loading does not work for a second or three due to network-related problems. Each time that happens, the caller will lose his session. */ rc = cson_cgi_gen_session_id(cx); if( 0 != rc ) return rc; } } } assert( NULL != cx->session.id ); { /* make sure the session ID is set in the cookies and has an updated expiry time... */ unsigned int expiry = 0; cson_object const * conf; cson_value * jstr = cson_value_new_string( cx->session.id, strlen(cx->session.id) ); if( ! jstr ) return cson_rc.AllocError; conf = cson_cgi_env_get_obj( cx, 'f', 0 ); if( conf ) { expiry = cson_value_get_integer( cson_object_get_sub( conf, "session.cookieLifetimeMinutes", '.' ) ); if( expiry ) expiry *= 60 /* convert to seconds */; } if( ! expiry ) { expiry = (60*60*24); } expiry += (unsigned int)time(NULL); rc = cson_cgi_cookie_set2( cx, sessKey, jstr, NULL, NULL, expiry, 0/*FIXME: set 'secure' option in HTTPS mode.*/, 0/*FIXME: make the httponly flag configurable*/ ); if( 0 != rc ) { cson_value_free( jstr ); if( cson_rc.AllocError == rc ) return rc; rc = 0 /* else treat as non-fatal */; } } return 0; } int cson_cgi_init(cson_cgi_cx * cx, int argc, char const * const * argv, cson_cgi_init_opt * opt ) { int rc = 0; static int hasInited = 0; if( NULL == cx ) return cson_rc.ArgError; else if( NULL != cx->gc.jval ) { /* we've already done this or object was mal-initialized... */ return cson_rc.ArgError; } assert( NULL != CSON_CGI_GETENV_DEFAULT ); #if CSON_CGI_USE_SIGNALS { /* FIXME: use sigaction() instead of signal() */ typedef void (*sighnd)(int); sighnd oldSigPipe; oldSigPipe = signal(SIGPIPE, SIG_IGN) /* to try avoid unclean termination if client disconnects. */; if( SIG_ERR == oldSigPipe ) { return cson_rc.UnknownError; } } #endif if( ! hasInited ) { hasInited = 1; setlocale( LC_ALL, "C" ) /* supposedly important for underlying JSON parser. FIXME: only do this init once! */; } cx->gc.jval = cson_value_new_object(); if( NULL == cx->gc.jval ) { return cson_rc.AllocError; } cx->gc.jobj = cson_value_get_object( cx->gc.jval ); assert( NULL != cx->gc.jobj ); if( opt ) { cx->opt = *opt; } if( NULL == cx->opt.inStream ) cx->opt.inStream = stdin; if( NULL == cx->opt.outStream ) cx->opt.outStream = stdout; if( NULL == cx->opt.errStream ) cx->opt.errStream = stderr; #define CHECKRC if(rc) goto end rc = cson_cgi_import_environ(cx); CHECKRC; rc = cson_cgi_init_argv( cx, argc, argv ); CHECKRC; { /* read config file */ char const * conffile = cx->opt.configFile; if( ! conffile ) { cson_value const * v = cson_cgi_getenv( cx, "e", "CSON_CGI_CONFIG" ); if( v && cson_value_is_string(v) ) { conffile = cson_string_cstr( cson_value_get_string( v ) ); } } if( conffile ) { cson_cgi_init_config( cx, conffile ) /* Ignore error code. TODO: - use argv[0]+".json" as the default config file. */ ; } } rc = cson_cgi_parse_query_string( cx, getenv("QUERY_STRING") ); CHECKRC; rc = cson_cgi_parse_cookies( cx, getenv("HTTP_COOKIE") ); CHECKRC; rc = cson_cgi_init_POST(cx); if( cson_rc.AllocError == rc ) goto end; else rc = 0 /* this can fail for several reasons which are non-fatal. */ ; if( (NULL == opt) ) { /* TODO: read these values from cx->config, if available. */ cx->opt.outOpt.indentation = 1; cx->opt.outOpt.addNewline = 1; cx->opt.outOpt.addSpaceAfterColon = 1; cx->opt.outOpt.indentSingleMemberValues = 1; } rc = cson_cgi_init_session( cx, opt ? opt->sessionID : NULL ) /* ignore non-OOM error codes. Not fatal. */; if( cson_rc.AllocError == rc ) goto end; else rc = 0; /* TODOs: - Read form-urlencoded POST data. (Do this BEFORE restoring the session, so that we can get the session ID from there if needed.) */ end: return rc; #undef CHECKRC } #undef cson_cgi_env_map_empty_m #undef CSON_CGI_USE_SIGNALS #undef RNG_FILENAME /* end file cgi/cson_cgi.c */ |
Added src/cson_amalgamation.h.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 | /* auto-generated! Do not edit! */ /* begin file include/wh/cson/cson.h */ #if !defined(WANDERINGHORSE_NET_CSON_H_INCLUDED) #define WANDERINGHORSE_NET_CSON_H_INCLUDED 1 /*#include <stdint.h> C99: fixed-size int types. */ #include <stdio.h> /* FILE decl */ /** @page page_cson cson JSON API cson (pronounced "season") is an object-oriented C API for generating and consuming JSON (http://www.json.org) data. Its main claim to fame is that it can parse JSON from, and output it to, damned near anywhere. The i/o routines use a callback function to fetch/emit JSON data, allowing clients to easily plug in their own implementations. Implementations are provided for string- and FILE-based i/o. Project home page: http://fossil.wanderinghorse.net/repos/cson Author: Stephan Beal (http://www.wanderinghorse.net/home/stephan/) License: Dual Public Domain/MIT The full license text is at the bottom of the main header file (cson.h). Examples of how to use the library are scattered throughout the API documentation, in the test.c file in the source repo, and in the wiki on the project's home page. */ #if defined(__cplusplus) extern "C" { #endif #if defined(_WIN32) # define CSON_ENABLE_UNIX 0 #else # define CSON_ENABLE_UNIX 1 #endif /** @typedef some_long_int_type cson_int_t Typedef for JSON-like integer types. This is (long long) where feasible, otherwise (long). */ #if (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1) typedef long long cson_int_t; #define CSON_INT_T_SFMT "lld" #define CSON_INT_T_PFMT "lld" #else typedef long cson_int_t; #define CSON_INT_T_SFMT "ld" #define CSON_INT_T_PFMT "ld" #endif /** @def CSON_VOID_PTR_IS_BIG ONLY define this to a true value if you know that (sizeof(cson_int_t) <= sizeof(void*)) If that is the case, cson does not need to dynamically allocate integers. However, enabling this may cause compilation warnings in 32-bit builds even though the code being warned about cannot ever be called. To get around such warnings, when building on a 64-bit environment you can define this to 1 to get "big" integer support. HOWEVER, all clients must also use the same value for this macro. If i knew a halfway reliable way to determine this automatically at preprocessor-time, i would automate this. We might be able to do halfway reliably by looking for a large INT_MAX value? */ #if !defined(CSON_VOID_PTR_IS_BIG) /* Largely taken from http://predef.sourceforge.net/prearch.html See also: http://poshlib.hookatooka.com/poshlib/trac.cgi/browser/posh.h */ # if defined(_WIN64) || defined(__LP64__/*gcc*/) \ || defined(_M_X64) || defined(__amd64__) || defined(__amd64) \ || defined(__x86_64__) || defined(__x86_64) \ || defined(__ia64__) || defined(__ia64) || defined(_IA64) || defined(__IA64__) \ || defined(_M_IA64) \ || defined(__sparc_v9__) || defined(__sparcv9) || defined(_ADDR64) \ || defined(__64BIT__) # define CSON_VOID_PTR_IS_BIG 1 # else # define CSON_VOID_PTR_IS_BIG 0 # endif #endif /** @typedef double_or_long_double cson_double_t This is the type of double value used by the library. It is only lightly tested with long double, and when using long double the memory requirements for such values goes up. */ #if 0 typedef long double cson_double_t; #define CSON_DOUBLE_T_SFMT "Lf" #define CSON_DOUBLE_T_PFMT "Lf" #else typedef double cson_double_t; #define CSON_DOUBLE_T_SFMT "f" #define CSON_DOUBLE_T_PFMT "f" #endif /** @def CSON_INT_T_SFMT scanf()-compatible format token for cson_int_t. */ /** @def CSON_INT_T_PFMT printf()-compatible format token for cson_int_t. */ /** @def CSON_DOUBLE_T_SFMT scanf()-compatible format token for cson_double_t. */ /** @def CSON_DOUBLE_T_PFMT printf()-compatible format token for cson_double_t. */ typedef struct cson_value cson_value; /** @struct cson_value The core value type of this API. It is opaque to clients, and only the cson public API should be used for setting or inspecting their values. This class is opaque because stack-based usage can easily cause leaks if one does not intimately understand the underlying internal memory management (which sometimes changes). It is (as of 20110323) legal to insert a given value instance into multiple containers (they will share ownership using reference counting) as long as those insertions do not cause cycles. However, be very aware that such value re-use uses a reference to the original copy, meaning that if its value is changed once, it is changed everywhere. Also beware that multi-threaded write operations on such references leads to undefined behaviour. PLEASE read the ACHTUNGEN below... ACHTUNG #1: cson_values MUST NOT form cycles (e.g. via object or array entries). Not abiding th Holy Law Of No Cycles will lead to double-frees and the like (i.e. undefined behaviour, likely crashes due to infinite recursion or stepping on invalid (freed) pointers). ACHTUNG #2: ALL cson_values returned as non-const cson_value pointers from any public functions in the cson API are to be treated as if they are heap-allocated, and MUST be freed by client by doing ONE of: - Passing it to cson_value_free(). - Adding it to an Object or Array, in which case the object/array takes over ownership. As of 20110323, a value may be inserted into a single container multiple times, or into multiple containers, in which case they all share ownership (via reference counting) of the original value (meaning any changes to it are visible in all references to it). Each call to cson_value_new_xxx() MUST eventually be followed up by one of those options. Some cson_value_new_XXX() implementations do not actually allocate memory, but this is an internal implementation detail. Client code MUST NOT rely on this behaviour and MUST treat each object returned by such a function as if it was a freshly-allocated copy (even if their pointer addresses are the same). ACHTUNG #3: Note that ACHTUNG #2 tells us that we must always free (or transfer ownership of) all pointers returned bycson_value_new_xxx(), but that two calls to (e.g.) cson_value_new_bool(1) will (or might) return the same address. The client must not rely on the "non-allocation" policy of such special cases, and must pass each returned value to cson_value_free(), even if two of them have the same address. Some special values (e.g. null, true, false, integer 0, double 0.0, and empty strings) use shared copies and in other places reference counting is used internally to figure out when it is safe to destroy an object. @see cson_value_new_array() @see cson_value_new_object() @see cson_value_new_string() @see cson_value_new_integer() @see cson_value_new_double() @see cson_value_new_bool() @see cson_value_true() @see cson_value_false() @see cson_value_null() @see cson_value_free() */ /** @var cson_rc This object defines the error codes used by cson. Library routines which return int values almost always return a value from this structure. None of the members in this struct have published values except for the OK member, which has the value 0. All other values might be incidentally defined where clients can see them, but the numbers might change from release to release, so clients should only use the symbolic names. Client code is expected to access these values via the shared cson_rc object, and use them as demonstrated here: @code int rc = cson_some_func(...); if( 0 == rc ) {...success...} else if( cson_rc.ArgError == rc ) { ... some argument was wrong ... } else if( cson_rc.AllocError == rc ) { ... allocation error ... } ... @endcode The entries named Parse_XXX are generally only returned by cson_parse() and friends. */ /** @struct cson_rc_ See \ref cson_rc for details. */ static const struct cson_rc_ { /** The generic success value. Guaranteed to be 0. */ const int OK; /** Signifies an error in one or more arguments (e.g. NULL where it is not allowed). */ const int ArgError; /** Signifies that some argument is not in a valid range. */ const int RangeError; /** Signifies that some argument is not of the correct logical cson type. */ const int TypeError; /** Signifies an input/ouput error. */ const int IOError; /** Signifies an out-of-memory error. */ const int AllocError; /** Signifies that the called code is "NYI" (Not Yet Implemented). */ const int NYIError; /** Signifies that an internal error was triggered. If it happens, please report this as a bug! */ const int InternalError; /** Signifies that the called operation is not supported in the current environment. e.g. missing support from 3rd-party or platform-specific code. */ const int UnsupportedError; /** Signifies that the request resource could not be found. */ const int NotFoundError; /** Signifies an unknown error, possibly because an underlying 3rd-party API produced an error and we have no other reasonable error code to convert it to. */ const int UnknownError; /** Signifies that the parser found an unexpected character. */ const int Parse_INVALID_CHAR; /** Signifies that the parser found an invalid keyword (possibly an unquoted string). */ const int Parse_INVALID_KEYWORD; /** Signifies that the parser found an invalid escape sequence. */ const int Parse_INVALID_ESCAPE_SEQUENCE; /** Signifies that the parser found an invalid Unicode character sequence. */ const int Parse_INVALID_UNICODE_SEQUENCE; /** Signifies that the parser found an invalid numeric token. */ const int Parse_INVALID_NUMBER; /** Signifies that the parser reached its maximum defined parsing depth before finishing the input. */ const int Parse_NESTING_DEPTH_REACHED; /** Signifies that the parser found an unclosed object or array. */ const int Parse_UNBALANCED_COLLECTION; /** Signifies that the parser found an key in an unexpected place. */ const int Parse_EXPECTED_KEY; /** Signifies that the parser expected to find a colon but found none (e.g. between keys and values in an object). */ const int Parse_EXPECTED_COLON; } cson_rc = { 0/*OK*/, 1/*ArgError*/, 2/*RangeError*/, 3/*TypeError*/, 4/*IOError*/, 5/*AllocError*/, 6/*NYIError*/, 7/*InternalError*/, 8/*UnsupportedError*/, 9/*NotFoundError*/, 10/*UnknownError*/, 11/*Parse_INVALID_CHAR*/, 12/*Parse_INVALID_KEYWORD*/, 13/*Parse_INVALID_ESCAPE_SEQUENCE*/, 14/*Parse_INVALID_UNICODE_SEQUENCE*/, 15/*Parse_INVALID_NUMBER*/, 16/*Parse_NESTING_DEPTH_REACHED*/, 17/*Parse_UNBALANCED_COLLECTION*/, 18/*Parse_EXPECTED_KEY*/, 19/*Parse_EXPECTED_COLON*/ }; /** Returns the string form of the cson_rc code corresponding to rc, or some unspecified, non-NULL string if it is an unknown code. The returned bytes are static and do not changing during the lifetime of the application. */ char const * cson_rc_string(int rc); /** @struct cson_parse_opt Client-configurable options for the cson_parse() family of functions. */ struct cson_parse_opt { /** Maximum object/array depth to traverse. */ unsigned short maxDepth; /** Whether or not to allow C-style comments. Do not rely on this option being available. If the underlying parser is replaced, this option might no longer be supported. */ char allowComments; }; typedef struct cson_parse_opt cson_parse_opt; /** Empty-initialized cson_parse_opt object. */ #define cson_parse_opt_empty_m { 25/*maxDepth*/, 0/*allowComments*/} /** A class for holding JSON parser information. It is primarily intended for finding the position of a parse error. */ struct cson_parse_info { /** 1-based line number. */ unsigned int line; /** 0-based column number. */ unsigned int col; /** Length, in bytes. */ unsigned int length; /** Error code of the parse run (0 for no error). */ int errorCode; /** The total number of object keys successfully processed by the parser. */ unsigned int totalKeyCount; /** The total number of object/array values successfully processed by the parser, including the root node. */ unsigned int totalValueCount; }; typedef struct cson_parse_info cson_parse_info; /** Empty-initialized cson_parse_info object. */ #define cson_parse_info_empty_m {1/*line*/,\ 0/*col*/, \ 0/*length*/, \ 0/*errorCode*/, \ 0/*totalKeyCount*/, \ 0/*totalValueCount*/ \ } /** Empty-initialized cson_parse_info object. */ extern const cson_parse_info cson_parse_info_empty; /** Empty-initialized cson_parse_opt object. */ extern const cson_parse_opt cson_parse_opt_empty; /** Client-configurable options for the cson_output() family of functions. */ struct cson_output_opt { /** Specifies how to indent (or not) output. The values are: (0) == no extra indentation. (1) == 1 TAB character for each level. (>1) == that number of SPACES for each level. */ unsigned char indentation; /** Maximum object/array depth to traverse. Traversing deeply can be indicative of cycles in the object/array tree, and this value is used to figure out when to abort the traversal. */ unsigned short maxDepth; /** If true, a newline will be added to generated output, else not. */ char addNewline; /** If true, a space will be added after the colon operator in objects' key/value pairs. */ char addSpaceAfterColon; /** If set to 1 then objects/arrays containing only a single value will not indent an extra level for that value (but will indent on subsequent levels if that value contains multiple values). */ char indentSingleMemberValues; /** The JSON format allows, but does not require, JSON generators to backslash-escape forward slashes. This option enables/disables that feature. According to JSON's inventor, Douglas Crockford: <quote> It is allowed, not required. It is allowed so that JSON can be safely embedded in HTML, which can freak out when seeing strings containing "</". JSON tolerates "<\/" for this reason. </quote> (from an email on 2011-04-08) The default value is 0 (because it's just damned ugly). */ char escapeForwardSlashes; }; typedef struct cson_output_opt cson_output_opt; /** Empty-initialized cson_output_opt object. */ #define cson_output_opt_empty_m { 0/*indentation*/,\ 25/*maxDepth*/, \ 0/*addNewline*/, \ 0/*addSpaceAfterColon*/, \ 0/*indentSingleMemberValues*/, \ 0/*escapeForwardSlashes*/ \ } /** Empty-initialized cson_output_opt object. */ extern const cson_output_opt cson_output_opt_empty; /** Typedef for functions which act as an input source for the cson JSON parser. The arguments are: - state: implementation-specific state needed by the function. - n: when called, *n will be the number of bytes the function should read and copy to dest. The function MUST NOT copy more than *n bytes to dest. Before returning, *n must be set to the number of bytes actually copied to dest. If that number is smaller than the original *n value, the input is assumed to be completed (thus this is not useful with non-blocking readers). - dest: the destination memory to copy the data do. Must return 0 on success, non-0 on error (preferably a value from cson_rc). The parser allows this routine to return a partial character from a UTF multi-byte character. The input routine does not need to concern itself with character boundaries. */ typedef int (*cson_data_source_f)( void * state, void * dest, unsigned int * n ); /** Typedef for functions which act as an output destination for generated JSON. The arguments are: - state: implementation-specific state needed by the function. - n: the length, in bytes, of src. - src: the source bytes which the output function should consume. The src pointer will be invalidated shortly after this function returns, so the implementation must copy or ignore the data, but not hold a copy of the src pointer. Must return 0 on success, non-0 on error (preferably a value from cson_rc). These functions are called relatively often during the JSON-output process, and should try to be fast. */ typedef int (*cson_data_dest_f)( void * state, void const * src, unsigned int n ); /** Reads JSON-formatted string data (in ASCII, UTF8, or UTF16), using the src function to fetch all input. This function fetches each input character from the source function, which is calls like src(srcState, buffer, bufferSize), and processes them. If anything is not JSON-kosher then this function fails and returns one of the non-0 cson_rc codes. This function is only intended to read root nodes of a JSON tree, either a single object or a single array, containing any number of child elements. On success, *tgt is assigned the value of the root node of the JSON input, and the caller takes over ownership of that memory. On error, *tgt is not modified and the caller need not do any special cleanup, except possibly for the input source. The opt argument may point to an initialized cson_parse_opt object which contains any settings the caller wants. If it is NULL then default settings (the values defined in cson_parse_opt_empty) are used. The info argument may be NULL. If it is not NULL then the parser populates it with information which is useful in error reporting. Namely, it contains the line/column of parse errors. The srcState argument is ignored by this function but is passed on to src, so any output-destination-specific state can be stored there and accessed via the src callback. Non-parse error conditions include: - (!tgt) or !src: cson_rc.ArgError - cson_rc.AllocError can happen at any time during the input phase Here's a complete example of using a custom input source: @code // Internal type to hold state for a JSON input string. typedef struct { char const * str; // start of input string char const * pos; // current internal cursor position char const * end; // logical EOF (one-past-the-end) } StringSource; // cson_data_source_f() impl which uses StringSource. static int cson_data_source_StringSource( void * state, void * dest, unsigned int * n ) { StringSource * ss = (StringSource*) state; unsigned int i; unsigned char * tgt = (unsigned char *)dest; if( ! ss || ! n || !dest ) return cson_rc.ArgError; else if( !*n ) return cson_rc.RangeError; for( i = 0; (i < *n) && (ss->pos < ss->end); ++i, ++ss->pos, ++tgt ) { *tgt = *ss->pos; } *n = i; return 0; } ... // Now use StringSource together with cson_parse() StringSource ss; cson_value * root = NULL; char const * json = "{\"k1\":123}"; ss.str = ss.pos = json; ss.end = json + strlen(json); int rc = cson_parse( &root, cson_data_source_StringSource, &ss, NULL, NULL ); @endcode It is recommended that clients wrap such utility code into type-safe wrapper functions which also initialize the internal state object and check the user-provided parameters for legality before passing them on to cson_parse(). For examples of this, see cson_parse_FILE() or cson_parse_string(). TODOs: - Buffer the input in larger chunks. We currently read byte-by-byte, but i'm too tired to write/test the looping code for the buffering. @see cson_parse_FILE() @see cson_parse_string() */ int cson_parse( cson_value ** tgt, cson_data_source_f src, void * srcState, cson_parse_opt const * opt, cson_parse_info * info ); /** A cson_data_source_f() implementation which requires the state argument to be a readable (FILE*) handle. */ int cson_data_source_FILE( void * state, void * dest, unsigned int * n ); /** Equivalent to cson_parse( tgt, cson_data_source_FILE, src, opt ). @see cson_parse_filename() */ int cson_parse_FILE( cson_value ** tgt, FILE * src, cson_parse_opt const * opt, cson_parse_info * info ); /** Convenience wrapper around cson_parse_FILE() which opens the given filename. Returns cson_rc.IOError if the file cannot be opened. @see cson_parse_FILE() */ int cson_parse_filename( cson_value ** tgt, char const * src, cson_parse_opt const * opt, cson_parse_info * info ); /** Uses an internal helper class to pass src through cson_parse(). See that function for the return value and argument semantics. src must be a string containing JSON code, at least len bytes long, and the parser will attempt to parse exactly len bytes from src. If len is less than 2 (the minimum length of a legal top-node JSON object) then cson_rc.RangeError is returned. */ int cson_parse_string( cson_value ** tgt, char const * src, unsigned int len, cson_parse_opt const * opt, cson_parse_info * info ); /** Outputs the given value as a JSON-formatted string, sending all output to the given callback function. It is intended for top-level objects or arrays, but can be used with any cson_value. If opt is NULL then default options (the values defined in cson_output_opt_empty) are used. If opt->maxDepth is exceeded while traversing the value tree, cson_rc.RangeError is returned. The destState parameter is ignored by this function and is passed on to the dest function. Returns 0 on success. On error, any amount of output might have been generated before the error was triggered. Example: @code int rc = cson_output( myValue, cson_data_dest_FILE, stdout, NULL ); // basically equivalent to: cson_output_FILE( myValue, stdout, NULL ); // but note that cson_output_FILE() actually uses different defaults // for the output options. @endcode */ int cson_output( cson_value const * src, cson_data_dest_f dest, void * destState, cson_output_opt const * opt ); /** A cson_data_dest_f() implementation which requires the state argument to be a writable (FILE*) handle. */ int cson_data_dest_FILE( void * state, void const * src, unsigned int n ); /** Almost equivalent to cson_output( src, cson_data_dest_FILE, dest, opt ), with one minor difference: if opt is NULL then the default options always include the addNewline option, since that is normally desired for FILE output. @see cson_output_filename() */ int cson_output_FILE( cson_value const * src, FILE * dest, cson_output_opt const * opt ); /** Convenience wrapper around cson_output_FILE() which writes to the given filename, destroying any existing contents. Returns cson_rc.IOError if the file cannot be opened. @see cson_output_FILE() */ int cson_output_filename( cson_value const * src, char const * dest, cson_output_opt const * fmt ); /** Returns true if v is null, v->api is NULL, or v holds the special undefined value. */ char cson_value_is_undef( cson_value const * v ); /** Returns true if v contains a null value. */ char cson_value_is_null( cson_value const * v ); /** Returns true if v contains a bool value. */ char cson_value_is_bool( cson_value const * v ); /** Returns true if v contains an integer value. */ char cson_value_is_integer( cson_value const * v ); /** Returns true if v contains a double value. */ char cson_value_is_double( cson_value const * v ); /** Returns true if v contains a number (double, integer) value. */ char cson_value_is_number( cson_value const * v ); /** Returns true if v contains a string value. */ char cson_value_is_string( cson_value const * v ); /** Returns true if v contains an array value. */ char cson_value_is_array( cson_value const * v ); /** Returns true if v contains an object value. */ char cson_value_is_object( cson_value const * v ); /** @struct cson_object cson_object is an opaque handle to an Object value. They are used like: @code cson_object * obj = cson_value_get_object(myValue); ... @endcode They can be created like: @code cson_value * objV = cson_value_new_object(); cson_object * obj = cson_value_get_object(objV); // obj is owned by objV and objV must eventually be freed // using cson_value_free() or added to a container // object/array (which transfers ownership to that container). @endcode @see cson_value_new_object() @see cson_value_get_object() @see cson_value_free() */ typedef struct cson_object cson_object; /** @struct cson_array cson_array is an opaque handle to an Array value. They are used like: @code cson_array * obj = cson_value_get_array(myValue); ... @endcode They can be created like: @code cson_value * arV = cson_value_new_array(); cson_array * ar = cson_value_get_array(arV); // ar is owned by arV and arV must eventually be freed // using cson_value_free() or added to a container // object/array (which transfers ownership to that container). @endcode @see cson_value_new_array() @see cson_value_get_array() @see cson_value_free() */ typedef struct cson_array cson_array; /** @struct cson_string cson-internal string type, opaque to client code. Strings in cson are immutable and allocated only by library internals, never directly by client code. The actual string bytes are to be allocated together in the same memory chunk as the cson_string object, which saves us 1 malloc() and 1 pointer member in this type (because we no longer have a direct pointer to the memory). Potential TODOs: @see cson_string_cstr() */ typedef struct cson_string cson_string; /** Converts the given value to a boolean, using JavaScript semantics depending on the concrete type of val: undef or null: false boolean: same integer, double: 0 or 0.0 == false, else true object, array: true Returns 0 on success and assigns *v (if v is not NULL) to either 0 or 1. On error (val is NULL) then v is not modified. */ int cson_value_fetch_bool( cson_value const * val, char * v ); /** Similar to cson_value_fetch_bool(), but fetches an integer value. The conversion, if any, depends on the concrete type of val: NULL, null, undefined: *v is set to 0 and 0 is returned. string, object, array: *v is set to 0 and cson_rc.TypeError is returned. The error may normally be safely ignored, but it is provided for those wanted to know whether a direct conversion was possible. integer: *v is set to the int value and 0 is returned. double: *v is set to the value truncated to int and 0 is returned. */ int cson_value_fetch_integer( cson_value const * val, cson_int_t * v ); /** The same conversions and return values as cson_value_fetch_integer(), except that the roles of int/double are swapped. */ int cson_value_fetch_double( cson_value const * val, cson_double_t * v ); /** If cson_value_is_string(val) then this function assigns *str to the contents of the string. str may be NULL, in which case this function functions like cson_value_is_string() but returns 0 on success. Returns 0 if val is-a string, else non-0, in which case *str is not modified. The bytes are owned by the given value and may be invalidated in any of the following ways: - The value is cleaned up or freed. - An array or object containing the value peforms a re-allocation (it shrinks or grows). And thus the bytes should be consumed before any further operations on val or any container which holds it. Note that this routine does not convert non-String values to their string representations. (Adding that ability would add more overhead to every cson_value instance.) */ int cson_value_fetch_string( cson_value const * val, cson_string const ** str ); /** If cson_value_is_object(val) then this function assigns *obj to the underlying object value and returns 0, otherwise non-0 is returned and *obj is not modified. obj may be NULL, in which case this function works like cson_value_is_object() but with inverse return value semantics (0==success) (and it's a few CPU cycles slower). The *obj pointer is owned by val, and will be invalidated when val is cleaned up. Achtung: for best results, ALWAYS pass a pointer to NULL as the second argument, e.g.: @code cson_object * obj = NULL; int rc = cson_value_fetch_object( val, &obj ); // Or, more simply: obj = cson_value_get_object( val ); @endcode @see cson_value_get_object() */ int cson_value_fetch_object( cson_value const * val, cson_object ** obj ); /** Identical to cson_value_fetch_object(), but works on array values. @see cson_value_get_array() */ int cson_value_fetch_array( cson_value const * val, cson_array ** tgt ); /** Simplified form of cson_value_fetch_bool(). Returns 0 if val is NULL. */ char cson_value_get_bool( cson_value const * val ); /** Simplified form of cson_value_fetch_integer(). Returns 0 if val is NULL. */ cson_int_t cson_value_get_integer( cson_value const * val ); /** Simplified form of cson_value_fetch_double(). Returns 0.0 if val is NULL. */ cson_double_t cson_value_get_double( cson_value const * val ); /** Simplified form of cson_value_fetch_string(). Returns NULL if val is-not-a string value. */ cson_string const * cson_value_get_string( cson_value const * val ); /** Returns a pointer to the NULL-terminated string bytes of str. The bytes are owned by string and will be invalided when it is cleaned up. If str is NULL then NULL is returned. @see cson_string_length_bytes() @see cson_value_get_string() */ char const * cson_string_cstr( cson_string const * str ); /** Convenience function which returns the string bytes of the given value if it is-a string, otherwise it returns NULL. Note that this does no conversion of non-string types to strings. Equivalent to cson_string_cstr(cson_value_get_string(val)). */ char const * cson_value_get_cstr( cson_value const * val ); /** Equivalent to cson_string_cmp_cstr_n(lhs, cson_string_cstr(rhs), cson_string_length_bytes(rhs)). */ int cson_string_cmp( cson_string const * lhs, cson_string const * rhs ); /** Compares lhs to rhs using memcmp()/strcmp() semantics. Generically speaking it returns a negative number if lhs is less-than rhs, 0 if they are equivalent, or a positive number if lhs is greater-than rhs. It has the following rules for equivalence: - The maximum number of bytes compared is the lesser of rhsLen and the length of lhs. If the strings do not match, but compare equal up to the just-described comparison length, the shorter string is considered to be less-than the longer one. - If lhs and rhs are both NULL, or both have a length of 0 then they will compare equal. - If lhs is null/length-0 but rhs is not then lhs is considered to be less-than rhs. - If rhs is null/length-0 but lhs is not then rhs is considered to be less-than rhs. - i have no clue if the results are exactly correct for UTF strings. */ int cson_string_cmp_cstr_n( cson_string const * lhs, char const * rhs, unsigned int rhsLen ); /** Equivalent to cson_string_cmp_cstr_n( lhs, rhs, (rhs&&*rhs)?strlen(rhs):0 ). */ int cson_string_cmp_cstr( cson_string const * lhs, char const * rhs ); /** Returns the length, in bytes, of str, or 0 if str is NULL. This is an O(1) operation. TODO: add cson_string_length_chars() (is O(N) unless we add another member to store the char length). @see cson_string_cstr() */ unsigned int cson_string_length_bytes( cson_string const * str ); /** Returns the number of UTF8 characters in str. This value will be at most as long as cson_string_length_bytes() for the same string, and less if it has multi-byte characters. Returns 0 if str is NULL. */ unsigned int cson_string_length_utf8( cson_string const * str ); /** Like cson_value_get_string(), but returns a copy of the underying string bytes, which the caller owns and must eventually free using free(). */ char * cson_value_get_string_copy( cson_value const * val ); /** Simplified form of cson_value_fetch_object(). Returns NULL if val is-not-a object value. */ cson_object * cson_value_get_object( cson_value const * val ); /** Simplified form of cson_value_fetch_array(). Returns NULL if val is-not-a array value. */ cson_array * cson_value_get_array( cson_value const * val ); /** Const-correct form of cson_value_get_array(). */ cson_array const * cson_value_get_array_c( cson_value const * val ); /** If ar is-a array and is at least (pos+1) entries long then *v (if v is not NULL) is assigned to the value at that position (which may be NULL). Ownership of the *v return value is unchanged by this call. (The containing array may share ownership of the value with other containers.) If pos is out of range, non-0 is returned and *v is not modified. If v is NULL then this function returns 0 if pos is in bounds, but does not otherwise return a value to the caller. */ int cson_array_value_fetch( cson_array const * ar, unsigned int pos, cson_value ** v ); /** Simplified form of cson_array_value_fetch() which returns NULL if ar is NULL, pos is out of bounds or if ar has no element at that position. */ cson_value * cson_array_get( cson_array const * ar, unsigned int pos ); /** Ensures that ar has allocated space for at least the given number of entries. This never shrinks the array and never changes its logical size, but may pre-allocate space in the array for storing new (as-yet-unassigned) values. Returns 0 on success, or non-zero on error: - If ar is NULL: cson_rc.ArgError - If allocation fails: cson_rc.AllocError */ int cson_array_reserve( cson_array * ar, unsigned int size ); /** If ar is not NULL, sets *v (if v is not NULL) to the length of the array and returns 0. Returns cson_rc.ArgError if ar is NULL. */ int cson_array_length_fetch( cson_array const * ar, unsigned int * v ); /** Simplified form of cson_array_length_fetch() which returns 0 if ar is NULL. */ unsigned int cson_array_length_get( cson_array const * ar ); /** Sets the given index of the given array to the given value. If ar already has an item at that index then it is cleaned up and freed before inserting the new item. ar is expanded, if needed, to be able to hold at least (ndx+1) items, and any new entries created by that expansion are empty (NULL values). On success, 0 is returned and ownership of v is transfered to ar. On error ownership of v is NOT modified, and the caller may still need to clean it up. For example, the following code will introduce a leak if this function fails: @code cson_array_append( myArray, cson_value_new_integer(42) ); @endcode Because the value created by cson_value_new_integer() has no owner and is not cleaned up. The "more correct" way to do this is: @code cson_value * v = cson_value_new_integer(42); int rc = cson_array_append( myArray, v ); if( 0 != rc ) { cson_value_free( v ); ... handle error ... } @endcode */ int cson_array_set( cson_array * ar, unsigned int ndx, cson_value * v ); /** Appends the given value to the given array, transfering ownership of v to ar. On error, ownership of v is not modified. Ownership of ar is never changed by this function. This is functionally equivalent to cson_array_set(ar,cson_array_length_get(ar),v), but this implementation has slightly different array-preallocation policy (it grows more eagerly). Returns 0 on success, non-zero on error. Error cases include: - ar or v are NULL: cson_rc.ArgError - Array cannot be expanded to hold enough elements: cson_rc.AllocError. - Appending would cause a numeric overlow in the array's size: cson_rc.RangeError. (However, you'll get an AllocError long before that happens!) On error ownership of v is NOT modified, and the caller may still need to clean it up. See cson_array_set() for the details. */ int cson_array_append( cson_array * ar, cson_value * v ); /** Creates a new cson_value from the given boolean value. Ownership of the new value is passed to the caller, who must eventually either free the value using cson_value_free() or inserting it into a container (array or object), which transfers ownership to the container. See the cson_value class documentation for more details. Returns NULL on allocation error. */ cson_value * cson_value_new_bool( char v ); /** Returns the special JSON "null" value. When outputing JSON, its string representation is "null" (without the quotes). See cson_value_new_bool() for notes regarding the returned value's memory. */ cson_value * cson_value_null(); /** Equivalent to cson_value_new_bool(1). */ cson_value * cson_value_true(); /** Equivalent to cson_value_new_bool(0). */ cson_value * cson_value_false(); /** Semantically the same as cson_value_new_bool(), but for integers. */ cson_value * cson_value_new_integer( cson_int_t v ); /** Semantically the same as cson_value_new_bool(), but for doubles. */ cson_value * cson_value_new_double( cson_double_t v ); /** Semantically the same as cson_value_new_bool(), but for strings. This creates a JSON value which copies the first n bytes of str. The string will automatically be NUL-terminated. Note that if str is NULL or n is 0, this function still returns non-NULL value representing that empty string. Returns NULL on allocation error. See cson_value_new_bool() for important information about the returned memory. */ cson_value * cson_value_new_string( char const * str, unsigned int n ); /** Allocates a new "object" value and transfers ownership of it to the caller. It must eventually be destroyed, by the caller or its owning container, by passing it to cson_value_free(). Returns NULL on allocation error. Post-conditions: cson_value_is_object(value) will return true. @see cson_value_new_array() @see cson_value_free() */ cson_value * cson_value_new_object(); /** Allocates a new "array" value and transfers ownership of it to the caller. It must eventually be destroyed, by the caller or its owning container, by passing it to cson_value_free(). Returns NULL on allocation error. Post-conditions: cson_value_is_array(value) will return true. @see cson_value_new_object() @see cson_value_free() */ cson_value * cson_value_new_array(); /** Frees any resources owned by v, then frees v. If v is a container type (object or array) its children are also freed (recursively). If v is NULL, this is a no-op. This function decrements a reference count and only destroys the value if its reference count drops to 0. Reference counts are increased by either inserting the value into a container or via cson_value_add_reference(). Even if this function does not immediately destroy the value, the value must be considered, from the perspective of that client code, to have been destroyed/invalidated by this call. @see cson_value_new_object() @see cson_value_new_array() @see cson_value_add_reference() */ void cson_value_free(cson_value * v); /** Functionally similar to cson_array_set(), but uses a string key as an index. Like arrays, if a value already exists for the given key, it is destroyed by this function before inserting the new value. If v is NULL then this call is equivalent to cson_object_unset(obj,key). Note that (v==NULL) is treated differently from v having the special null value. In the latter case, the key is set to the special null value. The key may be encoded as ASCII or UTF8. Results are undefined with other encodings, and the errors won't show up here, but may show up later, e.g. during output. Returns 0 on success, non-0 on error. It has the following error cases: - cson_rc.ArgError: obj or key are NULL or strlen(key) is 0. - cson_rc.AllocError: an out-of-memory error On error ownership of v is NOT modified, and the caller may still need to clean it up. For example, the following code will introduce a leak if this function fails: @code cson_object_set( myObj, "foo", cson_value_new_integer(42) ); @endcode Because the value created by cson_value_new_integer() has no owner and is not cleaned up. The "more correct" way to do this is: @code cson_value * v = cson_value_new_integer(42); int rc = cson_object_set( myObj, "foo", v ); if( 0 != rc ) { cson_value_free( v ); ... handle error ... } @endcode Potential TODOs: - Add an overload which takes a cson_value key instead. To get any value out of that we first need to be able to convert arbitrary value types to strings. We could simply to-JSON them and use those as keys. */ int cson_object_set( cson_object * obj, char const * key, cson_value * v ); /** Removes a property from an object. If obj contains the given key, it is removed and 0 is returned. If it is not found, cson_rc.NotFoundError is returned (which can normally be ignored by client code). cson_rc.ArgError is returned if obj or key are NULL or key has a length of 0. Returns 0 if the given key is found and removed. This is functionally equivalent calling cson_object_set(obj,key,NULL). */ int cson_object_unset( cson_object * obj, char const * key ); /** Searches the given object for a property with the given key. If found, it is returned. If no match is found, or any arguments are NULL, NULL is returned. The returned object is owned by obj, and may be invalidated by ANY operations which change obj's property list (i.e. add or remove properties). FIXME: allocate the key/value pairs like we do for cson_array, to get improve the lifetimes of fetched values. @see cson_object_fetch_sub() @see cson_object_get_sub() */ cson_value * cson_object_get( cson_object const * obj, char const * key ); /** Similar to cson_object_get(), but removes the value from the parent object's ownership. If no item is found then NULL is returned, else the object (now owned by the caller or possibly shared with other containers) is returned. Returns NULL if either obj or key are NULL or key has a length of 0. This function reduces the returned value's reference count but has the specific property that it does not treat refcounts 0 and 1 identically, meaning that the returned object may have a refcount of 0. This behaviour works around a corner-case where we want to extract a child element from its parent and then destroy the parent (which leaves us in an undesireable (normally) reference count state). */ cson_value * cson_object_take( cson_object * obj, char const * key ); /** Fetches a property from a child (or [great-]*grand-child) object. obj is the object to search. path is a delimited string, where the delimiter is the given separator character. This function searches for the given path, starting at the given object and traversing its properties as the path specifies. If a given part of the path is not found, then this function fails with cson_rc.NotFoundError. If it finds the given path, it returns the value by assiging *tgt to it. If tgt is NULL then this function has no side-effects but will return 0 if the given path is found within the object, so it can be used to test for existence without fetching it. Returns 0 if it finds an entry, cson_rc.NotFoundError if it finds no item, and any other non-zero error code on a "real" error. Errors include: - obj or path are NULL: cson_rc.ArgError - separator is 0, or path is an empty string or contains only separator characters: cson_rc.RangeError - There is an upper limit on how long a single path component may be (some "reasonable" internal size), and cson_rc.RangeError is returned if that length is violated. Limitations: - It has no way to fetch data from arrays this way. i could imagine, e.g., a path of "subobj.subArray.0" for subobj.subArray[0], or "0.3.1" for [0][3][1]. But i'm too lazy/tired to add this. Example usage: Assume we have a JSON structure which abstractly looks like: @code {"subobj":{"subsubobj":{"myValue":[1,2,3]}}} @endcode Out goal is to get the value of myValue. We can do that with: @code cson_value * v = NULL; int rc = cson_object_fetch_sub( object, &v, "subobj.subsubobj.myValue", '.' ); @endcode Note that because keys in JSON may legally contain a '.', the separator must be specified by the caller. e.g. the path "subobj/subsubobj/myValue" with separator='/' is equivalent the path "subobj.subsubobj.myValue" with separator='.'. The value of 0 is not legal as a separator character because we cannot distinguish that use from the real end-of-string without requiring the caller to also pass in the length of the string. Multiple successive separators in the list are collapsed into a single separator for parsing purposes. e.g. the path "a...b...c" (separator='.') is equivalent to "a.b.c". @see cson_object_get_sub() */ int cson_object_fetch_sub( cson_object const * obj, cson_value ** tgt, char const * path, char separator ); /** Convenience form of cson_object_fetch_sub() which returns NULL if the given item is not found. */ cson_value * cson_object_get_sub( cson_object const * obj, char const * path, char sep ); /** An iterator type for traversing object properties. Its values must be considered private, not to be touched by client code. @see cson_object_iter_init() @see cson_object_iter_next() */ struct cson_object_iterator { /** @internal The underlying object. */ cson_object const * obj; /** @internal Current position in the property list. */ unsigned int pos; }; typedef struct cson_object_iterator cson_object_iterator; /** Empty-initialized cson_object_iterator object. */ #define cson_object_iterator_empty_m {NULL/*obj*/,0/*pos*/} /** Empty-initialized cson_object_iterator object. */ extern const cson_object_iterator cson_object_iterator_empty; /** Initializes the given iterator to point at the start of obj's properties. Returns 0 on success or cson_rc.ArgError if !obj or !iter. obj must outlive iter, or results are undefined. Results are also undefined if obj is modified while the iterator is active. @see cson_object_iter_next() */ int cson_object_iter_init( cson_object const * obj, cson_object_iterator * iter ); /** @struct cson_kvp This class represents a key/value pair and is used for storing object properties. It is opaque to client code, and the public API only uses this type for purposes of iterating over cson_object properties using the cson_object_iterator interfaces. */ typedef struct cson_kvp cson_kvp; /** Returns the next property from the given iterator's object, or NULL if the end of the property list as been reached. Note that the order of object properties is undefined by the API, and may change from version to version. The returned memory belongs to the underlying object and may be invalidated by any changes to that object. Example usage: @code cson_object_iterator it; cson_object_iter_init( myObject, &it ); // only fails if either arg is 0 cson_kvp * kvp; cson_string const * key; cson_value const * val; while( (kvp = cson_object_iter_next(&it) ) ) { key = cson_kvp_key(kvp); val = cson_kvp_value(kvp); ... } @endcode There is no need to clean up an iterator, as it holds no dynamic resources. @see cson_kvp_key() @see cson_kvp_value() */ cson_kvp * cson_object_iter_next( cson_object_iterator * iter ); /** Returns the key associated with the given key/value pair, or NULL if !kvp. The memory is owned by the object which contains the key/value pair, and may be invalidated by any modifications to that object. */ cson_string const * cson_kvp_key( cson_kvp const * kvp ); /** Returns the value associated with the given key/value pair, or NULL if !kvp. The memory is owned by the object which contains the key/value pair, and may be invalidated by any modifications to that object. */ cson_value * cson_kvp_value( cson_kvp const * kvp ); /** @typedef some unsigned int type cson_size_t */ typedef unsigned int cson_size_t; /** A generic buffer class. They can be used like this: @code cson_buffer b = cson_buffer_empty; int rc = cson_buffer_reserve( &buf, 100 ); if( 0 != rc ) { ... allocation error ... } ... use buf.mem ... ... then free it up ... cson_buffer_reserve( &buf, 0 ); @endcode To take over ownership of a buffer's memory: @code void * mem = b.mem; // mem is b.capacity bytes long, but only b.used // bytes of it has been "used" by the API. b = cson_buffer_empty; @endcode The memory now belongs to the caller and must eventually be free()d. */ struct cson_buffer { /** The number of bytes allocated for this object. Use cson_buffer_reserve() to change its value. */ cson_size_t capacity; /** The number of bytes "used" by this object. It is not needed for all use cases, and management of this value (if needed) is up to the client. The cson_buffer public API does not use this member. The intention is that this can be used to track the length of strings which are allocated via cson_buffer, since they need an explicit length and/or null terminator. */ cson_size_t used; /** This is a debugging/metric-counting value intended to help certain malloc()-conscious clients tweak their memory reservation sizes. Each time cson_buffer_reserve() expands the buffer, it increments this value by 1. */ cson_size_t timesExpanded; /** The memory allocated for and owned by this buffer. Use cson_buffer_reserve() to change its size or free it. To take over ownership, do: @code void * myptr = buf.mem; buf = cson_buffer_empty; @endcode (You might also need to store buf.used and buf.capacity, depending on what you want to do with the memory.) When doing so, the memory must eventually be passed to free() to deallocate it. */ unsigned char * mem; }; /** Convenience typedef. */ typedef struct cson_buffer cson_buffer; /** An empty-initialized cson_buffer object. */ #define cson_buffer_empty_m {0/*capacity*/,0/*used*/,0/*timesExpanded*/,NULL/*mem*/} /** An empty-initialized cson_buffer object. */ extern const cson_buffer cson_buffer_empty; /** Uses cson_output() to append all JSON output to the given buffer object. The semantics for the (v, opt) parameters, and the return value, are as documented for cson_output(). buf must be a non-NULL pointer to a properly initialized buffer (see example below). Ownership of buf is not changed by calling this. On success 0 is returned and the contents of buf.mem are guaranteed to be NULL-terminated. On error the buffer might contain partial contents, and it should not be used except to free its contents. On error non-zero is returned. Errors include: - Invalid arguments: cson_rc.ArgError - Buffer cannot be expanded (runs out of memory): cson_rc.AllocError Example usage: @code cson_buffer buf = cson_buffer_empty; // optional: cson_buffer_reserve(&buf, 1024 * 10); int rc = cson_output_buffer( myValue, &buf, NULL ); if( 0 != rc ) { ... error! ... } else { ... use buffer ... puts((char const*)buf.mem); } // In both cases, we eventually need to clean up the buffer: cson_buffer_reserve( &buf, 0 ); // Or take over ownership of its memory: { char * mem = (char *)buf.mem; buf = cson_buffer_empty; ... free(mem); } @endcode @see cson_output() */ int cson_output_buffer( cson_value const * v, cson_buffer * buf, cson_output_opt const * opt ); /** This works identically to cson_parse_string(), but takes a cson_buffer object as its input. buf->used bytes of buf->mem are assumed to be valid JSON input, but it need not be NUL-terminated (we only read up to buf->used bytes). The value of buf->used is assumed to be the "string length" of buf->mem, i.e. not including the NUL terminator. Returns 0 on success, non-0 on error. See cson_parse() for the semantics of the tgt, opt, and err parameters. */ int cson_parse_buffer( cson_value ** tgt, cson_buffer const * buf, cson_parse_opt const * opt, cson_parse_info * err ); /** Reserves the given amount of memory for the given buffer object. If n is 0 then buf->mem is freed and its state is set to NULL/0 values. If buf->capacity is less than or equal to n then 0 is returned and buf is not modified. If n is larger than buf->capacity then buf->mem is (re)allocated and buf->capacity contains the new length. Newly-allocated bytes are filled with zeroes. On success 0 is returned. On error non-0 is returned and buf is not modified. buf->mem is owned by buf and must eventually be freed by passing an n value of 0 to this function. buf->used is never modified by this function. */ int cson_buffer_reserve( cson_buffer * buf, cson_size_t n ); /** Fills all bytes of the given buffer with the given character. Returns the number of bytes set (buf->capacity), or 0 if !buf or buf has no memory allocated to it. */ cson_size_t cson_buffer_fill( cson_buffer * buf, char c ); /** Uses a cson_data_source_f() function to buffer input into a cson_buffer. dest must be a non-NULL, initialized (though possibly empty) cson_buffer object. Its contents, if any, will be overwritten by this function, and any memory it holds might be re-used. The src function is called, and passed the state parameter, to fetch the input. If it returns non-0, this function returns that error code. src() is called, possibly repeatedly, until it reports that there is no more data. Whether or not this function succeeds, dest still owns any memory pointed to by dest->mem, and the client must eventually free it by calling cson_buffer_reserve(dest,0). dest->mem might (and possibly will) be (re)allocated by this function, so any pointers to it held from before this call might be invalidated by this call. On error non-0 is returned and dest has almost certainly been modified but its state must be considered incomplete. Errors include: - dest or src are NULL (cson_rc.ArgError) - Allocation error (cson_rc.AllocError) - src() returns an error code Whether or not the state parameter may be NULL depends on the src implementation requirements. On success dest will contain the contents read from the input source. dest->used will be the length of the read-in data, and dest->mem will point to the memory. dest->mem is automatically NUL-terminated if this function succeeds, but dest->used does not count that terminator. On error the state of dest->mem must be considered incomplete, and is not guaranteed to be NUL-terminated. Example usage: @code cson_buffer buf = cson_buffer_empty; int rc = cson_buffer_fill_from( &buf, cson_data_source_FILE, stdin ); if( rc ) { fprintf(stderr,"Error %d (%s) while filling buffer.\n", rc, cson_rc_string(rc)); cson_buffer_reserve( &buf, 0 ); return ...; } ... use the buf->mem ... ... clean up the buffer ... cson_buffer_reserve( &buf, 0 ); @endcode To take over ownership of the buffer's memory, do: @code void * mem = buf.mem; buf = cson_buffer_empty; @endcode In which case the memory must eventually be passed to free() to free it. */ int cson_buffer_fill_from( cson_buffer * dest, cson_data_source_f src, void * state ); /** Increments the reference count for the given value. This is a low-level operation and should not normally be used by client code without understanding exactly what side-effects it introduces. Mis-use can lead to premature destruction or cause a value instance to never be properly destructed (i.e. a memory leak). This function is probably only useful for the following cases: - You want to hold a reference to a value which is itself contained in one or more containers, and you need to be sure that your reference outlives the container(s) and/or that you can free your copy of the reference without invaliding any references to the same value held in containers. - You want to implement "value sharing" behaviour without using an object or array to contain the shared value. This can be used to ensure the lifetime of the shared value instance. Each sharing point adds a reference and simply passed the value to cson_value_free() when they're done. The object will be kept alive for other sharing points which added a reference. Normally any such value handles would be invalidated when the parent container(s) is/are cleaned up, but this function can be used to effectively delay the cleanup. This function, at its lowest level, increments the value's reference count by 1. To decrement the reference count, pass the value to cson_value_free(), after which the value must be considered, from the perspective of that client code, to be destroyed (though it will not be if there are still other live references to it). cson_value_free() will not _actually_ destroy the value until its reference count drops to 0. Returns 0 on success. The only error conditions are if v is NULL (cson_rc.ArgError) or if the reference increment would overflow (cson_rc.RangeError). In theory a client would get allocation errors long before the reference count could overflow (assuming those reference counts come from container insertions, as opposed to via this function). Insider notes which clients really need to know: For shared/constant value instances, such as those returned by cson_value_true() and cson_value_null(), this function has no side effects - it does not actually modify the reference count because (A) those instances are shared across all client code and (B) those objects are static and never get cleaned up. However, that is an implementation detail which client code should not rely on. In other words, if you call cson_value_add_reference() 3 times using the value returned by cson_value_true() (which is incidentally a shared cson_value instance), you must eventually call cson_value_free() 3 times to (semantically) remove those references. However, internally the reference count for that specific cson_value instance will not be modified and those objects will never be freed (they're stack-allocated). It might be interesting to note that newly-created objects have a reference count of 0 instead of 1. This is partly because if the initial reference is counted then it makes ownership problematic when inserting values into containers. e.g. consider the following code: @code // ACHTUNG: this code is hypothetical and does not reflect // what actually happens! cson_value * v = cson_value_new_integer( 42 ); // v's refcount = 1 cson_array_append( myArray, v ); // v's refcount = 2 @endcode If that were the case, the client would be forced to free his own reference after inserting it into the container (which is a bit counter-intuitive as well as intrusive). It would look a bit like the following and would have to be done after every create/insert operation: @code // ACHTUNG: this code is hypothetical and does not reflect // what actually happens! cson_array_append( myArray, v ); // v's refcount = 2 cson_value_free( v ); // v's refcount = 1 @endcode (As i said: it's counter-intuitive and intrusive.) Instead, values start with a refcount of 0 and it is only increased when the value is added to an object/array container or when this function is used to manually increment it. cson_value_free() treats a refcount of 0 or 1 equivalently, destroying the value instance. The only semantic difference between 0 and 1, for purposes of cleaning up, is that a value with a non-0 refcount has been had its refcount adjusted, whereas a 0 refcount indicates a fresh, "unowned" reference. */ int cson_value_add_reference( cson_value * v ); #if 0 /** DO NOT use this unless you know EXACTLY what you're doing. It is only in the public API to work around a couple corner cases involving extracting child elements and discarding their parents. This function sets v's reference count to the given value. It does not clean up the object if rc is 0. Returns 0 on success, non-0 on error. */ int cson_value_refcount_set( cson_value * v, unsigned short rc ); #endif /** Deeply copies a JSON value, be it an object/array or a "plain" value (e.g. number/string/boolean). If cv is not NULL then this function makes a deep clone of it and returns that clone. Ownership of the clone is transfered to the caller, who must eventually free the value using cson_value_free() or add it to a container object/array to transfer ownership to the container. The returned object will be of the same logical type as orig. ACHTUNG: if orig contains any cyclic references at any depth level this function will endlessly recurse. (Having _any_ cyclic references violates this library's requirements.) Returns NULL if orig is NULL or if cloning fails. Assuming that orig is in a valid state, the only "likely" error case is that an allocation fails while constructing the clone. In other words, if cloning fails due to something other than an allocation error then either orig is in an invalid state or there is a bug. */ cson_value * cson_value_clone( cson_value const * orig ); /* LICENSE This software's source code, including accompanying documentation and demonstration applications, are licensed under the following conditions... Certain files are imported from external projects and have their own licensing terms. Namely, the JSON_parser.* files. See their files for their official licenses, but the summary is "do what you want [with them] but leave the license text and copyright in place." The author (Stephan G. Beal [http://wanderinghorse.net/home/stephan/]) explicitly disclaims copyright in all jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2011), this software is Copyright (c) 2011 by Stephan G. Beal, and is released under the terms of the MIT License (see below). In jurisdictions which recognize Public Domain property, the user of this software may choose to accept it either as 1) Public Domain, 2) under the conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License The full text of the MIT License follows: -- Copyright (c) 2011 Stephan G. Beal (http://wanderinghorse.net/home/stephan/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --END OF MIT LICENSE-- For purposes of the above license, the term "Software" includes documentation and demonstration source code which accompanies this software. ("Accompanies" = is contained in the Software's primary public source code repository.) */ #if defined(__cplusplus) } /*extern "C"*/ #endif #endif /* WANDERINGHORSE_NET_CSON_H_INCLUDED */ /* end file include/wh/cson/cson.h */ /* begin file include/wh/cson/cson_sqlite3.h */ /** @file cson_sqlite3.h This file contains cson's public sqlite3-to-JSON API declarations and API documentation. If CSON_ENABLE_SQLITE3 is not defined, or is defined to 0, then including this file will have no side-effects other than defining CSON_ENABLE_SQLITE3 (if it was not defined) to 0 and defining a few include guard macros. i.e. if CSON_ENABLE_SQLITE3 is not set to a true value then the API is not visible. This API requires that <sqlite3.h> be in the INCLUDES path and that the client eventually link to (or directly embed) the sqlite3 library. */ #if !defined(WANDERINGHORSE_NET_CSON_SQLITE3_H_INCLUDED) #define WANDERINGHORSE_NET_CSON_SQLITE3_H_INCLUDED 1 #if !defined(CSON_ENABLE_SQLITE3) # if defined(DOXYGEN) #define CSON_ENABLE_SQLITE3 1 # else #define CSON_ENABLE_SQLITE3 1 # endif #endif #if CSON_ENABLE_SQLITE3 /* we do this here for the sake of the amalgamation build */ #include <sqlite3.h> #if defined(__cplusplus) extern "C" { #endif /** Converts the results of an sqlite3 SELECT statement to JSON, in the form of a cson_value object tree. st must be a prepared, but not yet traversed, SELECT query. tgt must be a pointer to NULL (see the example below). If either of those arguments are NULL, cson_rc.ArgError is returned. This walks the query results and returns a JSON object which has a different structure depending on the value of the 'fat' argument. If 'fat' is 0 then the structure is: @code { "columns":["colName1",..."colNameN"], "rows":[ [colVal0, ... colValN], [colVal0, ... colValN], ... ] } @endcode In the "non-fat" format the order of the columns and row values is guaranteed to be the same as that of the underlying query. If 'fat' is not 0 then the structure is: @code { "columns":["colName1",..."colNameN"], "rows":[ {"colName1":value1,..."colNameN":valueN}, {"colName1":value1,..."colNameN":valueN}, ... ] } @endcode In the "fat" format, the order of the "columns" entries is guaranteed to be the same as the underlying query fields, but the order of the keys in the "rows" might be different and might in fact change when passed through different JSON implementations, depending on how they implement object key/value pairs. On success it returns 0 and assigns *tgt to a newly-allocated JSON object tree (using the above structure), which the caller owns. If the query returns no rows, the "rows" value will be an empty array, as opposed to null. On error non-0 is returned and *tgt is not modified. The error code cson_rc.IOError is used to indicate a db-level error, and cson_rc.TypeError is returned if sqlite3_column_count(st) returns 0 or less (indicating an invalid or non-SELECT statement). The JSON data types are determined by the column type as reported by sqlite3_column_type(): SQLITE_INTEGER: integer SQLITE_FLOAT: double SQLITE_TEXT or SQLITE_BLOB: string, and this will only work if the data is UTF8 compatible. If the db returns a literal or SQL NULL for a value it is converted to a JSON null. If it somehow finds a column type it cannot handle, the value is also converted to a NULL in the output. Example @code cson_value * json = NULL; int rc = cson_sqlite3_stmt_to_json( myStatement, &json, 1 ); if( 0 != rc ) { ... error ... } else { cson_output_FILE( json, stdout, NULL ); cson_value_free( json ); } @endcode */ int cson_sqlite3_stmt_to_json( sqlite3_stmt * st, cson_value ** tgt, char fat ); /** A convenience wrapper around cson_sqlite3_stmt_to_json(), which takes SQL instead of a sqlite3_stmt object. It has the same return value and argument semantics as that function. */ int cson_sqlite3_sql_to_json( sqlite3 * db, cson_value ** tgt, char const * sql, char fat ); #if defined(__cplusplus) } /*extern "C"*/ #endif #endif /* CSON_ENABLE_SQLITE3 */ #endif /* WANDERINGHORSE_NET_CSON_SQLITE3_H_INCLUDED */ /* end file include/wh/cson/cson_sqlite3.h */ /* begin file include/wh/cson/cson_session.h */ #if !defined(WANDERINGHORSE_NET_CSON_SESSION_H_INCLUDED) #define WANDERINGHORSE_NET_CSON_SESSION_H_INCLUDED 1 /** @page page_cson_session cson Session API The cson_session API provides a small interface, called cson_sessmgr, which defines the basic operations needed for implementent persistent application state, across application sessions, by storing the state as JSON data in "some back-end storage." The exact underlying storage is not specified by the interface, but two implementations are provided by the library: - File-based sessions. - Database-based sessions, using libcpdo for connection abstraction. libcpdo is included, in full, in the cson source tree, but can also be found on its web page: http://fossil.wanderinghorse.net/repos/cpdo/ @see cson_sessmgr_register() @see cson_sessmgr_load() @see cson_sessmgr_names() @see cson_sessmgr @see cson_sessmgr_api */ #if defined(__cplusplus) extern "C" { #endif typedef struct cson_sessmgr cson_sessmgr; typedef struct cson_sessmgr_api cson_sessmgr_api; /** @struct cson_sessmgr_api Defines operations required by "session managers." Session managers are responsible for loading and saving cson session information in the form of JSON data. @see cson_sessmgr */ struct cson_sessmgr_api { /** Loads/creates a session object (JSON data). The implementation must use the given identifier for loading an existing session, creating the session if createIfNeeded is true and the session data is not found. If createIfNeeded is true then the implementation must create an Object for the session root, as opposed to an Array or other JSON value. Clients are allowed to use non-Objects as their sessions but doing so would seem to have no benefit, and is not recommended. If the given id cannot be found then cson_rc.NotFoundError must be returned. On success it must assign the root node of the session tree to *tgt and return 0. On error *tgt must not be modified and non-zero must be returned. On success ownership of *tgt is transfered to the caller. Error conditions include: - self, tgt, or id are NULL: cson_rc.ArgError - id is "not valid" (the meaning of "valid" is implementation-dependent): cson_rc.ArgError The identifier string must be NUL-terminated. Its maximum length, if any, is implementation-dependent. */ int (*load)( cson_sessmgr * self, cson_value ** tgt, char const * id ); /** Must save the given JSON object tree to the underlying storage, using the given identifier as its unique key. It must overwrite any existing session with that same identifier. */ int (*save)( cson_sessmgr * self, cson_value const * root, char const * id ); /** Must remove all session data associated with the given id. Must return 0 on success, non-0 on error. */ int (*remove)( cson_sessmgr * self, char const * id ); /** Must free up any resources used by the self object and then free self. After calling this, further use of the self object invokes undefined behaviour. */ void (*finalize)( cson_sessmgr * self ); }; /** cson_sessmgr is base interface type for concrete cson_sessmgr_api implementations. Each holds a pointer to its underlying implementation and to implementation-private data. @see cson_sessmgr_register() @see cson_sessmgr_load() @see cson_sessmgr_names() @see cson_sessmgr_api */ struct cson_sessmgr { /** The concrete implementation functions for this session manager instance. */ const cson_sessmgr_api * api; /** Private implementation date for this session manager instance. It is owned by this object and will be freed when thisObject->api->finalize(thisObject) is called. Client code must never use nor rely on the type/contents of the memory stored here. */ void * impl; }; /** A typedef for factory functions which instantiate cson_sessmgr instances. The semantics are: - tgt must be a non-NULL pointer where the result object can be stored. If it is NULL, cson_rc.ArgError must be returned. - opt (configuration options) may or may not be required, depending on the manager. If it is required and not passed in, cson_rc.ArgError must be returned. If the config options are required but the passed-in object is missing certain values, or has incorrect values, the implementation may substitute sensible defaults (if possible) or return cson_rc.ArgError. - On error non-0 (one of the cson_rc values) must be returned and tgt must not be modified. - On success *tgt must be pointed to the new manager object, zero must be returned, and the caller takes over ownership of the *tgt value (and must eventually free it with obj->api->finalize(obj)). */ typedef int (*cson_sessmgr_factory_f)( cson_sessmgr ** tgt, cson_object const * config ); #define cson_sessmgr_empty_m { NULL/*api*/, NULL/*impl*/ } /** Registers a session manager by name. The given name must be a NUL-terminaed string shorter than some internal limit (currently 32 bytes, including the trailing NUL). f must be a function conforming to the cson_sessmgr_factory_f() interface. On success returns 0. On error either one of the arguments was invalid, an entry with the given name was already found, or no space is left in the internal registration list. The API guarantees that at least 10 slots are initially available, and it is not anticipated that more than a small handful of them will ever be used. This function is not threadsafe - do not register factories concurrently from multiple threads. By default the following registrations are (possibly) pre-installed: - "file" = cson_sessmgr_file() - "cpdo" = cson_sessmgr_cpdo() IF this library is compiled with the macro CSON_ENABLE_CPDO set to a true value. Exactly which databases are supported by that back-end (if any) are determined by how the cpdo library code is compiled. - "whio_ht" = cson_sessmgr_whio_ht() IF this library is compiled with whio support. - "whio_epfs" = cson_sessmgr_whio_epfs() IF this library is compiled with whio support. */ int cson_sessmgr_register( char const * name, cson_sessmgr_factory_f f ); /** A front-end to loading cson_sessmgr intances by their cson_session-conventional name. The first arguments must be a NUL-terminated string holding the name of the session manager driver. The other two arguments have the same semantics as for cson_sessmgr_factory_f(), so see that typedef's documentation regarding, e.g., ownership of the *tgt value. This function is thread-safe with regards to itself but not with regards to cson_sessmgr_register(). That is, it is legal to call this function concurrently from multiple threads, provided the arguments themselves are not being used concurrently. However, it is not safe to call this function when cson_sessmgr_register() is being called from another thread, as that function modifies the lookup table used by this function. On success 0 is returned and the ownership of *tgt is as documented for cson_sessmgr_factory_f(). On error non-0 is returned and tgt is not modified. */ int cson_sessmgr_load( char const * name, cson_sessmgr ** tgt, cson_object const * opt ); /** Returns the list of session managers registered via cson_sessmgr_register(). This function is not thread-safe in conjunction with cson_sessmgr_register(), and results are undefined if that function is called while this function is called or the results of this function call are being used. The returned array is never NULL but has a NULL as its final entry. Example usage: @code char const * const * mgr = cson_sessmgr_names(); for( ; *mgr; ++mgr ) puts( *mgr ); @endcode */ char const * const * cson_sessmgr_names(); /** A cson_sessmgr_factory_f() implementation which returns a new session manager which uses local files for storage. tgt must be a non-NULL pointer where the result can be stored. The opt object may be NULL or may be a configuration object with the following structure: @code { dir: string (directory to store session files in), prefix: string (prefix part of filename), suffix: string (file extension, including leading '.') } @endcode Any missing options will assume (unspecified) default values. This routine does not ensure the validity of the option values, other than to make sure they are strings. The returned object is owned by the caller, who must eventually free it using obj->api->finalize(obj). If it returns NULL, the error was an out-of-memory condition or tgt was NULL. On error non-0 is returned, but the only error conditions are allocation errors and (NULL==tgt), which will return cson_rc.AllocError resp. cson_rc.ArgError. Threading notes: - As long as no two operations on these manager instances use the same JSON object and/or session ID at the same time, multi-threaded usage should be okay. All save()/load()/remove() data is local to those operations, with the exception of the input arguments (which must not be used concurrently to those calls). Storage locking: - No locking of input/output files is done, under the assumption that only one thread/process will be using a given session ID (which should, after all, be unique world-wide). If sessions will only be read, not written, there is little danger of something going wrong vis-a-vis locking (assuming the session files exists and can be read). TODO: - Add a config option to enable storage locking. If we'll re-implement this to use the whio API under the hood then we could use the (slightly simpler) whio_lock API for this. */ int cson_sessmgr_file( cson_sessmgr ** tgt, cson_object const * opt ); /** This is only available if cson is compiled with cpdo support. Implements the cson_sessmgr_factory_f() interface. This function tries to create a database connection using the options supplied in the opt object. The opt object must structurarly look like: @code { "dsn": "cpdo dsn string", "user": "string", "password": "string", "table": "table_name_where_sessions_are_stored", "fieldId": "field_name_for_session_id (VARCHAR/STRING)", "fieldTimestamp": "field_name_for_last_saved_timestamp (INTEGER)", "fieldSession": "field_name_for_session_data (TEXT)" } @endcode On success it returns 0 and sets *tgt to the new session manager, which is owned by the caller and must eventually be freed by calling obj->api->finalize(obj). This function can fail for any number of reasons: - Any parameters are NULL (cson_rc.ArgError). - cpdo cannot connect to the given DSN with the given username/password. Any error in establishing a connection causes cson_rc.IOError to be returned, as opposed to the underlying cpdo error code. - Any of the "table" or "fieldXXX" properties are NULL. It needs these data in order to know where to load/save sessions. If any required options are missing, cson_rc.ArgError is returned. TODO: add option "preferBlob", which can be used to set the db field type preference for the fieldSession field to blob. Currently it prefers string but will try blob operations if string ops fail. Blobs have the disadvantage of much larger encoded sizes but the advantage that the JSON data is encoded (at least by sqlite3) as a hex number stream, making it unreadable to casual observers. @endcode */ int cson_sessmgr_cpdo( cson_sessmgr ** tgt, cson_object const * opt ); /** This cson_sessmgr_factory_f() implementation might or might not be compiled in, depending on the mood of the cson maintainer. It is very niche-market, and primarily exists just to test (and show off) the whio_ht code. It uses libwhio's on-storage hashtable (called whio_ht) as the underlying storage: http://fossil.wanderinghorse.net/repos/whio/index.cgi/wiki/whio_ht The opt object must not be NULL and must contain a single string property named "file" which contains the path to the whio_ht file to use for sessions. That file must have been previously created, either programatically using the whio_ht API or using whio-ht-tool: http://fossil.wanderinghorse.net/repos/whio/index.cgi/wiki/whio_ht_tool See cson_sessmgr_factory_f() for the semantics of the tgt argument and the return value. Threading notes: While the underlying hashtable supports a client-defined mutex, this usage of it does not set one (because we have no default one to use). What this means for clients is that they must not use this session manager from multiple threads, nor may they use multiple instances in the same process which use the same underlying hashtable file from multiple threads. How best to remedy this (allowing the client to tell this API what mutex to use) is not yet clear. Maybe a global whio_mutex object which the client must initialize before instantiating these session managers. Storage Locking: If the underlying filesystem reports that it supports file locking (via the whio_lock API, basically meaning POSIX fcntl()-style locking) the the session manager will use it. For the load() operation a read lock is acquired and for save()/remove() a write lock. The operations will fail if locking fails, the exception being if the device reports that it doesn't support locking, in which case we optimistically save/load/remove without locking. Remember that in POSIX-style locking, a single process does not see its own locks and can overwrite locks set via other threads. This means that multi-threaded use of a given instance, or multiple instances in the same process using the same underlying hashtable file, will likely eventually corrupt the hashtable. TODO: - Add a config option to disable storage locking, for clients who really don't want to use it. */ int cson_sessmgr_whio_ht( cson_sessmgr ** tgt, cson_object const * opt ); /** This cson_sessmgr_factory_f() implementation might or might not be compiled in, depending on the mood of the cson maintainer. It is very niche-market, and primarily exists just to test (and show off) the whio_epfs code. It uses libwhio's embedded filesystem (called whio_epfs) as the underlying storage: http://fossil.wanderinghorse.net/repos/whio/index.cgi/wiki/whio_epfs The opt object must not be NULL and must contain a single string property named "file" which contains the path to the whio_epfs "container file" to use for storing sessions. That file must have been previously created, either programatically using the whio_epfs API or using whio-epfs-mkfs: http://fossil.wanderinghorse.net/repos/whio/index.cgi/wiki/whio_epfs_mkfs The EPFS container file MUST be created with a "namer" installed. See the above page for full details and examples. See cson_sessmgr_factory_f() for the semantics of the tgt argument and the return value. Threading notes: - It is not legal to use this session manager from multiple threads. Doing so will eventually corrupt the underlying EFS if multiple writers work concurrently, and will also eventually _appear_ corrupt to multiple readers. Storage locking: The underlying storage (EFS container file) is locked (with a write lock) for the lifetime the the returned session manager IF the storage reports that it supports locking. Unlocked write access from an outside application will corrupt the EFS. TODOs: - Add config option to explicitly disable locking support. */ int cson_sessmgr_whio_epfs( cson_sessmgr ** tgt, cson_object const * opt ); #if 0 /** TODO? dummy manager which has no i/o support. */ int cson_sessmgr_transient( cson_sessmgr ** tgt ); #endif /* LICENSE This software's source code, including accompanying documentation and demonstration applications, are licensed under the following conditions... Certain files are imported from external projects and have their own licensing terms. Namely, the JSON_parser.* files. See their files for their official licenses, but the summary is "do what you want [with them] but leave the license text and copyright in place." The author (Stephan G. Beal [http://wanderinghorse.net/home/stephan/]) explicitly disclaims copyright in all jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2011), this software is Copyright (c) 2011 by Stephan G. Beal, and is released under the terms of the MIT License (see below). In jurisdictions which recognize Public Domain property, the user of this software may choose to accept it either as 1) Public Domain, 2) under the conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License The full text of the MIT License follows: -- Copyright (c) 2011 Stephan G. Beal (http://wanderinghorse.net/home/stephan/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --END OF MIT LICENSE-- For purposes of the above license, the term "Software" includes documentation and demonstration source code which accompanies this software. ("Accompanies" = is contained in the Software's primary public source code repository.) */ #if defined(__cplusplus) } /*extern "C"*/ #endif #endif /* WANDERINGHORSE_NET_CSON_SESSION_H_INCLUDED */ /* end file include/wh/cson/cson_session.h */ /* begin file include/wh/cson/cson_cgi.h */ #if !defined(WANDERINGHORSE_NET_CSON_CGI_H_INCLUDED) #define WANDERINGHORSE_NET_CSON_CGI_H_INCLUDED 1 /** @page page_cson_cgi cson CGI API cson_cgi is a small framework encapsulating features usefor for writing JSON-only applications (primarily CGI apps) in C. It is based off of the cson JSON library: http://fossil.wanderinghorse.net/repos/cson/ In essence, it takes care of the basic CGI-related app setup, making the data somewhat more accessible for client purposes. Clients create, as output, a single JSON object. The framework takes care of outputing it, along with any necessary HTTP headers. Primary features: - Uses cson for its JSON handling, so it's pretty simple to use. - Provides a simple-to-use mini-framework for writing CGI applications which generate only JSON output. - Various sources of system data are converted by the framework to JSON for use by the client. This includes HTTP GET, OS environment, command-line arguments, HTTP cookies, and (with some limitations) HTTP POST. - Can read unencoded JSON POST data (TODO: read in form-urlencoded as a JSON object). - Supports an optional JSON config file. - Optional persistent sessions using files, sqlite3, or MySQL5 for the storage. Primary misfeatures: - Very young and not yet complete. - Intended for writing apps which ONLY generate JSON data, not HTML. - JSONP output support is currently incomplete. - TODO: support reading of POSTed Array data (currently only Objects work). - We're missing a good number of convenience functions. - Add client API for setting cookies. Currently they can be fetched or removed but not explicitly set. Other potential TODOs: - Session support using session cookies for the IDs. For this to work we also need to add a storage back-end or two (files, db (e.g. using cpdo), etc.) and have a fast, good source of random numbers for generating UUIDs. It _seems_ that using the address of (extern char ** environ) as a seed might be fairly random, but there are probably environments where that won't suffice. i want to avoid platform-specific bits, like /dev/urandom, if possible. - Add client-definable i/o routines. We have this code in the whprintf tree, but i was hoping to avoid having to import that here. This would allow a client to add, e.g., gzip support. */ /** @page page_cson_cgi_session cson CGI Sessions cson_cgi_init() will initialize a persistent session if it can figure out everything it needs in order to do so. If it cannot it will simply skip session initialization. A client can tell if a session was established or not by calling cson_cgi_get_env_val(cx,'s',0). If that returns NULL then no session was created during initialization. The API currently provides no way to initialize one after the fact. That is, client code can use cson_cgi_get_env_val(cx,'s',1) to create a session object, but it won't automatically be persistent across application sessions. Session management is really just the following: - Load a JSON object from some persistent storage. - Save that object at shutdown. "Persistent storage" is the important phrase here. How the sessions are saved is really unimportant. The library uses a generic interface (cson_sessmgr) to handle the i/o, and can use any implementation we care to provide. As of this writing (20110413) files, sqlite3, and MySQL5 are supported. The session object is a JSON object available via cson_cgi_getenv(), using "s" as the environment name (the second parameter to cson_cgi_getenv()). At library shutdown (typically when main() exits, but also via cson_cgi_cx_clean()), the session is saved using the current session manager. If the session is not loaded during initialization, but is created later, the library will assign a new session ID to it before saving. See cson_cgi_config_file() for examples of configuring the session management. */ #if defined(__cplusplus) extern "C" { #endif /** @def CSON_CGI_ENABLE_POST_FORM_URLENCODED If CSON_CGI_ENABLE_POST_FORM_URLENCODED is set to a true value then the API will try to process form-urlencoded POST data, otherwise it will not. Reminder to self: this is basically a quick hack for fossil integration. We disable form encoding in that build because fossil handles that itself and we must not interfere with it. */ #if !defined(CSON_CGI_ENABLE_POST_FORM_URLENCODED) #define CSON_CGI_ENABLE_POST_FORM_URLENCODED 0 #endif /** @def CSON_CGI_GETENV_DEFAULT The default environment name(s) to use for cson_cgi_getenv(). */ #define CSON_CGI_GETENV_DEFAULT "gpce" /** @def CSON_CGI_KEY_JSONP TODO?: get rid of this and move cson_cgi_keys into the public API? The default environment key name to use for checking whether a response should used JSONP or not. */ #define CSON_CGI_KEY_JSONP "jspon" #define CSON_CGI_KEY_SESSION "CSONSESSID" typedef struct cson_cgi_init_opt cson_cgi_init_opt; /** @struct cson_cgi_init_opt A type to hold core runtime configuration information for cson_cgi. */ struct cson_cgi_init_opt { /** stdin stream. If NULL, stdin is used. */ FILE * inStream; /** stdout stream. If NULL, stdout is used. */ FILE * outStream; /** stderr stream. If NULL, stderr is used. */ FILE * errStream; /** Path to a JSON config file. */ char const * configFile; /** If set then the session will be forced to use this ID, otherwise one will be generated. */ char const * sessionID; /** Values are interpretted as: 0 = do not output headers when cson_cgi_response_output_all() is called. (>0) = always output headers when cson_cgi_response_output_all() is called. (<0) = Try to determine, based on environment variables, if we are running in CGI mode. If so, output the headers when cson_cgi_response_output_all() is called, otherwise omit them. If the headers are omitted then so is the empty line which normally separates them from the response body! The intention of this flag is to allow non-CGI apps to disable output of the HTTP headers. */ char httpHeadersMode; /** JSON output options. */ cson_output_opt outOpt; }; /** Empty-initialized cson_cgi_init_opt object. */ #define cson_cgi_init_opt_empty_m { \ NULL/*inStream*/, NULL/*outStream*/, NULL/*errStream*/, \ NULL /*configFile*/, NULL /*sessionID*/, \ -1/*httpHeadersMode*/, \ cson_output_opt_empty_m /*outOpt*/ \ } /** Empty-initialized cson_cgi_init_opt object. */ extern const cson_cgi_init_opt cson_cgi_init_opt_empty; /** @struct cson_cgi_env_map Holds a cson_object and its cson_value parent reference. */ struct cson_cgi_env_map { /** Parent reference of jobj. */ cson_value * jval; /** Object reference of jval. */ cson_object * jobj; }; typedef struct cson_cgi_env_map cson_cgi_env_map; /** Empty cson_cgi_env_map object. */ #define cson_cgi_env_map_empty_m { NULL, NULL } /** @struct cson_cgi_cx Internal state used by cson_cgi. Clients must not rely on its internal structure. It is in the public API so that it can be stack- or custom-allocated. To properly initialize such an object, use cson_cgi_cx_empty_m cson_cgi_cx_empty, depending on the context. */ struct cson_cgi_cx { /** Various key/value stores used by the framework. Each corresponds to some convention source of key/value pairs, e.g. QUERY_STRING or POST parameters. */ struct { /** The system's environment variables. */ cson_cgi_env_map env; /** Holds QUERY_STRING key/value pairs. */ cson_cgi_env_map get; /** Holds POST form/JSON data key/value pairs. */ cson_cgi_env_map post; /** Holds cookie key/value pairs. */ cson_cgi_env_map cookie; /** Holds request headers. */ cson_cgi_env_map headers; } request; /** Holds data related to the response JSON. */ struct { /** HTTP error code to report. */ int httpCode; /** Root JSON object. Must be an Object or Array (per the JSON spec). */ cson_value * root; /** Holds HTTP response headers as an array of key/value pairs. */ cson_cgi_env_map headers; } response; /** A place to store cson_value references for cleanup purposes. */ cson_cgi_env_map gc; /** Holds client-defined key/value pairs. */ cson_cgi_env_map clientEnv; cson_cgi_env_map config; struct { cson_cgi_env_map env; cson_sessmgr * mgr; char * id; } session; struct { cson_array * jarr; cson_value * jval; } argv; cson_cgi_init_opt opt; cson_buffer tmpBuf; struct { char isJSONP; void const * allocStamp; } misc; }; typedef struct cson_cgi_cx cson_cgi_cx; /** Empty-initialized cson_cgi_cx object. */ extern const cson_cgi_cx cson_cgi_cx_empty; /** Empty-initialized cson_cgi_cx object. */ #define cson_cgi_cx_empty_m \ { \ { /*maps*/ \ cson_cgi_env_map_empty_m /*env*/, \ cson_cgi_env_map_empty_m /*get*/, \ cson_cgi_env_map_empty_m /*post*/, \ cson_cgi_env_map_empty_m /*cookie*/, \ cson_cgi_env_map_empty_m /*headers*/ \ }, \ {/*response*/ \ 0 /*httpCode*/, \ NULL /*root*/, \ cson_cgi_env_map_empty_m /*headers*/ \ }, \ cson_cgi_env_map_empty_m /*gc*/, \ cson_cgi_env_map_empty_m /*clientEnv*/, \ cson_cgi_env_map_empty_m /*config*/, \ {/*session*/ \ cson_cgi_env_map_empty_m /*env*/, \ NULL /*mgr*/, \ NULL /*id*/ \ }, \ {/*argv*/ \ NULL /*jarr*/, \ NULL /*jval*/ \ }, \ cson_cgi_init_opt_empty_m /*opt*/, \ cson_buffer_empty_m /* tmpBuf */, \ {/*misc*/ \ -1 /*isJSONP*/, \ NULL/*allocStamp*/ \ } \ } cson_cgi_cx * cson_cgi_cx_alloc(); /** Cleans up all internal state of cx. IFF cx was allocated by cson_cgi_cx_alloc() then cx is also free()d, else it is assumed to have been allocated by the caller (possibly on the stack). Returns 1 if cx is not NULL and this function actually frees it. If it returns 0 then either cx is NULL or this function cleaned up its internals but did not free(cx) (cx is assumed to have been allocated by the client). */ char cson_cgi_cx_clean(cson_cgi_cx * cx); /** Initializes the internal cson_cgi environment and must be called one time, from main(), at application startup. cx must be either: - Created via cson_cgi_cx_alloc(). - Alternately allocated (e.g. on the stack) and initialized by copying cson_cgi_cx_empty over it. Any other initialization leads to undefined behaviour. Returns 0 on success. On error the problem is almost certainly an allocation error. If it returns non-0 then the rest of the API will not work (and using the rest of the API invokes undefined behaviour unless documented otherwise for a specific function), so the application should exit immediately with an error code. The error codes returned by this function all come from the cson_rc object. The returned object must eventually be passed to cson_cgi_cx_clean(), regardless of success or failure, to clean up any resources allocated for the object. On success: - 0 is returned. - The cx object takes over ownership of any streams set in the opt object UNLESS they are the stdin/stdout/stderr streams (in which case ownership does not change). On error non-0 is returned and ownership of the opt.xxStream STILL transfers over to cx as described above (because this simpifies client-side error handling ). The 'opt' parameter can be used to tweak certain properties of the framework. It may be NULL, in which case defaults are used. This function currently performs the following initialization: - Parses QUERY_STRING environment variable into a JSON object. - Parses the HTTP_COOKIE environment variable into a JSON object. - Transforms the system environment to JSON. - Copies the list of arguments (argv, in the form conventional for main()) to JSON array form for downstream use by the client application. It does not interpret these arguments in any way. Clients may use cson_cgi_argv() and cson_cgi_argv_array() to fetch the list later on in the application's lifetime (presumably outside of main()). It is legal to pass (argv==NULL) only if argc is 0 or less. - If the CONTENT_TYPE env var is one of (application/json, application/javascript, or text/plain) and CONTENT_LENGTH is set then stdin is assumed to be JSON data coming in via POST. An error during that parsing is ignored for initialization purposes unless it is an allocation error, in which case it is propagated back to the caller of this function. - If the CSON_CGI_CONFIG env var is set then that file is read. Errors in loading the config are silently ignored. - If session management is properly configured in the configuration file and if a variable named CSON_CGI_KEY_SESSION is found in the environment (cookies, GET, POST, or system env) then the previous session is loaded. If it cannot be loaded, the error is ignored. (Note that the cookie name can be changed via the configuration file.) TODOs: - Add config file option to the opt object. - Only read POST data when REQUEST_METHOD==POST? - Convert form-urlencoded POST data to a JSON object. - Potentially add an option to do automatic data type detection for numeric GET/POST/ENV/COOKIE data, such that fetching the cson_value for such a key would return a numeric value object as opposed to a string. Or we could add that option in a separate function which walks a JSON Object and performs that check/transformation on all of its entries. That currently can't be done properly with the cson_object_iterator API because changes to the object while looping invalidate the iterator. This option would also open up problems when clients pass huge strings which just happen to look like numbers. @see cson_cgi_config_file() */ int cson_cgi_init( cson_cgi_cx * cx, int argc, char const * const * argv, cson_cgi_init_opt * options ); /** Searches for a value from the CGI environment. The fromWhere parameter is a NUL-terminated string which specifies which environment(s) to check, and may be made up of any of the letters [gprecl], case-insensitive. If fromWhere is NULL or its first byte is NUL (i.e. it is empty) then the default value defined in CSON_CGI_GETENV_DEFAULT is used. The environments are searched in the order specified in fromWhere. The various letters mean: - g = GET: key/value pairs parsed from the QUERY_STRING environment variable. - p = POST: form-encoded key/value pairs parsed from stdin. - r = REQUEST, equivalent to "gpc", a superset of GET/POST/COOKIE. - e = ENV, e.g. via getenv(), but see cson_cgi_env_get_val() for more details. - c = COOKIE: request cookies (not response cookies) parsed from the HTTP_COOKIE environment variable. - a = APP: an environment namespace reserved for client app use. - f = CONFIG FILE. - Use key 's' for the SESSION. Invalid characters are ignored. The returned value is owned by the cson_cgi environment and must not be destroyed by the caller. NULL is returned if none of the requested environments contain the given key. Results are undefined if fromWhere is not NULL and is not NUL-terminated. TODOs: - Replace CSON_CGI_GETENV_DEFAULT with a runtime-configurable value (via a config file). */ cson_value * cson_cgi_getenv( cson_cgi_cx * cx, char const * fromWhere, char const * key ); /** A convenience form of cson_cgi_getenv() which returns the given key as a string. This will return NULL if the requested key is-not-a string value. It does not convert non-string values to strings. On success the string value is returned. Its bytes are owned by this API and are valid until the given key is removed/replaced from/in the environment object it was found in or that environment object is cleaned up. */ char const * cson_cgi_getenv_cstr( cson_cgi_cx * cx, char const * where, char const * key ); /** During initialization, if the PATH_INFO environment variable is set, it is split on '/' characters into array. That array is stored in the environment with the name PATH_INFO_SPLIT. This function returns the element of the PATH_INFO at the given index, or NULL if ndx is out of bounds or if no PATH_INFO is available. e.g. if PATH_INFO=/a/b/c, passing 0 to this function would return "a", passing 2 would return "c", and passing anything greater than 2 would return NULL. */ char const * cson_cgi_path_part_cstr( cson_cgi_cx * cx, unsigned short ndx ); /** Functionally equivalent to cson_cgi_path_part_cstr(), but returns the underlying value as a cson value handle. That handle is owned by the underlying PATH_INFO_SPLIT array (which is owned by the "e" environment object). Unless the client has mucked with the PATH_INFO_SPLIT data, the returned value will (if it is not NULL) have a logical type of String. */ cson_value * cson_cgi_path_part( cson_cgi_cx * cx, unsigned short ndx ); /** Sets or unsets a key in the "user" environment/namespace. If v is NULL then the value is removed, otherwise it is set/replaced. Returns 0 on success. If key is NULL or has a length of 0 then cson_rc.ArgError is returned. The user namespace object can be fetched via cson_cgi_env_get_val('a',...). On success ownership of v is transfered to (or shared with) the cson_cgi API. On error ownership of v is not modified. Aside from */ int cson_cgi_setenv( cson_cgi_cx * cx, char const * key, cson_value * v ); /** This function is not implemented, but exists as a convenient place to document the cson_cgi config file format. cson_cgi_init() accepts the name of a configuration file (assumed to be in JSON format) to read during initialization. The library optionally uses the configuration to change certain aspects of its behaviour. The following commented JSON demonstrates the configuration file options: @code { "formatting": { // NOT YET HONORED. Will mimic cson_output_opt. "indentation": 1, "addNewline": true, "addSpaceAfterColon": true, "indentSingleMemberValues": true }, "session": { // Options for session handling "manager": "file", // name of session manager impl. Should // have a matching entry in "managers" (below) "cookieLifetimeMinutes": 10080, // cookie lifetime in minutes "cookieName": "cson_session_id", // cookie name for session ID "managers": { "file": { "sessionDriver": "file", -- cson_cgi-internal session manager name "dir": "./SESSIONS", "prefix": "cson-session-", "suffix": ".json" }, "mysql5": { "sessionDriver": "cpdo", -- cson_cgi-internal session manager name "dsn": "mysql5:dbname=cpdo;host=localhost", "user": "cpdo", "password": "cpdo", "table": "cson_session", "fieldId": "id", "fieldTimestamp": "last_saved", "fieldSession": "json" }, "sqlite3": { "sessionDriver": "cpdo", -- cson_cgi-internal session manager name "dsn": "sqlite3:sessions.sqlite3", "user": null, "password": null, "table": "cson_session", "fieldId": "id", "fieldTimestamp": "last_saved", "fieldSession": "json" } } } } @endcode TODO: allow initialization to take a JSON object, as opposed to a filename, so that we can embed the configuration inside client-side config data. */ void cson_cgi_config_file(); /** Sets or (if v is NULL) unsets a cookie value. v must either be of one of the types (string, integer, double, bool, null, NULL) or must be an object with the following structure: @code { value: (string, integer, double, bool, or null), OPTIONAL path: string, OPTIONAL domain: string, OPTIONAL expires: integer (Unix epoch timestamp), OPTIONAL secure: bool, OPTIONAL httponly: bool } @endcode For the object form, if the "value" property is missing or not of the correct type then the cookie will not be emitted in the HTTP response headers. The other properties are optional. A value of NULL or cson_value_null() will cause the expiry field (if set) to be ignored. Note, however, that removal will only work on the client side if all other cookie parameters match (e.g. domain and path). Returns 0 on success, non-0 on error. A duplicate cookie replaces any previous cookie with the same key. On success ownership of v is shared with the cson_cgi API (via reference counting). On error ownership of v is not modified. */ int cson_cgi_cookie_set( cson_cgi_cx * cx, char const * key, cson_value * v ); /** Sets or (if v is NULL) unsets an HTTP cookie value. key may not be NULL nor have a length of 0. v must be one of the types (string, integer, double, bool, null, NULL). Any other pointer arguments may be NULL, in which case they are not used. If v is NULL then the JSON null value is used as a placeholder value so that when the HTTP headers are generated, the cookie can be unset on the client side. This function creates an object with the structure documented in cson_cgi_cookie_set() and then passes that object to cson_cgi_cookie_set(). Any parameters which have NULL/0 values are not emitted in the generated object, with the exception of (v==NULL), which causes the expiry property to be ignored and a value from a time far in the past to be used (so that the client will expire it).. Returns 0 on success, non-0 on error. On success ownership of v is shared with the cson_cgi API (via reference counting). On error ownership of v is not modified. */ int cson_cgi_cookie_set2( cson_cgi_cx * cx, char const * key, cson_value * v, char const * domain, char const * path, unsigned int expires, char secure, char httponly ); /** Returns the internal "environment" JSON object corresponding to the given 'which' letter, which must be one of (case-insensitive): - g = GET - p = POST - c = COOKIE - e = ENV (i.e. system environment) - s = SESSION - a = APP (application-specific) TODO: s = SESSION See cson_cgi_getenv() for more details about each of those. Returns NULL if 'which' is not one of the above. Note that in the 'e' (system environment) case, making modifications to the returned object will NOT also modify the system environment. Likewise, future updates to the system environment will not be automatically reflected in the returned object. The returned object is owned by the cson_cgi environment and must not be destroyed by the caller. If createIfNeeded is non-0 (true) then the requested environment object is created if it was formerly empty. In that case, a return value of NULL can indicate an invalid 'which' parameter or an allocation error. To get the Object reference to this environment use cson_cgi_env_get_obj() or pass the result of this function to cson_value_get_object(). The returned value is owned by the cson_cgi API. The public API does not provide a way for clients to modify several of the internal environment stores, e.g. HTTP GET parameters are set only by this framework. However, clients can (if needed) get around this by fetching the associated "environment object" via this function or cson_cgi_env_get_obj(), and modifying it directly. Clients are encouraged to use the other public APIs for dealing with the environment, however, and are encouraged to not directly modify "special" namespaces like the cookie/GET/POST data. */ cson_value * cson_cgi_env_get_val( cson_cgi_cx * cx, char which, char createIfNeeded ); /** Equivalent to: @code cson_value_get_object( cson_cgi_env_get_val( which, createIfNeeded ) ); @endcode Note, however, that it is at least theoretically possible that cson_cgi_env_get_val() return non-NULL but this function returns NULL. If that happens it means that the value returned by cson_cgi_env_get_val() is-not-a Object instance, but is something else (maybe an array?). */ cson_object * cson_cgi_env_get_obj( cson_cgi_cx * cx, char which, char createIfNeeded ); /** Adds the given key/value to the list of HTTP headers (replacing any existing entry with the same name). If v is NULL then any header with the given key is removed from the pending response. Returns 0 on success. On success ownership of v is transfered to (or shared with) the internal header list. On error, ownership of v is not modified. If v is not of one of the types (string, integer, double, bool, undef, null) then the header will not be output when when cson_cgi_response_output_headers() is called. If it is one of those types then its stringified value will be its "natural" form (for strings and numbers), the integer 0 or 1 for booleans, and the number 0 for null. Note that a literal (v==NULL) is treated differently from a JSON null - it UNSETS the given header. This function should not be used for setting cookies, as they require extra url-encoding and possibly additional parameters. Use cson_cgi_cookie_set() and cson_cgi_cookie_set2() to set cookie headers. */ int cson_cgi_response_header_add( cson_cgi_cx * cx, char const * key, cson_value * v ); /** Returns a cson array value containing the arguments passed to cson_cgi_init(). The returned value is owned by the cson_cgi API and must not be destroyed by the caller. Only returns NULL if initialization of cson_cgi_init() fails early on, and is almost certainly indicative of an allocation error. If cson_cgi_init() is given a 0-length argument list then this function will return an empty array (except in the NULL case mentioned above). */ cson_value * cson_cgi_argv(cson_cgi_cx * cx); /** Equivalent to: @code cson_value_get_array( cson_cgi_argv() ); @endcode */ cson_array * cson_cgi_argv_array(cson_cgi_cx * cx); /** Flushes all response headers set via cson_cgi_response_header_add() to stdout. The client must output an empty line before the body part (if any), and may output custom headers before doing so. Do not call this more than once. */ int cson_cgi_response_output_headers(cson_cgi_cx * cx); /** Outputs the response root object to stdout. If none has been set, non-0 is returned. Returns 0 on success. On error, partial output might be generated. Do not call this more than once. */ int cson_cgi_response_output_root(cson_cgi_cx * cx); /** Outputs the whole response, including headers and the root JSON value. Returns 0 on success. Fails without side effects if no root is set. Do not call this more than once. */ int cson_cgi_response_output_all(cson_cgi_cx * cx); /** Don't use this - i need to re-think the JSONP bits. Returns non-0 (true) if the GET/POST environment contains a key named CSON_CGI_KEY_JSONP. If this is the case, then when cson_cgi_response_output_headers() is called the Content-type is set to "application/javascript". If cson_cgi_enable_jsonp() is ever called to set this option explicitly, this function does not guess, but uses that value instead. When JSONP is desired, the generated page output must be wrapped in the appropriate JS code. */ char cson_cgi_is_jsonp(cson_cgi_cx * cx); /** Don't use this - i need to re-think the JSONP bits. Sets or unsets JSONP mode. If b is 0 then JSONP guessing is explicitly disabled and output is assumed to be JSON. If it is non-0 then cson_cgi_guess_content_type() will never return "application/javascript". When JSONP is desired, the generated page output must be wrapped in the appropriate JS code. */ void cson_cgi_enable_jsonp( cson_cgi_cx * cx, char b ); /** Tries to guess the "best" Content-type header value for the current session, based on several factors: - If the GET/POST data contains a variable named CSON_CGI_KEY_JSONP then "application/javascript" is returned. - If the HTTP_ACCEPT environment variable is NOT set or contains "application/json" then "application/json [possibly charset info]" is returned. - If the HTTP_ACCEPT environment variable is set but does not contain "application/json" then "text/javascript" is returned. - If cson_cgi_enable_jsonp() is called and passed a true value, "application/javascript" is returned. If HTTP_ACCEPT_CHARSET is NOT set or contains "utf-8" then ";charset=utf-8" is included in the the returned string. The returned string is static and immutable and suitable for use as a Content-type header value. The string is guaranteed to be valid until the application exits. Multiple calls to this function, with different underlying environment data, can cause different results to be returned. Returns NULL if it absolutely cannot figure out what to do, but currently it has no such logic paths. */ char const * cson_cgi_guess_content_type(cson_cgi_cx * cx); /** Sets the response content root, replacing any existing one (and possibly cleaning it up). Returns 0 on success. On success, ownership of v is transfered to (or shared with) the cson_cgi API. It will be cleaned up at app shutdown time or if it is subsequently replaced and has no other open references to it. On error ownership of v is not modified and any previous root is not removed. If v is-not-a Object or Array, nor NULL, then cson_rc.TypeError is returned. JSON requires either an object or array for the root node. Passing NULL will possibly free up any current root (depending on its reference count). */ int cson_cgi_response_root_set( cson_cgi_cx * cx, cson_value * v ); /** Fetches the current content root JSON value, as set via cson_cgi_response_root_set() or (if no root has been set), as defined by createMode, as described below. If a content root has been set (or previously initialized) then the value of createMode is ignored. If no root has been set then this function might try to create one, as described here: (createMode==0) means not to create a root element if none exists already. (createMode<0) means to create the root as an Array value. (createMode>0) means to create the root as an Object value. Returns NULL on allocation error or if no root has been set and (createMode==0). On success the returned value is guaranteed to be either an Array or Object (see cson_value_get_object() and cson_value_get_array()) and it is owned by the cson_cgi API (so it must not be destroyed by the caller). If the client needs to destroy it, pass NULL to cson_cgi_response_root_set(). */ cson_value * cson_cgi_response_root_get( cson_cgi_cx * cx, char createMode ); /** Returns the current session ID. If session management is not enabled then NULL is returned. The returned bytes are owned by the cson_cgi API and are valid until the library is cleaned up (via cson_cgi_cleanup_lib() or via the normal shutdown process) or the session ID is re-generated for some reason. It is best not to hold a reference to this, but to copy it if it will be needed later. If the return value is not NULL, it is guaranteed to be NUL-terminated. */ char const * cson_cgi_session_id(cson_cgi_cx *); /** Writes a 36-byte (plus one NUL byte) random UUID value to dest. dest must be at least 37 bytes long. If dest is NULL this function has no side effects. This function uses internal RNG state and is not thread-safe. */ void cson_cgi_generate_uuid( cson_cgi_cx * cx, char * dest ); /** Adds v to the API-internal cleanup mechanism. key must be a unique key for the given element. Adding another item with that key may free the previous one. If freeOnError is true then v is passed to cson_value_free() if the key cannot be inserted, otherweise ownership of v is not changed on error. Returns 0 on success. On success, ownership of v is transfered to (or shared with) cx, and v will be valid until cx is cleaned up or its key is replaced via another call to this function. */ int cson_cgi_gc_add( cson_cgi_cx * cx, char const * key, cson_value * v, char freeOnError ); /* LICENSE This software's source code, including accompanying documentation and demonstration applications, are licensed under the following conditions... Certain files are imported from external projects and have their own licensing terms. Namely, the JSON_parser.* files. See their files for their official licenses, but the summary is "do what you want [with them] but leave the license text and copyright in place." The author (Stephan G. Beal [http://wanderinghorse.net/home/stephan/]) explicitly disclaims copyright in all jurisdictions which recognize such a disclaimer. In such jurisdictions, this software is released into the Public Domain. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 2011), this software is Copyright (c) 2011 by Stephan G. Beal, and is released under the terms of the MIT License (see below). In jurisdictions which recognize Public Domain property, the user of this software may choose to accept it either as 1) Public Domain, 2) under the conditions of the MIT License (see below), or 3) under the terms of dual Public Domain/MIT License conditions described here, as they choose. The MIT License is about as close to Public Domain as a license can get, and is described in clear, concise terms at: http://en.wikipedia.org/wiki/MIT_License The full text of the MIT License follows: -- Copyright (c) 2011 Stephan G. Beal (http://wanderinghorse.net/home/stephan/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --END OF MIT LICENSE-- For purposes of the above license, the term "Software" includes documentation and demonstration source code which accompanies this software. ("Accompanies" = is contained in the Software's primary public source code repository.) */ #if defined(__cplusplus) } /*extern "C"*/ #endif #endif /* WANDERINGHORSE_NET_CSON_CGI_H_INCLUDED */ /* end file include/wh/cson/cson_cgi.h */ |
Changes to src/db.c.
︙ | ︙ | |||
54 55 56 57 58 59 60 61 62 63 64 65 66 67 | /* ** Call this routine when a database error occurs. */ static void db_err(const char *zFormat, ...){ va_list ap; char *z; static const char zRebuildMsg[] = "If you have recently updated your fossil executable, you might\n" "need to run \"fossil all rebuild\" to bring the repository\n" "schemas up to date.\n"; va_start(ap, zFormat); z = vmprintf(zFormat, ap); va_end(ap); | > > > > > > > | | | | | | | | | | | | | > > | | 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | /* ** Call this routine when a database error occurs. */ static void db_err(const char *zFormat, ...){ va_list ap; char *z; int rc = 1; static const char zRebuildMsg[] = "If you have recently updated your fossil executable, you might\n" "need to run \"fossil all rebuild\" to bring the repository\n" "schemas up to date.\n"; va_start(ap, zFormat); z = vmprintf(zFormat, ap); va_end(ap); if( g.json.isJsonMode ){ json_err( 0, z, 1 ); if( g.isCGI ){ rc = 0 /* avoid HTTP 500 */; } }else{ if( g.xferPanic ){ cgi_reset_content(); @ error Database\serror:\s%F(z) cgi_reply(); } if( g.cgiOutput ){ g.cgiOutput = 0; cgi_printf("<h1>Database Error</h1>\n" "<pre>%h</pre><p>%s</p>", z, zRebuildMsg); cgi_reply(); }else{ fprintf(stderr, "%s: %s\n\n%s", fossil_nameofexe(), z, zRebuildMsg); } } free(z); db_force_rollback(); fossil_exit(rc); } static int nBegin = 0; /* Nesting depth of BEGIN */ static int doRollback = 0; /* True to force a rollback */ static int nCommitHook = 0; /* Number of commit hooks */ static struct sCommitHook { int (*xHook)(void); /* Functions to call at db_end_transaction() */ |
︙ | ︙ |
Added src/json.c.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 | /* ** Copyright (c) 2007 D. Richard Hipp ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the Simplified BSD License (also ** known as the "2-Clause License" or "FreeBSD License".) ** This program is distributed in the hope that it will be useful, ** but without any warranty; without even the implied warranty of ** merchantability or fitness for a particular purpose. ** ** Author contact information: ** drh@hwaci.com ** http://www.hwaci.com/drh/ ** ******************************************************************************* ** ** Code for the JSON/REST API. ** ** For notes regarding the public JSON interface, please see: ** ** https://docs.google.com/document/d/1fXViveNhDbiXgCuE7QDXQOKeFzf2qNUkBEgiUvoqFN4/edit ** */ #include "config.h" #include "VERSION.h" #include "json.h" #include <assert.h> #include <time.h> #if INTERFACE #include "cson_amalgamation.h" /* ** The "official" list of Fossil/JSON error codes. ** Their values might very well change during initial ** development but after their first public release ** they must stay stable. ** Values must be in the range 1..9999 ** ** Numbers evenly dividable by 100 are "categories", ** and error codes for a given category have their ** high bits set to the category value. ** */ enum FossilJsonCodes { FSL_JSON_E_GENERIC = 1000, FSL_JSON_E_INVALID_REQUEST = FSL_JSON_E_GENERIC + 1, FSL_JSON_E_UNKNOWN_COMMAND = FSL_JSON_E_GENERIC + 2, FSL_JSON_E_UNKNOWN = FSL_JSON_E_GENERIC + 3, FSL_JSON_E_RESOURCE_NOT_FOUND = FSL_JSON_E_GENERIC + 4, FSL_JSON_E_TIMEOUT = FSL_JSON_E_GENERIC + 5, FSL_JSON_E_ASSERT = FSL_JSON_E_GENERIC + 6, FSL_JSON_E_ALLOC = FSL_JSON_E_GENERIC + 7, FSL_JSON_E_NYI = FSL_JSON_E_GENERIC + 8, FSL_JSON_E_AUTH = 2000, FSL_JSON_E_LOGIN_FAILED = FSL_JSON_E_AUTH + 1, FSL_JSON_E_MISSING_AUTH = FSL_JSON_E_AUTH + 2, FSL_JSON_E_DENIED = FSL_JSON_E_AUTH + 3, FSL_JSON_E_WRONG_MODE = FSL_JSON_E_AUTH + 4, FSL_JSON_E_USAGE = 3000, FSL_JSON_E_INVALID_ARGS = FSL_JSON_E_USAGE + 1, FSL_JSON_E_MISSING_ARGS = FSL_JSON_E_USAGE + 2, FSL_JSON_E_DB = 4000, FSL_JSON_E_STMT_PREP = FSL_JSON_E_DB + 1, FSL_JSON_E_STMT_BIND = FSL_JSON_E_DB + 2, FSL_JSON_E_STMT_EXEC = FSL_JSON_E_DB + 3, FSL_JSON_E_DB_LOCKED = FSL_JSON_E_DB + 4, }; #endif /* ** Holds keys used for various JSON API properties. */ static const struct FossilJsonKeys_{ char const * authToken; } FossilJsonKeys = { "authToken" /*authToken*/ }; /* ** Given a FossilJsonCodes value, it returns a string suitable for use ** as a resultText string. Returns some unspecified string if errCode ** is not one of the FossilJsonCodes values. */ char const * json_err_str( int errCode ){ switch( errCode ){ case 0: return "Success"; #define C(X,V) case FSL_JSON_E_ ## X: return V C(GENERIC,"Generic error"); C(INVALID_REQUEST,"Invalid request"); C(UNKNOWN_COMMAND,"Unknown Command"); C(UNKNOWN,"Unknown error"); C(RESOURCE_NOT_FOUND,"Resource not found"); C(TIMEOUT,"Timeout reached"); C(ASSERT,"Assertion failed"); C(ALLOC,"Resource allocation failed"); C(NYI,"Not yet implemented."); C(AUTH,"Authentication error"); C(LOGIN_FAILED,"Login failed"); C(MISSING_AUTH,"Authentication info missing from request"); C(DENIED,"Access denied"); C(WRONG_MODE,"Request not allowed (wrong operation mode)"); C(USAGE,"Usage error"); C(INVALID_ARGS,"Invalid arguments"); C(MISSING_ARGS,"Missing arguments"); C(DB,"Database error"); C(STMT_PREP,"Statement preparation failed"); C(STMT_BIND,"Statement parameter binding failed"); C(STMT_EXEC,"Statement execution/stepping failed"); C(DB_LOCKED,"Database is locked"); #undef C default: return "Unknown Error"; } } /* ** Implements the cson_data_dest_f() interface and outputs the data to ** a fossil Blob object. pState must be-a initialized (Blob*), to ** which n bytes of src will be appended. **/ int cson_data_dest_Blob(void * pState, void const * src, unsigned int n){ Blob * b = (Blob*)pState; blob_append( b, (char const *)src, (int)n ) /* will die on OOM */; return 0; } /* ** Implements the cson_data_source_f() interface and reads ** input from a fossil Blob object. pState must be-a (Blob*). */ int cson_data_src_Blob(void * pState, void * dest, unsigned int * n){ Blob * b = (Blob*)pState; *n = blob_read( b, dest, *n ); return 0; } /* ** Convenience wrapper around cson_output() which appends the output ** to pDest. pOpt may be NULL, in which case g.json.outOpt will be used. */ int cson_output_Blob( cson_value const * pVal, Blob * pDest, cson_output_opt const * pOpt ){ return cson_output( pVal, cson_data_dest_Blob, pDest, pOpt ? pOpt : &g.json.outOpt ); } /* ** Convenience wrapper around cson_parse() which reads its input ** from pSrc. pSrc is rewound before parsing. ** ** pInfo may be NULL. If it is not NULL then it will contain details ** about the parse state when this function returns. ** ** On success a new JSON Object or Array is returned. On error NULL is ** returned. */ cson_value * cson_parse_Blob( Blob * pSrc, cson_parse_info * pInfo ){ cson_value * root = NULL; blob_rewind( pSrc ); cson_parse( &root, cson_data_src_Blob, pSrc, NULL, pInfo ); return root; } /* ** Returns a string in the form FOSSIL-XXXX, where XXXX is a ** left-zero-padded value of code. The returned buffer is static, and ** must be copied if needed for later. The returned value will always ** be 11 bytes long (not including the trailing NUL byte). ** ** In practice we will only ever call this one time per app execution ** when constructing the JSON response envelope, so the static buffer ** "shouldn't" be a problem. ** */ char const * json_rc_cstr( int code ){ enum { BufSize = 12 }; static char buf[BufSize] = {'F','O','S','S','I','L','-',0}; sprintf(buf+7,"%04d", code); return buf; } /* ** Returns the value of json_rc_cstr(code) as a new JSON ** string, which is owned by the caller and must eventually ** be cson_value_free()d or transfered to a JSON container. */ cson_value * json_rc_string( int code ){ return cson_value_new_string( json_rc_cstr(code), 11 ); } /* ** UNTESTED!!! ** ** Returns the current request's JSON authentication token, or NULL if ** none is found. The token's memory is owned by (or shared with) ** g.json.cgiCx. ** ** If an auth token is found in the GET/POST JSON request data then ** fossil is given that data for use in authentication for this ** session. ** ** Must be called once before login_check_credentials() is called or ** we will not be able to replace fossil's internal idea of the auth ** info in time (and future changes to that state may cause unexpected ** results). ** ** The result of this call are cached for future calls. */ static cson_value * json_auth_token(){ if( !g.json.authToken ){ /* Try to get an authorization token from GET parameter, POSTed JSON, or fossil cookie (in that order). */ g.json.authToken = cson_cgi_getenv(&g.json.cgiCx, "gp", FossilJsonKeys.authToken) /* reminder to self: cson_cgi does not have access to the cookies because fossil's core consumes them. Thus we cannot use "gpc" here. */; if( g.json.authToken){ /* tell fossil to use this login info. FIXME: because the JSON bits don't carry around login_cookie_name(), there is a login hijacking window here. We need to change the JSON auth token to be in the form: login_cookie_name()=... */ cgi_replace_parameter( login_cookie_name(), cson_value_get_cstr(g.json.authToken) ); } else if( g.isCGI ){ /* try fossil's conventional cookie. */ /* Reminder: chicken/egg scenario regarding db access in CLI mode because login_cookie_name() needs the db. */ char const * zCookie = P(login_cookie_name()); if( zCookie && *zCookie ){ /* Transfer fossil's cookie to JSON for downstream convenience... */ cson_value * v = cson_value_new_string(zCookie, strlen(zCookie)); if( 0 == cson_cgi_gc_add( &g.json.cgiCx, FossilJsonKeys.authToken, v, 1 ) ){ g.json.authToken = v; } } } } return g.json.authToken; } /* ** Performs some common initialization of JSON-related state. ** Implicitly sets up the login information state in CGI mode, ** but does not perform any authentication here. It _might_ ** (haven't tested this) die with an error if an auth cookie ** is malformed. */ static void json_mode_bootstrap(){ g.json.isJsonMode = 1; g.json.resultCode = 0; #if defined(NDEBUG) /* avoids debug messages on stderr in JSON mode */ sqlite3_config(SQLITE_CONFIG_LOG, NULL, 0); #endif g.json.reqPayload.v = cson_cgi_getenv( &g.json.cgiCx, "p", "payload" ); if( g.json.reqPayload.v ){ g.json.reqPayload.o = cson_value_get_object( g.json.reqPayload.v ); if( ! g.json.reqPayload.o ){/* POST data is an array, which we can't use. */ assert( cson_value_is_array( g.json.reqPayload.v ) ); g.json.reqPayload.v = NULL; } } json_auth_token()/* will copy our auth token, if any, to fossil's core. */; if( g.isCGI ){ login_check_credentials(); } else{ db_find_and_open_repository(OPEN_ANY_SCHEMA,0); } } /* ** If g.json.reqPayload.o is NULL then NULL is returned, else the ** given property is searched for in the request payload. If found it ** is returned. The returned value is owned by (or shares ownership ** with) g.json.cgiCx, and must NOT be cson_value_free()'d by the ** caller. */ static cson_value * json_payload_property( char const * key ){ return g.json.reqPayload.o ? cson_object_get( g.json.reqPayload.o, key ) : NULL; } /* Returns the C-string form of json_auth_token(), or NULL ** if json_auth_token() returns NULL. */ char const * json_auth_token_cstr() { return cson_value_get_cstr( json_auth_token() ); } /* ** Holds name-to-function mappings for JSON page/command dispatching. ** */ typedef struct JsonPageDef{ /* ** The commmand/page's name (path, not including leading /json/). ** ** Reminder to self: we cannot use sub-paths with commands this way ** without additional string-splitting downstream. e.g. foo/bar. ** Alternately, we can create different JsonPageDef arrays for each ** subset. */ char const * name; /* ** Returns a payload object for the response. ** If it returns a non-NULL value, the caller owns it. */ cson_value * (*func)(); /* ** Which mode(s) of execution does func() support: ** ** <0 = CLI only, >0 = HTTP only, 0==both */ char runMode; } JsonPageDef; /* ** Returns the JsonPageDef with the given name, or NULL if no match is ** found. ** ** head must be a pointer to an array of JsonPageDefs in which the ** last entry has a NULL name. */ static JsonPageDef const * json_handler_for_name( char const * name, JsonPageDef const * head ){ JsonPageDef const * pageDef = head; assert( head != NULL ); if(name && *name) for( ; pageDef->name; ++pageDef ){ if( 0 == strcmp(name, pageDef->name) ){ return pageDef; } } return NULL; } /* ** Given a Fossil/JSON result code, this function "dumbs it down" ** according to the current value of g.json.errorDetailParanoia. The ** dumbed-down value is returned. ** ** This function assert()s that code is either 0 ** or between the range of 1000 and 9999. */ static int json_dumbdown_rc( int code ){ if( !code ){ return 0; }else{ int modulo = 0; assert((code >= 1000) && (code <= 9999) && "Invalid Fossil/JSON code."); switch( g.json.errorDetailParanoia ){ case 1: modulo = 10; break; case 2: modulo = 100; break; case 3: modulo = 1000; break; default: break; } if( modulo ) code = code - (code % modulo); return code; } } /* ** Creates a new Fossil/REST response envelope skeleton. It is owned ** by the caller, who must eventually free it using cson_value_free(), ** or add it to a cson container to transfer ownership. Returns NULL ** on error. ** ** If payload is not NULL and resultCode is 0 then it is set as the ** "payload" property of the returned object. If resultCode is non-0 ** then this function will destroy payload if it is not NULL. ** ** pMsg is an optional message string (resultText) property of the ** response. If resultCode is non-0 and pMsg is NULL then ** json_err_str() is used to get the error string. The caller may ** provide his own or may use an empty string to suppress the ** resultText property. ** ** If resultCode is non-zero and payload is not NULL then this ** function calls cson_value_free(payload) and does not insert the ** payload into the response. ** */ cson_value * json_response_skeleton( int resultCode, cson_value * payload, char const * pMsg ){ cson_value * v = NULL; cson_value * tmp = NULL; cson_object * o = NULL; int rc; resultCode = json_dumbdown_rc(resultCode); v = cson_value_new_object(); o = cson_value_get_object(v); if( ! o ) return NULL; #define SET(K) if(!tmp) goto cleanup; \ rc = cson_object_set( o, K, tmp ); \ if(rc) do{\ cson_value_free(tmp); \ tmp = NULL; \ goto cleanup; \ }while(0) tmp = cson_value_new_string(MANIFEST_UUID,strlen(MANIFEST_UUID)); SET("fossil"); {/* "timestamp" */ time_t const t = (time_t)g.now; struct tm gt = *gmtime(&t); cson_int_t jsTime = (cson_int_t)mktime(>); tmp = cson_value_new_integer(jsTime); SET("timestamp"); } if( 0 != resultCode ){ if( ! pMsg ) pMsg = json_err_str(resultCode); tmp = json_rc_string(resultCode); SET("resultCode"); } if( pMsg && *pMsg ){ tmp = cson_value_new_string(pMsg,strlen(pMsg)); SET("resultText"); } tmp = cson_cgi_getenv(&g.json.cgiCx, "gp", "requestId"); if( tmp ) cson_object_set( o, "requestId", tmp ); if( NULL != payload ){ if( resultCode ){ cson_value_free(payload); payload = NULL; }else{ tmp = payload; SET("payload"); } } #undef SET goto ok; cleanup: cson_value_free(v); v = NULL; ok: return v; } /* ** Outputs a JSON error response to g.httpOut. If rc is 0 then ** g.json.resultCode is used. If that is also 0 then the "Unknown ** Error" code is used. ** ** If g.isCGI then the generated error object replaces any currently ** buffered page output. ** ** If alsoOutput is true AND g.isCGI then the cgi_reply() is called to ** flush the output (and headers). Generally only do this if you are about ** to call exit(). ** ** !g.isCGI then alsoOutput is ignored and all output is sent to ** stdout immediately. ** ** This clears any previously buffered CGI content, replacing it with ** JSON. */ void json_err( int code, char const * msg, char alsoOutput ){ int rc = code ? code : (g.json.resultCode ? g.json.resultCode : FSL_JSON_E_UNKNOWN); cson_value * resp = NULL; rc = json_dumbdown_rc(rc); if( rc && !msg ){ msg = json_err_str(rc); } resp = json_response_skeleton(rc, NULL, msg); if( g.isCGI ){ Blob buf = empty_blob; cgi_reset_content(); cson_output_Blob( resp, &buf, &g.json.outOpt ); cgi_set_content(&buf); if( alsoOutput ){ cgi_reply(); } }else{ cson_output_FILE( resp, stdout, &g.json.outOpt ); } cson_value_free(resp); } /* ** /json/version implementation. ** ** Returns the payload object (owned by the caller). */ cson_value * json_page_version(void){ cson_value * jval = NULL; cson_object * jobj = NULL; jval = cson_value_new_object(); jobj = cson_value_get_object(jval); #define FSET(X,K) cson_object_set( jobj, K, cson_value_new_string(X,strlen(X))) FSET(MANIFEST_UUID,"manifestUuid"); FSET(MANIFEST_VERSION,"manifestVersion"); FSET(MANIFEST_DATE,"manifestDate"); FSET(MANIFEST_YEAR,"manifestYear"); FSET(RELEASE_VERSION,"releaseVersion"); #undef FSET cson_object_set( jobj, "releaseVersionNumber", cson_value_new_integer(RELEASE_VERSION_NUMBER) ); return jval; } static cson_value * json_getenv( char const *zWhichEnv, char const * zKey ){ return cson_cgi_getenv(&g.json.cgiCx, zWhichEnv, zKey); } static char const * json_getenv_cstr( char const *zWhichEnv, char const * zKey ){ return cson_value_get_cstr( json_getenv(zWhichEnv, zKey) ); } /* ** Implementation for /json/cap ** ** Returned object contains details about the "capabilities" of the ** current user (what he may/may not do). ** ** This is primarily intended for debuggering, but may have ** a use in client code. (?) */ cson_value * json_page_cap(void){ cson_value * payload = cson_value_new_object(); cson_object * obj = cson_value_get_object(payload); #define ADD(X) cson_object_set(obj, #X, cson_value_new_bool(g.perm.X)) ADD(Setup); ADD(Admin); ADD(Delete); ADD(Password); ADD(Query); ADD(Write); ADD(Read); ADD(History); ADD(Clone); ADD(RdWiki); ADD(NewWiki); ADD(ApndWiki); ADD(WrWiki); ADD(RdTkt); ADD(NewTkt); ADD(ApndTkt); ADD(WrTkt); ADD(Attach); ADD(TktFmt); ADD(RdAddr); ADD(Zip); ADD(Private); #undef ADD return payload; } /* ** Implementation of the /json/login page. ** ** NOT YET FINSIHED! ** TODOs: ** ** - anonymous user login (requires separate handling ** due to random password). ** ** - more testing */ cson_value * json_page_login(void){ char const * name = cson_value_get_cstr(json_payload_property("name")); char const * pw; cson_value * payload = NULL; /*cson_object * pObj;*/ int uid = 0; /*return cson_cgi_env_get_val(&g.json.cgiCx,'g',0);*/ if( !name ){ name = json_getenv_cstr( "g", "name" ) /* When i use P("n") i'm not getting the result i expect! */ ; if( !name ){ name = json_getenv_cstr( "g", "n" ); } } if( !name ){ g.json.resultCode = FSL_JSON_E_LOGIN_FAILED; return NULL; } pw = cson_value_get_cstr(json_payload_property("password")); if( !pw ){ pw = json_getenv_cstr( "g", "password" ); if( !pw ){ pw = json_getenv_cstr( "g", "p" ); } } if(!pw){ g.json.resultCode = FSL_JSON_E_LOGIN_FAILED; }else{ uid = login_search_uid( name, pw ); } if( !uid ){ g.json.resultCode = FSL_JSON_E_LOGIN_FAILED; }else{ char * cookie = NULL; login_set_user_cookie(name, uid, &cookie); payload = cson_value_new_string( cookie, strlen(cookie) ); free(cookie); } return payload; } /* ** Implementation of the /json/stat page/command. ** */ cson_value * json_page_stat(void){ i64 t, fsize; int n, m; const char *zDb; enum { BufLen = 200 }; char zBuf[BufLen]; cson_value * jv = NULL; cson_object * jo = NULL; cson_value * jv2 = NULL; cson_object * jo2 = NULL; #if 0 /* FIXME: credentials */ login_check_credentials(); if( !g.okRead ){ login_needed(); return NULL; } #endif #define SETBUF(O,K) cson_object_set(O, K, cson_value_new_string(zBuf, strlen(zBuf))); jv = cson_value_new_object(); jo = cson_value_get_object(jv); sqlite3_snprintf(BufLen, zBuf, db_get("project-name","")); SETBUF(jo, "projectName"); /* FIXME: don't include project-description until we ensure that zBuf will always be big enough. We "should" replace zBuf with a blob for this purpose. */ fsize = file_size(g.zRepositoryName); cson_object_set(jo, "repositorySize", cson_value_new_integer((cson_int_t)fsize)); n = db_int(0, "SELECT count(*) FROM blob"); m = db_int(0, "SELECT count(*) FROM delta"); cson_object_set(jo, "blobCount", cson_value_new_integer((cson_int_t)n)); cson_object_set(jo, "deltaCount", cson_value_new_integer((cson_int_t)m)); if( n>0 ){ int a, b; Stmt q; db_prepare(&q, "SELECT total(size), avg(size), max(size)" " FROM blob WHERE size>0"); db_step(&q); t = db_column_int64(&q, 0); cson_object_set(jo, "uncompressedArtifactSize", cson_value_new_integer((cson_int_t)t)); cson_object_set(jo, "averageArtifactSize", cson_value_new_integer((cson_int_t)db_column_int(&q, 1))); cson_object_set(jo, "maxArtifactSize", cson_value_new_integer((cson_int_t)db_column_int(&q, 2))); db_finalize(&q); if( t/fsize < 5 ){ b = 10; fsize /= 10; }else{ b = 1; } a = t/fsize; sqlite3_snprintf(BufLen,zBuf, "%d:%d", a, b); SETBUF(jo, "compressionRatio"); } n = db_int(0, "SELECT count(distinct mid) FROM mlink /*scan*/"); cson_object_set(jo, "checkinCount", cson_value_new_integer((cson_int_t)n)); n = db_int(0, "SELECT count(*) FROM filename /*scan*/"); cson_object_set(jo, "fileCount", cson_value_new_integer((cson_int_t)n)); n = db_int(0, "SELECT count(*) FROM tag /*scan*/" " WHERE +tagname GLOB 'wiki-*'"); cson_object_set(jo, "wikiPageCount", cson_value_new_integer((cson_int_t)n)); n = db_int(0, "SELECT count(*) FROM tag /*scan*/" " WHERE +tagname GLOB 'tkt-*'"); cson_object_set(jo, "ticketCount", cson_value_new_integer((cson_int_t)n)); n = db_int(0, "SELECT julianday('now') - (SELECT min(mtime) FROM event)" " + 0.99"); cson_object_set(jo, "ageDays", cson_value_new_integer((cson_int_t)n)); cson_object_set(jo, "ageYears", cson_value_new_double(n/365.24)); sqlite3_snprintf(BufLen, zBuf, db_get("project-code","")); SETBUF(jo, "projectCode"); sqlite3_snprintf(BufLen, zBuf, db_get("server-code","")); SETBUF(jo, "serverCode"); cson_object_set(jo, "compiler", cson_value_new_string(COMPILER_NAME, strlen(COMPILER_NAME))); jv2 = cson_value_new_object(); jo2 = cson_value_get_object(jv2); cson_object_set(jo, "sqlite", jv2); sqlite3_snprintf(BufLen, zBuf, "%.19s [%.10s] (%s)", SQLITE_SOURCE_ID, &SQLITE_SOURCE_ID[20], SQLITE_VERSION); SETBUF(jo2, "version"); zDb = db_name("repository"); cson_object_set(jo2, "pageCount", cson_value_new_integer((cson_int_t)db_int(0, "PRAGMA %s.page_count", zDb))); cson_object_set(jo2, "pageSize", cson_value_new_integer((cson_int_t)db_int(0, "PRAGMA %s.page_size", zDb))); cson_object_set(jo2, "freeList", cson_value_new_integer((cson_int_t)db_int(0, "PRAGMA %s.freelist_count", zDb))); sqlite3_snprintf(BufLen, zBuf, "%s", db_text(0, "PRAGMA %s.encoding", zDb)); SETBUF(jo2, "encoding"); sqlite3_snprintf(BufLen, zBuf, "%s", db_text(0, "PRAGMA %s.journal_mode", zDb)); cson_object_set(jo2, "journalMode", *zBuf ? cson_value_new_string(zBuf, strlen(zBuf)) : cson_value_null()); return jv; #undef SETBUF } /* ** Implements the /json/wiki family of pages/commands. Far from ** complete. ** */ cson_value * json_page_wiki(void){ cson_value * jlist = NULL; cson_value * rows = NULL; Stmt q; wiki_prepare_page_list(&q); cson_sqlite3_stmt_to_json( q.pStmt, &jlist, 1 ); db_finalize(&q); assert( NULL != jlist ); rows = cson_object_take( cson_value_get_object(jlist), "rows" ); assert( NULL != rows ); cson_value_free( jlist ); return rows; } /* ** Mapping of names to JSON pages/commands. Each name is a subpath of ** /json (in CGI mode) or a subcommand of the json command in CLI mode */ static const JsonPageDef JsonPageDefs[] = { /* please keep alphabetically sorted (case-insensitive) for maintenance reasons. */ {"cap", json_page_cap, 0}, {"HAI",json_page_version,0}, {"login",json_page_login,1/*should be >0. Only 0 for dev/testing purposes.*/}, {"stat",json_page_stat,0}, {"version",json_page_version,0}, {"wiki",json_page_wiki,0}, /* Last entry MUST have a NULL name. */ {NULL,NULL} }; /* ** WEBPAGE: /json ** ** Pages under /json/... must be entered into JsonPageDefs. */ void json_page_top(void){ int rc = FSL_JSON_E_UNKNOWN_COMMAND; Blob buf = empty_blob; char const * cmd; cson_value * payload = NULL; cson_value * root = NULL; JsonPageDef const * pageDef = NULL; json_mode_bootstrap(); cmd = cson_cgi_path_part_cstr(&g.json.cgiCx,1); pageDef = json_handler_for_name(cmd,&JsonPageDefs[0]); cgi_set_content_type( cson_cgi_guess_content_type(&g.json.cgiCx) ); if( ! pageDef ){ json_err( FSL_JSON_E_UNKNOWN_COMMAND, NULL, 0 ); return; }else if( pageDef->runMode < 0 /*CLI only*/) { rc = FSL_JSON_E_WRONG_MODE; }else{ rc = 0; payload = (*pageDef->func)(); } /* FIXME: we need a way of channeling resultCode values back here. */ if( g.json.resultCode ){ json_err(g.json.resultCode, NULL, 0); }else{ blob_zero(&buf); root = json_response_skeleton(rc, payload, NULL); cson_output_Blob( root, &buf, NULL ); cson_value_free(root); cgi_set_content(&buf)/*takes ownership of the buf memory*/; } } /* ** COMMAND: json ** ** Usage: %fossil json subcommand ** ** The commands include: ** ** stat ** version (alias: HAI) ** ** ** TODOs: ** ** wiki ** timeline ** tickets ** ... ** */ void json_cmd_top(void){ char const * cmd = NULL; unsigned int n; int rc = 1002; cson_value * payload = NULL; JsonPageDef const * pageDef; json_mode_bootstrap(); db_find_and_open_repository(0, 0); if( g.argc<3 ){ goto usage; } cmd = g.argv[2]; n = cmd ? strlen(cmd) : 0; if( n==0 ){ goto usage; } cgi_set_content_type( cson_cgi_guess_content_type(&g.json.cgiCx) ); pageDef = json_handler_for_name(cmd,&JsonPageDefs[0]); if( ! pageDef ){ json_err( FSL_JSON_E_UNKNOWN_COMMAND, NULL, 0 ); return; }else if( pageDef->runMode > 0 /*HTTP only*/) { rc = FSL_JSON_E_WRONG_MODE; }else{ rc = 0; payload = (pageDef->func)(); } if( g.json.resultCode ){ json_err(g.json.resultCode, NULL, 1); }else{ payload = json_response_skeleton(rc, payload, NULL); cson_output_FILE( payload, stdout, &g.json.outOpt ); cson_value_free( payload ); if((0 != rc) && !g.isCGI){ /* FIXME: we need a way of passing this error back up to the routine which called this callback. e.g. add g.errCode. */ exit(1); } } return; usage: usage("subcommand"); } |
Changes to src/login.c.
︙ | ︙ | |||
82 83 84 85 86 87 88 | /* ** Return the name of the login cookie. ** ** The login cookie name is always of the form: fossil-XXXXXXXXXXXXXXXX ** where the Xs are the first 16 characters of the login-group-code or ** of the project-code if we are not a member of any login-group. */ | | | 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | /* ** Return the name of the login cookie. ** ** The login cookie name is always of the form: fossil-XXXXXXXXXXXXXXXX ** where the Xs are the first 16 characters of the login-group-code or ** of the project-code if we are not a member of any login-group. */ char *login_cookie_name(void){ static char *zCookieName = 0; if( zCookieName==0 ){ zCookieName = db_text(0, "SELECT 'fossil-' || substr(value,1,16)" " FROM config" " WHERE name IN ('project-code','login-group-code')" " ORDER BY name;" |
︙ | ︙ | |||
139 140 141 142 143 144 145 146 147 148 | return mprintf("%.16s", zFullCode); } /* ** Check to see if the anonymous login is valid. If it is valid, return ** the userid of the anonymous user. */ static int isValidAnonymousLogin( const char *zUsername, /* The username. Must be "anonymous" */ | > > > | > < | > | < < | 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | return mprintf("%.16s", zFullCode); } /* ** Check to see if the anonymous login is valid. If it is valid, return ** the userid of the anonymous user. ** ** The zCS parameter is the "captcha seed" used for a specific ** anonymous login request. */ static int isValidAnonymousLogin( const char *zUsername, /* The username. Must be "anonymous" */ const char *zPassword, /* The supplied password */ const char *zCS /* The captcha seed value */ ){ const char *zPw; /* The correct password shown in the captcha */ int uid; /* The user ID of anonymous */ if( zUsername==0 ) return 0; else if( zPassword==0 ) return 0; else if( zCS==0 ) return 0; else if( fossil_strcmp(zUsername,"anonymous")!=0 ) return 0; zPw = captcha_decode((unsigned int)atoi(zCS)); if( fossil_stricmp(zPw, zPassword)!=0 ) return 0; uid = db_int(0, "SELECT uid FROM user WHERE login='anonymous'" " AND length(pw)>0 AND length(cap)>0"); return uid; } |
︙ | ︙ | |||
190 191 192 193 194 195 196 197 198 199 200 201 202 203 | create_accesslog_table(); db_multi_exec( "INSERT INTO accesslog(uname,ipaddr,success,mtime)" "VALUES(%Q,%Q,%d,julianday('now'));", zUsername, zIpAddr, bSuccess ); } /* ** WEBPAGE: login ** WEBPAGE: logout ** WEBPAGE: my ** ** Generate the login page. | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | create_accesslog_table(); db_multi_exec( "INSERT INTO accesslog(uname,ipaddr,success,mtime)" "VALUES(%Q,%Q,%d,julianday('now'));", zUsername, zIpAddr, bSuccess ); } /* ** Searches for the user ID matching the given name and password. ** On success it returns a positive value. On error it returns 0. ** On serious (DB-level) error it will probably exit. ** ** zPassword may be either the plain-text form or the encrypted ** form of the user's password. */ int login_search_uid(char const *zUsername, char const *zPasswd){ char * zSha1Pw = sha1_shared_secret(zPasswd, zUsername, 0); int const uid = db_int(0, "SELECT uid FROM user" " WHERE login=%Q" " AND length(cap)>0 AND length(pw)>0" " AND login NOT IN ('anonymous','nobody','developer','reader')" " AND (pw=%Q OR pw=%Q)", zUsername, zPasswd, zSha1Pw ); free(zSha1Pw); return uid; } /* ** Generates a login cookie value for a non-anonymous user. ** ** The zHash parameter must be a random value which must be ** subsequently stored in user.cookie for later validation. ** ** The returned memory should be free()d after use. */ char * login_gen_user_cookie_value(char const *zUsername, char const * zHash){ char *zCode = abbreviated_project_code(db_get("project-code","")); assert((zUsername && *zUsername) && "Invalid user data."); return mprintf("%s/%z/%s", zHash, zCode, zUsername); } /* ** Generates a login cookie for NON-ANONYMOUS users. Note that this ** function "could" figure out the uid by itself but it currently ** doesn't because the code which calls this already has the uid. ** ** This function also updates the user.cookie, user.ipaddr, ** and user.cexpire fields for the given user. ** ** If zDest is not NULL then the generated cookie is copied to ** *zDdest and ownership is transfered to the caller (who should ** eventually pass it to free()). */ void login_set_user_cookie( char const * zUsername, /* User's name */ int uid, /* User's ID */ char ** zDest /* Optional: store generated cookie value. */ ){ const char *zCookieName = login_cookie_name(); const char *zExpire = db_get("cookie-expire","8766"); int expires = atoi(zExpire)*3600; char *zHash; char *zCookie; char const * zIpAddr = PD("REMOTE_ADDR","nil"); /* Complete IP address for logging */ char * zRemoteAddr = ipPrefix(zIpAddr); /* Abbreviated IP address */ assert((zUsername && *zUsername) && (uid > 0) && "Invalid user data."); zHash = db_text(0, "SELECT hex(randomblob(25))"); zCookie = login_gen_user_cookie_value(zUsername, zHash); cgi_set_cookie(zCookieName, zCookie, login_cookie_path(), expires); record_login_attempt(zUsername, zIpAddr, 1); db_multi_exec( "UPDATE user SET cookie=%Q, ipaddr=%Q, " " cexpire=julianday('now')+%d/86400.0 WHERE uid=%d", zHash, zRemoteAddr, expires, uid ); free(zRemoteAddr); free(zHash); if( zDest ){ *zDest = zCookie; }else{ free(zCookie); } } /* ** "Unsets" the login cookie (insofar as cookies can be unset) and ** clears the current user's (g.userUid) login information from the ** user table. Sets: user.cookie, user.ipaddr, user.cexpire. ** ** We could/should arguably clear out g.userUid and g.perm here, but ** we don't currently do not. ** ** This is a no-op if g.userUid is 0. */ void login_clear_login_data(){ if(!g.userUid){ return; }else{ /* To logout, change the cookie value to an empty string */ cgi_set_cookie(login_cookie_name(), "", login_cookie_path(), -86400); db_multi_exec("UPDATE user SET cookie=NULL, ipaddr=NULL, " " cexpire=0 WHERE uid=%d", g.userUid); } } /* ** WEBPAGE: login ** WEBPAGE: logout ** WEBPAGE: my ** ** Generate the login page. |
︙ | ︙ | |||
219 220 221 222 223 224 225 | char *zRemoteAddr; /* Abbreviated IP address of requestor */ login_check_credentials(); zUsername = P("u"); zPasswd = P("p"); anonFlag = P("anon")!=0; if( P("out")!=0 ){ | < | < | 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | char *zRemoteAddr; /* Abbreviated IP address of requestor */ login_check_credentials(); zUsername = P("u"); zPasswd = P("p"); anonFlag = P("anon")!=0; if( P("out")!=0 ){ login_clear_login_data(); redirect_to_g(); } if( g.perm.Password && zPasswd && (zNew1 = P("n1"))!=0 && (zNew2 = P("n2"))!=0 ){ /* The user requests a password change */ zSha1Pw = sha1_shared_secret(zPasswd, g.zLogin, 0); if( db_int(1, "SELECT 0 FROM user" " WHERE uid=%d AND (pw=%Q OR pw=%Q)", |
︙ | ︙ | |||
270 271 272 273 274 275 276 | redirect_to_g(); return; } } } zIpAddr = PD("REMOTE_ADDR","nil"); /* Complete IP address for logging */ zRemoteAddr = ipPrefix(zIpAddr); /* Abbreviated IP address */ | | | 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | redirect_to_g(); return; } } } zIpAddr = PD("REMOTE_ADDR","nil"); /* Complete IP address for logging */ zRemoteAddr = ipPrefix(zIpAddr); /* Abbreviated IP address */ uid = isValidAnonymousLogin(zUsername, zPasswd, P("cs")); if( uid>0 ){ /* Successful login as anonymous. Set a cookie that looks like ** this: ** ** HASH/TIME/anonymous ** ** Where HASH is the sha1sum of TIME/IPADDR/SECRET, in which IPADDR |
︙ | ︙ | |||
300 301 302 303 304 305 306 | cgi_set_cookie(zCookieName, zCookie, login_cookie_path(), 6*3600); record_login_attempt("anonymous", zIpAddr, 1); redirect_to_g(); } if( zUsername!=0 && zPasswd!=0 && zPasswd[0]!=0 ){ /* Attempting to log in as a user other than anonymous. */ | < < < < < < < | < < < < < < < | < < < < < < < < < | 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | cgi_set_cookie(zCookieName, zCookie, login_cookie_path(), 6*3600); record_login_attempt("anonymous", zIpAddr, 1); redirect_to_g(); } if( zUsername!=0 && zPasswd!=0 && zPasswd[0]!=0 ){ /* Attempting to log in as a user other than anonymous. */ uid = login_search_uid(zUsername, zPasswd); if( uid<=0 ){ sleep(1); zErrMsg = @ <p><span class="loginError"> @ You entered an unknown user or an incorrect password. @ </span></p> ; record_login_attempt(zUsername, zIpAddr, 0); }else{ /* Non-anonymous login is successful. Set a cookie of the form: ** ** HASH/PROJECT/LOGIN ** ** where HASH is a random hex number, PROJECT is either project ** code prefix, and LOGIN is the user name. */ login_set_user_cookie(zUsername, uid, NULL); redirect_to_g(); } } style_header("Login/Logout"); @ %s(zErrMsg) @ <form action="login" method="post"> if( P("g") ){ |
︙ | ︙ | |||
511 512 513 514 515 516 517 518 519 520 521 522 523 524 | fossil_free(zOtherRepo); return nXfer; } /* ** Lookup the uid for a user with zLogin and zCookie and zRemoteAddr. ** Return 0 if not found. */ static int login_find_user( const char *zLogin, /* User name */ const char *zCookie, /* Login cookie value */ const char *zRemoteAddr /* Abbreviated IP address for valid login */ ){ int uid; | > > > > | 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | fossil_free(zOtherRepo); return nXfer; } /* ** Lookup the uid for a user with zLogin and zCookie and zRemoteAddr. ** Return 0 if not found. ** ** Note that this only searches for logged-in entries with ** matching zCookie (user.cookie) and zRemoteAddr (user.ipaddr) ** entries. */ static int login_find_user( const char *zLogin, /* User name */ const char *zCookie, /* Login cookie value */ const char *zRemoteAddr /* Abbreviated IP address for valid login */ ){ int uid; |
︙ | ︙ |
Changes to src/main.c.
︙ | ︙ | |||
21 22 23 24 25 26 27 | #include "config.h" #include "main.h" #include <string.h> #include <time.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> | | > | 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include "config.h" #include "main.h" #include <string.h> #include <time.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> /* atexit() */ #if INTERFACE #include "cson_amalgamation.h" /* JSON API */ /* ** Number of elements in an array */ #define count(X) (sizeof(X)/sizeof(X[0])) /* |
︙ | ︙ | |||
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | FILE *httpIn; /* Accept HTTP input from here */ FILE *httpOut; /* Send HTTP output here */ int xlinkClusterOnly; /* Set when cloning. Only process clusters */ int fTimeFormat; /* 1 for UTC. 2 for localtime. 0 not yet selected */ int *aCommitFile; /* Array of files to be committed */ int markPrivate; /* All new artifacts are private if true */ int clockSkewSeen; /* True if clocks on client and server out of sync */ int urlIsFile; /* True if a "file:" url */ int urlIsHttps; /* True if a "https:" url */ int urlIsSsh; /* True if an "ssh:" url */ char *urlName; /* Hostname for http: or filename for file: */ char *urlHostname; /* The HOST: parameter on http headers */ char *urlProtocol; /* "http" or "https" */ int urlPort; /* TCP port number for http: or https: */ int urlDfltPort; /* The default port for the given protocol */ char *urlPath; /* Pathname for http: */ char *urlUser; /* User id for http: */ char *urlPasswd; /* Password for http: */ char *urlCanonical; /* Canonical representation of the URL */ char *urlProxyAuth; /* Proxy-Authorizer: string */ char *urlFossil; /* The path of the ?fossil=path suffix on ssh: */ int dontKeepUrl; /* Do not persist the URL */ | > | | 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | FILE *httpIn; /* Accept HTTP input from here */ FILE *httpOut; /* Send HTTP output here */ int xlinkClusterOnly; /* Set when cloning. Only process clusters */ int fTimeFormat; /* 1 for UTC. 2 for localtime. 0 not yet selected */ int *aCommitFile; /* Array of files to be committed */ int markPrivate; /* All new artifacts are private if true */ int clockSkewSeen; /* True if clocks on client and server out of sync */ int isCGI; /* True if running in HTTP/CGI mode, else assume CLI. */ int urlIsFile; /* True if a "file:" url */ int urlIsHttps; /* True if a "https:" url */ int urlIsSsh; /* True if an "ssh:" url */ char *urlName; /* Hostname for http: or filename for file: */ char *urlHostname; /* The HOST: parameter on http headers */ char *urlProtocol; /* "http" or "https" */ int urlPort; /* TCP port number for http: or https: */ int urlDfltPort; /* The default port for the given protocol */ char *urlPath; /* Pathname for http: */ char *urlUser; /* User id for http: */ char *urlPasswd; /* Password for http: */ char *urlCanonical; /* Canonical representation of the URL */ char *urlProxyAuth; /* Proxy-Authorizer: string */ char *urlFossil; /* The path of the ?fossil=path suffix on ssh: */ int dontKeepUrl; /* Do not persist the URL */ const char *zLogin; /* Login name. "" if not logged in. */ const char *zSSLIdentity; /* Value of --ssl-identity option, filename of SSL client identity */ int useLocalauth; /* No login required if from 127.0.0.1 */ int noPswd; /* Logged in without password (on 127.0.0.1) */ int userUid; /* Integer user id */ /* Information used to populate the RCVFROM table */ |
︙ | ︙ | |||
163 164 165 166 167 168 169 170 171 172 173 174 175 176 | const char *azAuxName[MX_AUX]; /* Name of each aux() or option() value */ char *azAuxParam[MX_AUX]; /* Param of each aux() or option() value */ const char *azAuxVal[MX_AUX]; /* Value of each aux() or option() value */ const char **azAuxOpt[MX_AUX]; /* Options of each option() value */ int anAuxCols[MX_AUX]; /* Number of columns for option() values */ int allowSymlinks; /* Cached "allow-symlinks" option */ }; /* ** Macro for debugging: */ #define CGIDEBUG(X) if( g.fDebug ) cgi_debug X | > > > > > > > > > > > > > > > > | 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | const char *azAuxName[MX_AUX]; /* Name of each aux() or option() value */ char *azAuxParam[MX_AUX]; /* Param of each aux() or option() value */ const char *azAuxVal[MX_AUX]; /* Value of each aux() or option() value */ const char **azAuxOpt[MX_AUX]; /* Options of each option() value */ int anAuxCols[MX_AUX]; /* Number of columns for option() values */ int allowSymlinks; /* Cached "allow-symlinks" option */ struct FossilJsonBits { int isJsonMode; /* True if running in JSON mode, else false. This changes how errors are reported. In JSON mode we try to always output JSON-form error responses. */ int resultCode; /* used for passing back specific codes from /json callbacks. */ int errorDetailParanoia; /* 0=full error codes, 1=%10, 2=%100, 3=%1000 */ cson_cgi_cx cgiCx; /* cson_cgi context */ cson_output_opt outOpt; /* formatting options for JSON mode. */ cson_value * authToken; /* authentication token */ struct { cson_value * v; cson_object * o; } reqPayload; /* request payload object (if any) */ } json; }; /* ** Macro for debugging: */ #define CGIDEBUG(X) if( g.fDebug ) cgi_debug X |
︙ | ︙ | |||
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | if( cnt==1 ){ *pIndex = m; return 0; } return 1+(cnt>1); } /* ** This procedure runs first. */ int main(int argc, char **argv){ const char *zCmdName = "unknown"; int idx; int rc; int i; sqlite3_config(SQLITE_CONFIG_LOG, fossil_sqlite_log, 0); g.now = time(0); g.argc = argc; g.argv = argv; for(i=0; i<argc; i++) g.argv[i] = fossil_mbcs_to_utf8(argv[i]); if( getenv("GATEWAY_INTERFACE")!=0 && !find_option("nocgi", 0, 0)){ zCmdName = "cgi"; }else if( argc<2 ){ fossil_fatal("Usage: %s COMMAND ...\n" "\"%s help\" for a list of available commands\n" "\"%s help COMMAND\" for specific details\n", argv[0], argv[0], argv[0]); }else{ g.fQuiet = find_option("quiet", 0, 0)!=0; g.fSqlTrace = find_option("sqltrace", 0, 0)!=0; g.fSqlStats = find_option("sqlstats", 0, 0)!=0; g.fSystemTrace = find_option("systemtrace", 0, 0)!=0; if( g.fSqlTrace ) g.fSqlStats = 1; g.fSqlPrint = find_option("sqlprint", 0, 0)!=0; g.fHttpTrace = find_option("httptrace", 0, 0)!=0; | > > > > > > > > > > > > > > > > > > | 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | if( cnt==1 ){ *pIndex = m; return 0; } return 1+(cnt>1); } /* ** atexit() handler which frees up "some" of the resources ** used by fossil. */ void fossil_atexit() { cson_cgi_cx_clean(&g.json.cgiCx); if(g.db){ db_close(0); } } /* ** This procedure runs first. */ int main(int argc, char **argv){ const char *zCmdName = "unknown"; int idx; int rc; int i; sqlite3_config(SQLITE_CONFIG_LOG, fossil_sqlite_log, 0); memset(&g, 0, sizeof(g)); g.now = time(0); g.argc = argc; g.argv = argv; g.json.errorDetailParanoia = 0 /* FIXME: make configurable */; g.json.cgiCx = cson_cgi_cx_empty; g.json.outOpt = cson_output_opt_empty; g.json.outOpt.addNewline = 1; g.json.outOpt.indentation = 1 /* FIXME: make configurable */; for(i=0; i<argc; i++) g.argv[i] = fossil_mbcs_to_utf8(argv[i]); if( getenv("GATEWAY_INTERFACE")!=0 && !find_option("nocgi", 0, 0)){ zCmdName = "cgi"; g.isCGI = 1; }else if( argc<2 ){ fossil_fatal("Usage: %s COMMAND ...\n" "\"%s help\" for a list of available commands\n" "\"%s help COMMAND\" for specific details\n", argv[0], argv[0], argv[0]); }else{ g.isCGI = 0; g.fQuiet = find_option("quiet", 0, 0)!=0; g.fSqlTrace = find_option("sqltrace", 0, 0)!=0; g.fSqlStats = find_option("sqlstats", 0, 0)!=0; g.fSystemTrace = find_option("systemtrace", 0, 0)!=0; if( g.fSqlTrace ) g.fSqlStats = 1; g.fSqlPrint = find_option("sqlprint", 0, 0)!=0; g.fHttpTrace = find_option("httptrace", 0, 0)!=0; |
︙ | ︙ | |||
294 295 296 297 298 299 300 301 302 303 304 305 306 307 | } } fossil_fatal("%s: ambiguous command prefix: %s\n" "%s: could be any of:%s\n" "%s: use \"help\" for more information\n", argv[0], zCmdName, argv[0], blob_str(&couldbe), argv[0]); } aCommand[idx].xFunc(); fossil_exit(0); /*NOT_REACHED*/ return 0; } /* | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | } } fossil_fatal("%s: ambiguous command prefix: %s\n" "%s: could be any of:%s\n" "%s: use \"help\" for more information\n", argv[0], zCmdName, argv[0], blob_str(&couldbe), argv[0]); } rc = cson_cgi_init(&g.json.cgiCx, g.argc, (char const * const *)g.argv, NULL) /* Reminder: cson_cgi_init() may process the POST data before fossil gets to, but it is configured to only read application/[json/javascript] and text/plain. form-urlencoded and x-fossil-* data will be consumed by fossil's cgi_init(). Note that we set up the CGI bits even when not running in CGI mode because some of cson_cgi's facilities are useful in non-CGI contexts and we use those in the CLI variants of the JSON commands. FIXME: do some analysis of the request path (HTTP mode) or CLI args (CLI mode) and only call this if the command is a JSON-mode command. We can only do that easily from here if we use e.g. /json/foo instead of /foo.json, since we have a common prefix. */ ; if(rc){ fossil_fatal("%s: unrecoverable error while initializing JSON CGI bits: " "cson error code #%d (%s)\n", argv[0], rc, cson_rc_string(rc)); }else{ if( NULL != cson_cgi_env_get_obj( &g.json.cgiCx, 'p', 0 ) ){ /* if cson_cgi read the POST data then we're certainly in JSON mode. If it didn't then we have to delay this decision until the JSON family of callbacks is called. */ g.json.isJsonMode = 1; } atexit( fossil_atexit ); } aCommand[idx].xFunc(); fossil_exit(0); /*NOT_REACHED*/ return 0; } /* |
︙ | ︙ | |||
333 334 335 336 337 338 339 340 341 342 343 344 | /* ** Print an error message, rollback all databases, and quit. These ** routines never return. */ void fossil_panic(const char *zFormat, ...){ char *z; va_list ap; static int once = 1; mainInFatalError = 1; va_start(ap, zFormat); z = vmprintf(zFormat, ap); va_end(ap); | > > > > > > | > | > > > > > > > > | | | 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | /* ** Print an error message, rollback all databases, and quit. These ** routines never return. */ void fossil_panic(const char *zFormat, ...){ char *z; va_list ap; int rc = 1; static int once = 1; mainInFatalError = 1; va_start(ap, zFormat); z = vmprintf(zFormat, ap); va_end(ap); if( g.json.isJsonMode ){ json_err( 0, z, 1 ); if( g.isCGI ){ rc = 0 /* avoid HTTP 500 */; } }else if( g.cgiOutput && once ){ once = 0; cgi_printf("<p class=\"generalError\">%h</p>", z); cgi_reply(); }else{ char *zOut = mprintf("%s: %s\n", fossil_nameofexe(), z); fossil_puts(zOut, 1); } free(z); db_force_rollback(); fossil_exit(rc); } void fossil_fatal(const char *zFormat, ...){ char *z; int rc = 1; va_list ap; mainInFatalError = 1; va_start(ap, zFormat); z = vmprintf(zFormat, ap); va_end(ap); if( g.json.isJsonMode ){ json_err( 0, z, 1 ); if( g.isCGI ){ rc = 0 /* avoid HTTP 500 */; } } else if( g.cgiOutput ){ g.cgiOutput = 0; cgi_printf("<p class=\"generalError\">%h</p>", z); cgi_reply(); }else{ char *zOut = mprintf("\r%s: %s\n", fossil_nameofexe(), z); fossil_puts(zOut, 1); } db_force_rollback(); fossil_exit(rc); } /* This routine works like fossil_fatal() except that if called ** recursively, the recursive call is a no-op. ** ** Use this in places where an error might occur while doing ** fatal error shutdown processing. Unlike fossil_panic() and |
︙ | ︙ |
Changes to src/main.mk.
︙ | ︙ | |||
45 46 47 48 49 50 51 52 53 54 55 56 57 58 | $(SRCDIR)/gzip.c \ $(SRCDIR)/http.c \ $(SRCDIR)/http_socket.c \ $(SRCDIR)/http_ssl.c \ $(SRCDIR)/http_transport.c \ $(SRCDIR)/import.c \ $(SRCDIR)/info.c \ $(SRCDIR)/leaf.c \ $(SRCDIR)/login.c \ $(SRCDIR)/main.c \ $(SRCDIR)/manifest.c \ $(SRCDIR)/md5.c \ $(SRCDIR)/merge.c \ $(SRCDIR)/merge3.c \ | > | 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | $(SRCDIR)/gzip.c \ $(SRCDIR)/http.c \ $(SRCDIR)/http_socket.c \ $(SRCDIR)/http_ssl.c \ $(SRCDIR)/http_transport.c \ $(SRCDIR)/import.c \ $(SRCDIR)/info.c \ $(SRCDIR)/json.c \ $(SRCDIR)/leaf.c \ $(SRCDIR)/login.c \ $(SRCDIR)/main.c \ $(SRCDIR)/manifest.c \ $(SRCDIR)/md5.c \ $(SRCDIR)/merge.c \ $(SRCDIR)/merge3.c \ |
︙ | ︙ | |||
129 130 131 132 133 134 135 136 137 138 139 140 141 142 | $(OBJDIR)/gzip_.c \ $(OBJDIR)/http_.c \ $(OBJDIR)/http_socket_.c \ $(OBJDIR)/http_ssl_.c \ $(OBJDIR)/http_transport_.c \ $(OBJDIR)/import_.c \ $(OBJDIR)/info_.c \ $(OBJDIR)/leaf_.c \ $(OBJDIR)/login_.c \ $(OBJDIR)/main_.c \ $(OBJDIR)/manifest_.c \ $(OBJDIR)/md5_.c \ $(OBJDIR)/merge_.c \ $(OBJDIR)/merge3_.c \ | > | 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | $(OBJDIR)/gzip_.c \ $(OBJDIR)/http_.c \ $(OBJDIR)/http_socket_.c \ $(OBJDIR)/http_ssl_.c \ $(OBJDIR)/http_transport_.c \ $(OBJDIR)/import_.c \ $(OBJDIR)/info_.c \ $(OBJDIR)/json_.c \ $(OBJDIR)/leaf_.c \ $(OBJDIR)/login_.c \ $(OBJDIR)/main_.c \ $(OBJDIR)/manifest_.c \ $(OBJDIR)/md5_.c \ $(OBJDIR)/merge_.c \ $(OBJDIR)/merge3_.c \ |
︙ | ︙ | |||
213 214 215 216 217 218 219 220 221 222 223 224 225 226 | $(OBJDIR)/gzip.o \ $(OBJDIR)/http.o \ $(OBJDIR)/http_socket.o \ $(OBJDIR)/http_ssl.o \ $(OBJDIR)/http_transport.o \ $(OBJDIR)/import.o \ $(OBJDIR)/info.o \ $(OBJDIR)/leaf.o \ $(OBJDIR)/login.o \ $(OBJDIR)/main.o \ $(OBJDIR)/manifest.o \ $(OBJDIR)/md5.o \ $(OBJDIR)/merge.o \ $(OBJDIR)/merge3.o \ | > | 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | $(OBJDIR)/gzip.o \ $(OBJDIR)/http.o \ $(OBJDIR)/http_socket.o \ $(OBJDIR)/http_ssl.o \ $(OBJDIR)/http_transport.o \ $(OBJDIR)/import.o \ $(OBJDIR)/info.o \ $(OBJDIR)/json.o \ $(OBJDIR)/leaf.o \ $(OBJDIR)/login.o \ $(OBJDIR)/main.o \ $(OBJDIR)/manifest.o \ $(OBJDIR)/md5.o \ $(OBJDIR)/merge.o \ $(OBJDIR)/merge3.o \ |
︙ | ︙ | |||
299 300 301 302 303 304 305 | # to 1. If it is set to 1, then there is no need to build or link # the sqlite3.o object. Instead, the system sqlite will be linked # using -lsqlite3. SQLITE3_OBJ.1 = SQLITE3_OBJ.0 = $(OBJDIR)/sqlite3.o SQLITE3_OBJ. = $(SQLITE3_OBJ.0) | | | | 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | # to 1. If it is set to 1, then there is no need to build or link # the sqlite3.o object. Instead, the system sqlite will be linked # using -lsqlite3. SQLITE3_OBJ.1 = SQLITE3_OBJ.0 = $(OBJDIR)/sqlite3.o SQLITE3_OBJ. = $(SQLITE3_OBJ.0) EXTRAOBJ = $(SQLITE3_OBJ.$(USE_SYSTEM_SQLITE)) $(OBJDIR)/shell.o $(OBJDIR)/th.o $(OBJDIR)/th_lang.o $(OBJDIR)/cson_amalgamation.o $(APPNAME): $(OBJDIR)/headers $(OBJ) $(EXTRAOBJ) $(TCC) -o $(APPNAME) $(OBJ) $(EXTRAOBJ) $(LIB) # This rule prevents make from using its default rules to try build # an executable named "manifest" out of the file named "manifest.c" # $(SRCDIR)/../manifest: # noop clean: rm -rf $(OBJDIR)/* $(APPNAME) $(OBJDIR)/page_index.h: $(TRANS_SRC) $(OBJDIR)/mkindex $(OBJDIR)/mkindex $(TRANS_SRC) >$@ $(OBJDIR)/headers: $(OBJDIR)/page_index.h $(OBJDIR)/makeheaders $(OBJDIR)/VERSION.h $(OBJDIR)/makeheaders $(OBJDIR)/add_.c:$(OBJDIR)/add.h $(OBJDIR)/allrepo_.c:$(OBJDIR)/allrepo.h $(OBJDIR)/attach_.c:$(OBJDIR)/attach.h $(OBJDIR)/bag_.c:$(OBJDIR)/bag.h $(OBJDIR)/bisect_.c:$(OBJDIR)/bisect.h $(OBJDIR)/blob_.c:$(OBJDIR)/blob.h $(OBJDIR)/branch_.c:$(OBJDIR)/branch.h $(OBJDIR)/browse_.c:$(OBJDIR)/browse.h $(OBJDIR)/captcha_.c:$(OBJDIR)/captcha.h $(OBJDIR)/cgi_.c:$(OBJDIR)/cgi.h $(OBJDIR)/checkin_.c:$(OBJDIR)/checkin.h $(OBJDIR)/checkout_.c:$(OBJDIR)/checkout.h $(OBJDIR)/clearsign_.c:$(OBJDIR)/clearsign.h $(OBJDIR)/clone_.c:$(OBJDIR)/clone.h $(OBJDIR)/comformat_.c:$(OBJDIR)/comformat.h $(OBJDIR)/configure_.c:$(OBJDIR)/configure.h $(OBJDIR)/content_.c:$(OBJDIR)/content.h $(OBJDIR)/db_.c:$(OBJDIR)/db.h $(OBJDIR)/delta_.c:$(OBJDIR)/delta.h $(OBJDIR)/deltacmd_.c:$(OBJDIR)/deltacmd.h $(OBJDIR)/descendants_.c:$(OBJDIR)/descendants.h $(OBJDIR)/diff_.c:$(OBJDIR)/diff.h $(OBJDIR)/diffcmd_.c:$(OBJDIR)/diffcmd.h $(OBJDIR)/doc_.c:$(OBJDIR)/doc.h $(OBJDIR)/encode_.c:$(OBJDIR)/encode.h $(OBJDIR)/event_.c:$(OBJDIR)/event.h $(OBJDIR)/export_.c:$(OBJDIR)/export.h $(OBJDIR)/file_.c:$(OBJDIR)/file.h $(OBJDIR)/finfo_.c:$(OBJDIR)/finfo.h $(OBJDIR)/glob_.c:$(OBJDIR)/glob.h $(OBJDIR)/graph_.c:$(OBJDIR)/graph.h $(OBJDIR)/gzip_.c:$(OBJDIR)/gzip.h $(OBJDIR)/http_.c:$(OBJDIR)/http.h $(OBJDIR)/http_socket_.c:$(OBJDIR)/http_socket.h $(OBJDIR)/http_ssl_.c:$(OBJDIR)/http_ssl.h $(OBJDIR)/http_transport_.c:$(OBJDIR)/http_transport.h $(OBJDIR)/import_.c:$(OBJDIR)/import.h $(OBJDIR)/info_.c:$(OBJDIR)/info.h $(OBJDIR)/json_.c:$(OBJDIR)/json.h $(OBJDIR)/leaf_.c:$(OBJDIR)/leaf.h $(OBJDIR)/login_.c:$(OBJDIR)/login.h $(OBJDIR)/main_.c:$(OBJDIR)/main.h $(OBJDIR)/manifest_.c:$(OBJDIR)/manifest.h $(OBJDIR)/md5_.c:$(OBJDIR)/md5.h $(OBJDIR)/merge_.c:$(OBJDIR)/merge.h $(OBJDIR)/merge3_.c:$(OBJDIR)/merge3.h $(OBJDIR)/name_.c:$(OBJDIR)/name.h $(OBJDIR)/path_.c:$(OBJDIR)/path.h $(OBJDIR)/pivot_.c:$(OBJDIR)/pivot.h $(OBJDIR)/popen_.c:$(OBJDIR)/popen.h $(OBJDIR)/pqueue_.c:$(OBJDIR)/pqueue.h $(OBJDIR)/printf_.c:$(OBJDIR)/printf.h $(OBJDIR)/rebuild_.c:$(OBJDIR)/rebuild.h $(OBJDIR)/report_.c:$(OBJDIR)/report.h $(OBJDIR)/rss_.c:$(OBJDIR)/rss.h $(OBJDIR)/schema_.c:$(OBJDIR)/schema.h $(OBJDIR)/search_.c:$(OBJDIR)/search.h $(OBJDIR)/setup_.c:$(OBJDIR)/setup.h $(OBJDIR)/sha1_.c:$(OBJDIR)/sha1.h $(OBJDIR)/shun_.c:$(OBJDIR)/shun.h $(OBJDIR)/skins_.c:$(OBJDIR)/skins.h $(OBJDIR)/sqlcmd_.c:$(OBJDIR)/sqlcmd.h $(OBJDIR)/stash_.c:$(OBJDIR)/stash.h $(OBJDIR)/stat_.c:$(OBJDIR)/stat.h $(OBJDIR)/style_.c:$(OBJDIR)/style.h $(OBJDIR)/sync_.c:$(OBJDIR)/sync.h $(OBJDIR)/tag_.c:$(OBJDIR)/tag.h $(OBJDIR)/tar_.c:$(OBJDIR)/tar.h $(OBJDIR)/th_main_.c:$(OBJDIR)/th_main.h $(OBJDIR)/timeline_.c:$(OBJDIR)/timeline.h $(OBJDIR)/tkt_.c:$(OBJDIR)/tkt.h $(OBJDIR)/tktsetup_.c:$(OBJDIR)/tktsetup.h $(OBJDIR)/undo_.c:$(OBJDIR)/undo.h $(OBJDIR)/update_.c:$(OBJDIR)/update.h $(OBJDIR)/url_.c:$(OBJDIR)/url.h $(OBJDIR)/user_.c:$(OBJDIR)/user.h $(OBJDIR)/verify_.c:$(OBJDIR)/verify.h $(OBJDIR)/vfile_.c:$(OBJDIR)/vfile.h $(OBJDIR)/wiki_.c:$(OBJDIR)/wiki.h $(OBJDIR)/wikiformat_.c:$(OBJDIR)/wikiformat.h $(OBJDIR)/winhttp_.c:$(OBJDIR)/winhttp.h $(OBJDIR)/xfer_.c:$(OBJDIR)/xfer.h $(OBJDIR)/zip_.c:$(OBJDIR)/zip.h $(SRCDIR)/sqlite3.h $(SRCDIR)/th.h $(OBJDIR)/VERSION.h touch $(OBJDIR)/headers $(OBJDIR)/headers: Makefile Makefile: $(OBJDIR)/add_.c: $(SRCDIR)/add.c $(OBJDIR)/translate $(OBJDIR)/translate $(SRCDIR)/add.c >$(OBJDIR)/add_.c $(OBJDIR)/add.o: $(OBJDIR)/add_.c $(OBJDIR)/add.h $(SRCDIR)/config.h |
︙ | ︙ | |||
587 588 589 590 591 592 593 594 595 596 597 598 599 600 | $(OBJDIR)/info_.c: $(SRCDIR)/info.c $(OBJDIR)/translate $(OBJDIR)/translate $(SRCDIR)/info.c >$(OBJDIR)/info_.c $(OBJDIR)/info.o: $(OBJDIR)/info_.c $(OBJDIR)/info.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/info.o -c $(OBJDIR)/info_.c $(OBJDIR)/info.h: $(OBJDIR)/headers $(OBJDIR)/leaf_.c: $(SRCDIR)/leaf.c $(OBJDIR)/translate $(OBJDIR)/translate $(SRCDIR)/leaf.c >$(OBJDIR)/leaf_.c $(OBJDIR)/leaf.o: $(OBJDIR)/leaf_.c $(OBJDIR)/leaf.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/leaf.o -c $(OBJDIR)/leaf_.c $(OBJDIR)/leaf.h: $(OBJDIR)/headers | > > > > > > > | 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 | $(OBJDIR)/info_.c: $(SRCDIR)/info.c $(OBJDIR)/translate $(OBJDIR)/translate $(SRCDIR)/info.c >$(OBJDIR)/info_.c $(OBJDIR)/info.o: $(OBJDIR)/info_.c $(OBJDIR)/info.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/info.o -c $(OBJDIR)/info_.c $(OBJDIR)/info.h: $(OBJDIR)/headers $(OBJDIR)/json_.c: $(SRCDIR)/json.c $(OBJDIR)/translate $(OBJDIR)/translate $(SRCDIR)/json.c >$(OBJDIR)/json_.c $(OBJDIR)/json.o: $(OBJDIR)/json_.c $(OBJDIR)/json.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/json.o -c $(OBJDIR)/json_.c $(OBJDIR)/json.h: $(OBJDIR)/headers $(OBJDIR)/leaf_.c: $(SRCDIR)/leaf.c $(OBJDIR)/translate $(OBJDIR)/translate $(SRCDIR)/leaf.c >$(OBJDIR)/leaf_.c $(OBJDIR)/leaf.o: $(OBJDIR)/leaf_.c $(OBJDIR)/leaf.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/leaf.o -c $(OBJDIR)/leaf_.c $(OBJDIR)/leaf.h: $(OBJDIR)/headers |
︙ | ︙ | |||
907 908 909 910 911 912 913 | $(OBJDIR)/th.o: $(SRCDIR)/th.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th.c -o $(OBJDIR)/th.o $(OBJDIR)/th_lang.o: $(SRCDIR)/th_lang.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th_lang.c -o $(OBJDIR)/th_lang.o | > > > | 917 918 919 920 921 922 923 924 925 926 | $(OBJDIR)/th.o: $(SRCDIR)/th.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th.c -o $(OBJDIR)/th.o $(OBJDIR)/th_lang.o: $(SRCDIR)/th_lang.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th_lang.c -o $(OBJDIR)/th_lang.o $(OBJDIR)/cson_amalgamation.o: $(SRCDIR)/cson_amalgamation.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/cson_amalgamation.c -o $(OBJDIR)/cson_amalgamation.o |
Changes to src/makemake.tcl.
︙ | ︙ | |||
51 52 53 54 55 56 57 58 59 60 61 62 63 64 | graph gzip http http_socket http_transport import info leaf login main manifest md5 merge merge3 | > | 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | graph gzip http http_socket http_transport import info json leaf login main manifest md5 merge merge3 |
︙ | ︙ | |||
200 201 202 203 204 205 206 | SQLITE3_OBJ.0 = $(OBJDIR)/sqlite3.o SQLITE3_OBJ. = $(SQLITE3_OBJ.0) EXTRAOBJ = \ $(SQLITE3_OBJ.$(USE_SYSTEM_SQLITE)) \ $(OBJDIR)/shell.o \ $(OBJDIR)/th.o \ | | > | 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | SQLITE3_OBJ.0 = $(OBJDIR)/sqlite3.o SQLITE3_OBJ. = $(SQLITE3_OBJ.0) EXTRAOBJ = \ $(SQLITE3_OBJ.$(USE_SYSTEM_SQLITE)) \ $(OBJDIR)/shell.o \ $(OBJDIR)/th.o \ $(OBJDIR)/th_lang.o \ $(OBJDIR)/cson_amalgamation.o $(APPNAME): $(OBJDIR)/headers $(OBJ) $(EXTRAOBJ) $(TCC) -o $(APPNAME) $(OBJ) $(EXTRAOBJ) $(LIB) # This rule prevents make from using its default rules to try build # an executable named "manifest" out of the file named "manifest.c" # |
︙ | ︙ | |||
223 224 225 226 227 228 229 230 231 232 233 234 235 236 | set mhargs {} foreach s [lsort $src] { append mhargs " \$(OBJDIR)/${s}_.c:\$(OBJDIR)/$s.h" set extra_h($s) {} } append mhargs " \$(SRCDIR)/sqlite3.h" append mhargs " \$(SRCDIR)/th.h" append mhargs " \$(OBJDIR)/VERSION.h" writeln "\$(OBJDIR)/page_index.h: \$(TRANS_SRC) \$(OBJDIR)/mkindex" writeln "\t\$(OBJDIR)/mkindex \$(TRANS_SRC) >$@" writeln "\$(OBJDIR)/headers:\t\$(OBJDIR)/page_index.h \$(OBJDIR)/makeheaders \$(OBJDIR)/VERSION.h" writeln "\t\$(OBJDIR)/makeheaders $mhargs" writeln "\ttouch \$(OBJDIR)/headers" writeln "\$(OBJDIR)/headers: Makefile" | > | 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | set mhargs {} foreach s [lsort $src] { append mhargs " \$(OBJDIR)/${s}_.c:\$(OBJDIR)/$s.h" set extra_h($s) {} } append mhargs " \$(SRCDIR)/sqlite3.h" append mhargs " \$(SRCDIR)/th.h" #append mhargs " \$(SRCDIR)/cson_amalgamation.h" append mhargs " \$(OBJDIR)/VERSION.h" writeln "\$(OBJDIR)/page_index.h: \$(TRANS_SRC) \$(OBJDIR)/mkindex" writeln "\t\$(OBJDIR)/mkindex \$(TRANS_SRC) >$@" writeln "\$(OBJDIR)/headers:\t\$(OBJDIR)/page_index.h \$(OBJDIR)/makeheaders \$(OBJDIR)/VERSION.h" writeln "\t\$(OBJDIR)/makeheaders $mhargs" writeln "\ttouch \$(OBJDIR)/headers" writeln "\$(OBJDIR)/headers: Makefile" |
︙ | ︙ | |||
262 263 264 265 266 267 268 269 270 271 272 273 274 275 | writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/shell.c -o \$(OBJDIR)/shell.o\n" writeln "\$(OBJDIR)/th.o:\t\$(SRCDIR)/th.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/th.c -o \$(OBJDIR)/th.o\n" writeln "\$(OBJDIR)/th_lang.o:\t\$(SRCDIR)/th_lang.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/th_lang.c -o \$(OBJDIR)/th_lang.o\n" close $output_file # # End of the main.mk output ############################################################################## ############################################################################## ############################################################################## | > > > > > | 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/shell.c -o \$(OBJDIR)/shell.o\n" writeln "\$(OBJDIR)/th.o:\t\$(SRCDIR)/th.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/th.c -o \$(OBJDIR)/th.o\n" writeln "\$(OBJDIR)/th_lang.o:\t\$(SRCDIR)/th_lang.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/th_lang.c -o \$(OBJDIR)/th_lang.o\n" set opt {} writeln "\$(OBJDIR)/cson_amalgamation.o:\t\$(SRCDIR)/cson_amalgamation.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/cson_amalgamation.c -o \$(OBJDIR)/cson_amalgamation.o\n" close $output_file # # End of the main.mk output ############################################################################## ############################################################################## ############################################################################## |
︙ | ︙ | |||
410 411 412 413 414 415 416 | $(OBJDIR)/VERSION.h: $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(VERSION) $(VERSION) $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(SRCDIR)/../VERSION >$(OBJDIR)/VERSION.h EXTRAOBJ = \ $(OBJDIR)/sqlite3.o \ $(OBJDIR)/shell.o \ $(OBJDIR)/th.o \ | | > | 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | $(OBJDIR)/VERSION.h: $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(VERSION) $(VERSION) $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(SRCDIR)/../VERSION >$(OBJDIR)/VERSION.h EXTRAOBJ = \ $(OBJDIR)/sqlite3.o \ $(OBJDIR)/shell.o \ $(OBJDIR)/th.o \ $(OBJDIR)/th_lang.o \ $(OBJDIR)/cson_amalgamation.o $(APPNAME): $(OBJDIR)/headers $(OBJ) $(EXTRAOBJ) $(OBJDIR)/icon.o $(TCC) -o $(APPNAME) $(OBJ) $(EXTRAOBJ) $(LIB) $(OBJDIR)/icon.o # This rule prevents make from using its default rules to try build # an executable named "manifest" out of the file named "manifest.c" # |
︙ | ︙ | |||
464 465 466 467 468 469 470 471 472 473 474 475 476 477 | } writeln "\$(OBJDIR)/sqlite3.o:\t\$(SRCDIR)/sqlite3.c" set opt $SQLITE_OPTIONS writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/sqlite3.c -o \$(OBJDIR)/sqlite3.o\n" writeln "\$(OBJDIR)/shell.o:\t\$(SRCDIR)/shell.c \$(SRCDIR)/sqlite3.h" set opt {-Dmain=sqlite3_shell} append opt " -DSQLITE_OMIT_LOAD_EXTENSION=1" writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/shell.c -o \$(OBJDIR)/shell.o\n" writeln "\$(OBJDIR)/th.o:\t\$(SRCDIR)/th.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/th.c -o \$(OBJDIR)/th.o\n" | > > > > | 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | } writeln "\$(OBJDIR)/sqlite3.o:\t\$(SRCDIR)/sqlite3.c" set opt $SQLITE_OPTIONS writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/sqlite3.c -o \$(OBJDIR)/sqlite3.o\n" set opt {} writeln "\$(OBJDIR)/cson_amalgamation.o:\t\$(SRCDIR)/cson_amalgamation.c" writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/cson_amalgamation.c -o \$(OBJDIR)/cson_amalgamation.o\n" writeln "\$(OBJDIR)/shell.o:\t\$(SRCDIR)/shell.c \$(SRCDIR)/sqlite3.h" set opt {-Dmain=sqlite3_shell} append opt " -DSQLITE_OMIT_LOAD_EXTENSION=1" writeln "\t\$(XTCC) $opt -c \$(SRCDIR)/shell.c -o \$(OBJDIR)/shell.o\n" writeln "\$(OBJDIR)/th.o:\t\$(SRCDIR)/th.c" writeln "\t\$(XTCC) -I\$(SRCDIR) -c \$(SRCDIR)/th.c -o \$(OBJDIR)/th.o\n" |
︙ | ︙ | |||
575 576 577 578 579 580 581 582 583 584 585 586 587 588 | $(TCC) -o$@ -c $(SQLITE_OPTIONS) $** $(OBJDIR)\th$O : $(SRCDIR)\th.c $(TCC) -o$@ -c $** $(OBJDIR)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) -o$@ -c $** VERSION.h : version$E $B\manifest.uuid $B\manifest $B\VERSION +$** > $@ page_index.h: mkindex$E $(SRC) +$** > $@ | > > > | 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | $(TCC) -o$@ -c $(SQLITE_OPTIONS) $** $(OBJDIR)\th$O : $(SRCDIR)\th.c $(TCC) -o$@ -c $** $(OBJDIR)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) -o$@ -c $** $(OBJDIR)\cson_amalgamation.h : $(SRCDIR)\cson_amalgamation.h cp $@ $@ VERSION.h : version$E $B\manifest.uuid $B\manifest $B\VERSION +$** > $@ page_index.h: mkindex$E $(SRC) +$** > $@ |
︙ | ︙ | |||
601 602 603 604 605 606 607 | writeln "\t+translate\$E \$** > \$@\n" } writeln -nonewline "headers: makeheaders\$E page_index.h VERSION.h\n\t +makeheaders\$E " foreach s [lsort $src] { writeln -nonewline "${s}_.c:$s.h " } | | | 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 | writeln "\t+translate\$E \$** > \$@\n" } writeln -nonewline "headers: makeheaders\$E page_index.h VERSION.h\n\t +makeheaders\$E " foreach s [lsort $src] { writeln -nonewline "${s}_.c:$s.h " } writeln "\$(SRCDIR)\\sqlite3.h \$(SRCDIR)\\th.h VERSION.h \$(SRCDIR)\\cson_amalgamation.h" writeln "\t@copy /Y nul: headers" close $output_file # # End of the win/Makefile.dmc output ############################################################################## ############################################################################## |
︙ | ︙ | |||
715 716 717 718 719 720 721 722 723 724 725 726 727 728 | $(TCC) /Fo$@ -c $** $(OX)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) /Fo$@ -c $** VERSION.h : mkversion$E $B\manifest.uuid $B\manifest $B\VERSION $** > $@ page_index.h: mkindex$E $(SRC) $** > $@ clean: -del $(OX)\*.obj -del *.obj *_.c *.h *.map | > > | 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 | $(TCC) /Fo$@ -c $** $(OX)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) /Fo$@ -c $** VERSION.h : mkversion$E $B\manifest.uuid $B\manifest $B\VERSION $** > $@ $(OBJDIR)\cson_amalgamation.h : $(SRCDIR)\cson_amalgamation.h cp $(SRCDIR)\cson_amalgamation.h $@ page_index.h: mkindex$E $(SRC) $** > $@ clean: -del $(OX)\*.obj -del *.obj *_.c *.h *.map |
︙ | ︙ | |||
739 740 741 742 743 744 745 | writeln "\ttranslate\$E \$** > \$@\n" } writeln -nonewline "headers: makeheaders\$E page_index.h VERSION.h\n\tmakeheaders\$E " foreach s [lsort $src] { writeln -nonewline "${s}_.c:$s.h " } | | | 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | writeln "\ttranslate\$E \$** > \$@\n" } writeln -nonewline "headers: makeheaders\$E page_index.h VERSION.h\n\tmakeheaders\$E " foreach s [lsort $src] { writeln -nonewline "${s}_.c:$s.h " } writeln "\$(SRCDIR)\\sqlite3.h \$(SRCDIR)\\th.h VERSION.h \$(SRCDIR)\\cson_amalgamation.h" writeln "\t@copy /Y nul: headers" close $output_file # # End of the win/Makefile.msc output ############################################################################## |
︙ | ︙ |
Changes to src/report.c.
︙ | ︙ | |||
17 18 19 20 21 22 23 24 25 26 27 28 29 30 | ** ** Code to generate the ticket listings */ #include "config.h" #include <time.h> #include "report.h" #include <assert.h> /* Forward references to static routines */ static void report_format_hints(void); /* ** WEBPAGE: /reportlist */ | > | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ** ** Code to generate the ticket listings */ #include "config.h" #include <time.h> #include "report.h" #include <assert.h> #include "cson_amalgamation.h" /* Forward references to static routines */ static void report_format_hints(void); /* ** WEBPAGE: /reportlist */ |
︙ | ︙ | |||
1152 1153 1154 1155 1156 1157 1158 | report_restrict_sql(&zErr1); sqlite3_exec_readonly(g.db, zSql, output_separated_file, &count, &zErr2); report_unrestrict_sql(); if( zFilter ){ free(zSql); } } | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | report_restrict_sql(&zErr1); sqlite3_exec_readonly(g.db, zSql, output_separated_file, &count, &zErr2); report_unrestrict_sql(); if( zFilter ){ free(zSql); } } void rptshowJson( const char *zRep, char const * zLimit, const char *zFilter, char indention ){ Stmt q; char *zSql; char const *zTitle; char const *zOwner; char *zClrKey; char *zErr1 = 0; int count = 0; int rn; int rc; cson_value * zJVal = NULL; if (!zRep || !strcmp(zRep,zFullTicketRptRn) || !strcmp(zRep,zFullTicketRptTitle) ){ zTitle = zFullTicketRptTitle; zSql = mprintf("SELECT * FROM ticket"); zOwner = g.zLogin; zClrKey = ""; }else{ rn = atoi(zRep); if( rn ){ db_prepare(&q, "SELECT title, sqlcode, owner, cols FROM reportfmt WHERE rn=%d", rn); }else{ db_prepare(&q, "SELECT title, sqlcode, owner, cols FROM reportfmt WHERE title=%Q", zRep); } if( db_step(&q)!=SQLITE_ROW ){ db_finalize(&q); rpt_list_reports(); fossil_fatal("unkown report format(%s)!",zRep); } zTitle = db_column_malloc(&q, 0)/*leak!*/; zSql = db_column_malloc(&q, 1); zOwner = db_column_malloc(&q, 2)/*leak!*/; zClrKey = db_column_malloc(&q, 3); db_finalize(&q); } if( zFilter ){ char * old = zSql; zSql = mprintf("SELECT * FROM (%s) WHERE %s%s%s",old,zFilter, (zLimit?" LIMIT ":""), (zLimit?zLimit:"")); free(old); }else if( zLimit ){ char * old = zSql; zSql = mprintf("%s LIMIT %s",old, zLimit); free(old); } count = 0; /*fprintf(stderr,"SQL=[%s]\n",zSql);*/ sqlite3_set_authorizer(g.db, report_query_authorizer, (void*)&zErr1); rc = cson_sqlite3_sql_to_json(g.db, &zJVal, zSql, 1); if( 0 == rc ){ cson_output_opt outOpt = cson_output_opt_empty; outOpt.addNewline = 1; outOpt.indentation = indention; rc = cson_output_FILE( zJVal, stdout, &outOpt ); } else{ fossil_fatal("sql-to-json failed with code %d (%s)!", rc, cson_rc_string(rc)); } sqlite3_set_authorizer(g.db, 0, 0); cson_value_free(zJVal); free(zSql); free(zClrKey); } |
Changes to src/timeline.c.
︙ | ︙ | |||
18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ** This file contains code to implement the timeline web page ** */ #include <string.h> #include <time.h> #include "config.h" #include "timeline.h" /* ** Shorten a UUID so that is the minimum length needed to contain ** at least one digit in the range 'a'..'f'. The minimum length is 10. */ static void shorten_uuid(char *zDest, const char *zSrc){ int i; | > | 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | ** This file contains code to implement the timeline web page ** */ #include <string.h> #include <time.h> #include "config.h" #include "timeline.h" #include "cson_amalgamation.h" /* ** Shorten a UUID so that is the minimum length needed to contain ** at least one digit in the range 'a'..'f'. The minimum length is 10. */ static void shorten_uuid(char *zDest, const char *zSrc){ int i; |
︙ | ︙ | |||
1363 1364 1365 1366 1367 1368 1369 | /* ** Return a pointer to a static string that forms the basis for ** a timeline query for display on a TTY. */ const char *timeline_query_for_tty(void){ static const char zBaseSql[] = @ SELECT | | | | | | | | 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 | /* ** Return a pointer to a static string that forms the basis for ** a timeline query for display on a TTY. */ const char *timeline_query_for_tty(void){ static const char zBaseSql[] = @ SELECT @ blob.rid AS rid, @ uuid, @ datetime(event.mtime,'localtime') AS mDateTime, @ coalesce(ecomment,comment) @ || ' (user: ' || coalesce(euser,user,'?') @ || (SELECT case when length(x)>0 then ' tags: ' || x else '' end @ FROM (SELECT group_concat(substr(tagname,5), ', ') AS x @ FROM tag, tagxref @ WHERE tagname GLOB 'sym-*' AND tag.tagid=tagxref.tagid @ AND tagxref.rid=blob.rid AND tagxref.tagtype>0)) @ || ')' as comment, @ (SELECT count(*) FROM plink WHERE pid=blob.rid AND isprim) AS primPlinkCount, @ (SELECT count(*) FROM plink WHERE cid=blob.rid) AS plinkCount, @ event.mtime AS mtime @ FROM event, blob @ WHERE blob.rid=event.objid ; return zBaseSql; } /* |
︙ | ︙ | |||
1423 1424 1425 1426 1427 1428 1429 | ** The optional TYPE argument may any types supported by the /timeline ** page. For example: ** ** w = wiki commits only ** ci = file commits only ** t = tickets only ** | | | > > | 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 | ** The optional TYPE argument may any types supported by the /timeline ** page. For example: ** ** w = wiki commits only ** ci = file commits only ** t = tickets only ** ** The optional showfiles argument, if specified, prints the list of ** files changed in a checkin after the checkin comment. ** */ void timeline_cmd(void){ Stmt q; int n, k; const char *zCount; const char *zType; char *zOrigin; char *zDate; Blob sql; int objid = 0; Blob uuid; int mode = 0 ; /* 0:none 1: before 2:after 3:children 4:parents */ int showfilesFlag = 0 ; db_find_and_open_repository(0, 0); showfilesFlag = find_option("showfiles","f", 0)!=0; db_find_and_open_repository(0, 0); zCount = find_option("count","n",1); zType = find_option("type","t",1); if( zCount ){ n = atoi(zCount); }else{ |
︙ | ︙ | |||
1522 1523 1524 1525 1526 1527 1528 | compute_ancestors(objid, n); } blob_appendf(&sql, " AND blob.rid IN ok"); } if( zType && (zType[0]!='a') ){ blob_appendf(&sql, " AND event.type=%Q ", zType); } | < | 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 | compute_ancestors(objid, n); } blob_appendf(&sql, " AND blob.rid IN ok"); } if( zType && (zType[0]!='a') ){ blob_appendf(&sql, " AND event.type=%Q ", zType); } blob_appendf(&sql, " ORDER BY event.mtime DESC"); db_prepare(&q, blob_str(&sql)); blob_reset(&sql); print_timeline(&q, n, showfilesFlag); db_finalize(&q); } |
︙ | ︙ |
Changes to src/tkt.c.
︙ | ︙ | |||
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | ** ?-q|--quote? ** ?-R|--repository FILE? ** ** Run the ticket report, identified by the report format title ** used in the gui. The data is written as flat file on stdout, ** using "," as separator. The separator "," can be changed using ** the -l or --limit option. ** If TICKETFILTER is given on the commandline, the query is ** limited with a new WHERE-condition. ** example: Report lists a column # with the uuid ** TICKETFILTER may be [#]='uuuuuuuuu' ** example: Report only lists rows with status not open ** TICKETFILTER: status != 'open' ** If the option -q|--quote is used, the tickets are encoded by ** quoting special chars(space -> \\s, tab -> \\t, newline -> \\n, ** cr -> \\r, formfeed -> \\f, vtab -> \\v, nul -> \\0, \\ -> \\\\). ** Otherwise, the simplified encoding as on the show report raw | > | | 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | ** ?-q|--quote? ** ?-R|--repository FILE? ** ** Run the ticket report, identified by the report format title ** used in the gui. The data is written as flat file on stdout, ** using "," as separator. The separator "," can be changed using ** the -l or --limit option. ** ** If TICKETFILTER is given on the commandline, the query is ** limited with a new WHERE-condition. ** example: Report lists a column # with the uuid ** TICKETFILTER may be [#]='uuuuuuuuu' ** example: Report only lists rows with status not open ** TICKETFILTER: status != 'open' ** If the option -q|--quote is used, the tickets are encoded by ** quoting special chars(space -> \\s, tab -> \\t, newline -> \\n, ** cr -> \\r, formfeed -> \\f, vtab -> \\v, nul -> \\0, \\ -> \\\\). ** Otherwise, the simplified encoding as on the show report raw ** page in the gui is used. This has no effect in JSON mode. ** ** Instead of the report title its possible to use the report ** number. Using the special report number 0 list all columns, ** defined in the ticket table. ** ** %fossil ticket list fields ** |
︙ | ︙ | |||
957 958 959 960 961 962 963 | if( strncmp(g.argv[2],"show",n)==0 ){ if( g.argc==3 ){ usage("show REPORTNR"); }else{ const char *zRep = 0; const char *zSep = 0; const char *zFilterUuid = 0; | < < < | 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 | if( strncmp(g.argv[2],"show",n)==0 ){ if( g.argc==3 ){ usage("show REPORTNR"); }else{ const char *zRep = 0; const char *zSep = 0; const char *zFilterUuid = 0; zSep = find_option("limit","l",1); zRep = g.argv[3]; if( !strcmp(zRep,"0") ){ zRep = 0; } if( g.argc>4 ){ zFilterUuid = g.argv[4]; } rptshow( zRep, zSep, zFilterUuid, tktEncoding ); } }else{ /* add a new ticket or update an existing ticket */ enum { set,add,history,err } eCmd = err; int i = 0; int rid; const char *zTktUuid = 0; |
︙ | ︙ |
Changes to src/wiki.c.
︙ | ︙ | |||
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | @ %h(blob_str(&d)) @ </pre> manifest_destroy(pW1); manifest_destroy(pW2); style_footer(); } /* ** WEBPAGE: wcontent ** ** all=1 Show deleted pages ** ** List all available wiki pages with date created and last modified. */ void wcontent_page(void){ Stmt q; int showAll = P("all")!=0; login_check_credentials(); if( !g.perm.RdWiki ){ login_needed(); return; } style_header("Available Wiki Pages"); if( showAll ){ style_submenu_element("Active", "Only Active Pages", "%s/wcontent", g.zTop); }else{ style_submenu_element("All", "All", "%s/wcontent?all=1", g.zTop); } @ <ul> | > > > > > > > > > > > > > > > > > | < < < < < < | 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | @ %h(blob_str(&d)) @ </pre> manifest_destroy(pW1); manifest_destroy(pW2); style_footer(); } /* ** prepare()s pStmt with a query requesting: ** ** - wiki page name ** - tagxref (whatever that really is!) ** ** Used by wcontent_page() and the JSON wiki code. */ void wiki_prepare_page_list( Stmt * pStmt ){ db_prepare(pStmt, "SELECT" " substr(tagname, 6) as name," " (SELECT value FROM tagxref WHERE tagid=tag.tagid ORDER BY mtime DESC) as tagXref" " FROM tag WHERE tagname GLOB 'wiki-*'" " ORDER BY lower(tagname) /*sort*/" ); } /* ** WEBPAGE: wcontent ** ** all=1 Show deleted pages ** ** List all available wiki pages with date created and last modified. */ void wcontent_page(void){ Stmt q; int showAll = P("all")!=0; login_check_credentials(); if( !g.perm.RdWiki ){ login_needed(); return; } style_header("Available Wiki Pages"); if( showAll ){ style_submenu_element("Active", "Only Active Pages", "%s/wcontent", g.zTop); }else{ style_submenu_element("All", "All", "%s/wcontent?all=1", g.zTop); } @ <ul> wiki_prepare_page_list(&q); while( db_step(&q)==SQLITE_ROW ){ const char *zName = db_column_text(&q, 0); int size = db_column_int(&q, 1); if( size>0 ){ @ <li><a href="%s(g.zTop)/wiki?name=%T(zName)">%h(zName)</a></li> }else if( showAll ){ @ <li><a href="%s(g.zTop)/wiki?name=%T(zName)"><s>%h(zName)</s></a></li> |
︙ | ︙ |
Changes to win/Makefile.dmc.
︙ | ︙ | |||
20 21 22 23 24 25 26 | CFLAGS = -o BCC = $(DMDIR)\bin\dmc $(CFLAGS) TCC = $(DMDIR)\bin\dmc $(CFLAGS) $(DMCDEF) $(SSL) $(INCL) LIBS = $(DMDIR)\extra\lib\ zlib wsock32 SQLITE_OPTIONS = -DSQLITE_OMIT_LOAD_EXTENSION=1 -DSQLITE_THREADSAFE=0 -DSQLITE_DEFAULT_FILE_FORMAT=4 -DSQLITE_ENABLE_STAT3 -Dlocaltime=fossil_localtime -DSQLITE_ENABLE_LOCKING_STYLE=0 | | | | | 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | CFLAGS = -o BCC = $(DMDIR)\bin\dmc $(CFLAGS) TCC = $(DMDIR)\bin\dmc $(CFLAGS) $(DMCDEF) $(SSL) $(INCL) LIBS = $(DMDIR)\extra\lib\ zlib wsock32 SQLITE_OPTIONS = -DSQLITE_OMIT_LOAD_EXTENSION=1 -DSQLITE_THREADSAFE=0 -DSQLITE_DEFAULT_FILE_FORMAT=4 -DSQLITE_ENABLE_STAT3 -Dlocaltime=fossil_localtime -DSQLITE_ENABLE_LOCKING_STYLE=0 SRC = add_.c allrepo_.c attach_.c bag_.c bisect_.c blob_.c branch_.c browse_.c captcha_.c cgi_.c checkin_.c checkout_.c clearsign_.c clone_.c comformat_.c configure_.c content_.c db_.c delta_.c deltacmd_.c descendants_.c diff_.c diffcmd_.c doc_.c encode_.c event_.c export_.c file_.c finfo_.c glob_.c graph_.c gzip_.c http_.c http_socket_.c http_ssl_.c http_transport_.c import_.c info_.c json_.c leaf_.c login_.c main_.c manifest_.c md5_.c merge_.c merge3_.c name_.c path_.c pivot_.c popen_.c pqueue_.c printf_.c rebuild_.c report_.c rss_.c schema_.c search_.c setup_.c sha1_.c shun_.c skins_.c sqlcmd_.c stash_.c stat_.c style_.c sync_.c tag_.c tar_.c th_main_.c timeline_.c tkt_.c tktsetup_.c undo_.c update_.c url_.c user_.c verify_.c vfile_.c wiki_.c wikiformat_.c winhttp_.c xfer_.c zip_.c OBJ = $(OBJDIR)\add$O $(OBJDIR)\allrepo$O $(OBJDIR)\attach$O $(OBJDIR)\bag$O $(OBJDIR)\bisect$O $(OBJDIR)\blob$O $(OBJDIR)\branch$O $(OBJDIR)\browse$O $(OBJDIR)\captcha$O $(OBJDIR)\cgi$O $(OBJDIR)\checkin$O $(OBJDIR)\checkout$O $(OBJDIR)\clearsign$O $(OBJDIR)\clone$O $(OBJDIR)\comformat$O $(OBJDIR)\configure$O $(OBJDIR)\content$O $(OBJDIR)\db$O $(OBJDIR)\delta$O $(OBJDIR)\deltacmd$O $(OBJDIR)\descendants$O $(OBJDIR)\diff$O $(OBJDIR)\diffcmd$O $(OBJDIR)\doc$O $(OBJDIR)\encode$O $(OBJDIR)\event$O $(OBJDIR)\export$O $(OBJDIR)\file$O $(OBJDIR)\finfo$O $(OBJDIR)\glob$O $(OBJDIR)\graph$O $(OBJDIR)\gzip$O $(OBJDIR)\http$O $(OBJDIR)\http_socket$O $(OBJDIR)\http_ssl$O $(OBJDIR)\http_transport$O $(OBJDIR)\import$O $(OBJDIR)\info$O $(OBJDIR)\json$O $(OBJDIR)\leaf$O $(OBJDIR)\login$O $(OBJDIR)\main$O $(OBJDIR)\manifest$O $(OBJDIR)\md5$O $(OBJDIR)\merge$O $(OBJDIR)\merge3$O $(OBJDIR)\name$O $(OBJDIR)\path$O $(OBJDIR)\pivot$O $(OBJDIR)\popen$O $(OBJDIR)\pqueue$O $(OBJDIR)\printf$O $(OBJDIR)\rebuild$O $(OBJDIR)\report$O $(OBJDIR)\rss$O $(OBJDIR)\schema$O $(OBJDIR)\search$O $(OBJDIR)\setup$O $(OBJDIR)\sha1$O $(OBJDIR)\shun$O $(OBJDIR)\skins$O $(OBJDIR)\sqlcmd$O $(OBJDIR)\stash$O $(OBJDIR)\stat$O $(OBJDIR)\style$O $(OBJDIR)\sync$O $(OBJDIR)\tag$O $(OBJDIR)\tar$O $(OBJDIR)\th_main$O $(OBJDIR)\timeline$O $(OBJDIR)\tkt$O $(OBJDIR)\tktsetup$O $(OBJDIR)\undo$O $(OBJDIR)\update$O $(OBJDIR)\url$O $(OBJDIR)\user$O $(OBJDIR)\verify$O $(OBJDIR)\vfile$O $(OBJDIR)\wiki$O $(OBJDIR)\wikiformat$O $(OBJDIR)\winhttp$O $(OBJDIR)\xfer$O $(OBJDIR)\zip$O $(OBJDIR)\shell$O $(OBJDIR)\sqlite3$O $(OBJDIR)\th$O $(OBJDIR)\th_lang$O RC=$(DMDIR)\bin\rcc RCFLAGS=-32 -w1 -I$(SRCDIR) /D__DMC__ APPNAME = $(OBJDIR)\fossil$(E) all: $(APPNAME) $(APPNAME) : translate$E mkindex$E headers $(OBJ) $(OBJDIR)\link cd $(OBJDIR) $(DMDIR)\bin\link @link $(OBJDIR)\fossil.res: $B\win\fossil.rc $(RC) $(RCFLAGS) -o$@ $** $(OBJDIR)\link: $B\win\Makefile.dmc $(OBJDIR)\fossil.res +echo add allrepo attach bag bisect blob branch browse captcha cgi checkin checkout clearsign clone comformat configure content db delta deltacmd descendants diff diffcmd doc encode event export file finfo glob graph gzip http http_socket http_ssl http_transport import info json leaf login main manifest md5 merge merge3 name path pivot popen pqueue printf rebuild report rss schema search setup sha1 shun skins sqlcmd stash stat style sync tag tar th_main timeline tkt tktsetup undo update url user verify vfile wiki wikiformat winhttp xfer zip shell sqlite3 th th_lang > $@ +echo fossil >> $@ +echo fossil >> $@ +echo $(LIBS) >> $@ +echo. >> $@ +echo fossil >> $@ translate$E: $(SRCDIR)\translate.c |
︙ | ︙ | |||
70 71 72 73 74 75 76 77 78 79 80 81 82 83 | $(TCC) -o$@ -c $(SQLITE_OPTIONS) $** $(OBJDIR)\th$O : $(SRCDIR)\th.c $(TCC) -o$@ -c $** $(OBJDIR)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) -o$@ -c $** VERSION.h : version$E $B\manifest.uuid $B\manifest $B\VERSION +$** > $@ page_index.h: mkindex$E $(SRC) +$** > $@ | > > > | 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | $(TCC) -o$@ -c $(SQLITE_OPTIONS) $** $(OBJDIR)\th$O : $(SRCDIR)\th.c $(TCC) -o$@ -c $** $(OBJDIR)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) -o$@ -c $** $(OBJDIR)\cson_amalgamation.h : $(SRCDIR)\cson_amalgamation.h cp $@ $@ VERSION.h : version$E $B\manifest.uuid $B\manifest $B\VERSION +$** > $@ page_index.h: mkindex$E $(SRC) +$** > $@ |
︙ | ︙ | |||
312 313 314 315 316 317 318 319 320 321 322 323 324 325 | +translate$E $** > $@ $(OBJDIR)\info$O : info_.c info.h $(TCC) -o$@ -c info_.c info_.c : $(SRCDIR)\info.c +translate$E $** > $@ $(OBJDIR)\leaf$O : leaf_.c leaf.h $(TCC) -o$@ -c leaf_.c leaf_.c : $(SRCDIR)\leaf.c +translate$E $** > $@ | > > > > > > | 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | +translate$E $** > $@ $(OBJDIR)\info$O : info_.c info.h $(TCC) -o$@ -c info_.c info_.c : $(SRCDIR)\info.c +translate$E $** > $@ $(OBJDIR)\json$O : json_.c json.h $(TCC) -o$@ -c json_.c json_.c : $(SRCDIR)\json.c +translate$E $** > $@ $(OBJDIR)\leaf$O : leaf_.c leaf.h $(TCC) -o$@ -c leaf_.c leaf_.c : $(SRCDIR)\leaf.c +translate$E $** > $@ |
︙ | ︙ | |||
578 579 580 581 582 583 584 | $(OBJDIR)\zip$O : zip_.c zip.h $(TCC) -o$@ -c zip_.c zip_.c : $(SRCDIR)\zip.c +translate$E $** > $@ headers: makeheaders$E page_index.h VERSION.h | | | 587 588 589 590 591 592 593 594 595 | $(OBJDIR)\zip$O : zip_.c zip.h $(TCC) -o$@ -c zip_.c zip_.c : $(SRCDIR)\zip.c +translate$E $** > $@ headers: makeheaders$E page_index.h VERSION.h +makeheaders$E add_.c:add.h allrepo_.c:allrepo.h attach_.c:attach.h bag_.c:bag.h bisect_.c:bisect.h blob_.c:blob.h branch_.c:branch.h browse_.c:browse.h captcha_.c:captcha.h cgi_.c:cgi.h checkin_.c:checkin.h checkout_.c:checkout.h clearsign_.c:clearsign.h clone_.c:clone.h comformat_.c:comformat.h configure_.c:configure.h content_.c:content.h db_.c:db.h delta_.c:delta.h deltacmd_.c:deltacmd.h descendants_.c:descendants.h diff_.c:diff.h diffcmd_.c:diffcmd.h doc_.c:doc.h encode_.c:encode.h event_.c:event.h export_.c:export.h file_.c:file.h finfo_.c:finfo.h glob_.c:glob.h graph_.c:graph.h gzip_.c:gzip.h http_.c:http.h http_socket_.c:http_socket.h http_ssl_.c:http_ssl.h http_transport_.c:http_transport.h import_.c:import.h info_.c:info.h json_.c:json.h leaf_.c:leaf.h login_.c:login.h main_.c:main.h manifest_.c:manifest.h md5_.c:md5.h merge_.c:merge.h merge3_.c:merge3.h name_.c:name.h path_.c:path.h pivot_.c:pivot.h popen_.c:popen.h pqueue_.c:pqueue.h printf_.c:printf.h rebuild_.c:rebuild.h report_.c:report.h rss_.c:rss.h schema_.c:schema.h search_.c:search.h setup_.c:setup.h sha1_.c:sha1.h shun_.c:shun.h skins_.c:skins.h sqlcmd_.c:sqlcmd.h stash_.c:stash.h stat_.c:stat.h style_.c:style.h sync_.c:sync.h tag_.c:tag.h tar_.c:tar.h th_main_.c:th_main.h timeline_.c:timeline.h tkt_.c:tkt.h tktsetup_.c:tktsetup.h undo_.c:undo.h update_.c:update.h url_.c:url.h user_.c:user.h verify_.c:verify.h vfile_.c:vfile.h wiki_.c:wiki.h wikiformat_.c:wikiformat.h winhttp_.c:winhttp.h xfer_.c:xfer.h zip_.c:zip.h $(SRCDIR)\sqlite3.h $(SRCDIR)\th.h VERSION.h $(SRCDIR)\cson_amalgamation.h @copy /Y nul: headers |
Changes to win/Makefile.mingw.
︙ | ︙ | |||
108 109 110 111 112 113 114 115 116 117 118 119 120 121 | $(SRCDIR)/gzip.c \ $(SRCDIR)/http.c \ $(SRCDIR)/http_socket.c \ $(SRCDIR)/http_ssl.c \ $(SRCDIR)/http_transport.c \ $(SRCDIR)/import.c \ $(SRCDIR)/info.c \ $(SRCDIR)/leaf.c \ $(SRCDIR)/login.c \ $(SRCDIR)/main.c \ $(SRCDIR)/manifest.c \ $(SRCDIR)/md5.c \ $(SRCDIR)/merge.c \ $(SRCDIR)/merge3.c \ | > | 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | $(SRCDIR)/gzip.c \ $(SRCDIR)/http.c \ $(SRCDIR)/http_socket.c \ $(SRCDIR)/http_ssl.c \ $(SRCDIR)/http_transport.c \ $(SRCDIR)/import.c \ $(SRCDIR)/info.c \ $(SRCDIR)/json.c \ $(SRCDIR)/leaf.c \ $(SRCDIR)/login.c \ $(SRCDIR)/main.c \ $(SRCDIR)/manifest.c \ $(SRCDIR)/md5.c \ $(SRCDIR)/merge.c \ $(SRCDIR)/merge3.c \ |
︙ | ︙ | |||
192 193 194 195 196 197 198 199 200 201 202 203 204 205 | $(OBJDIR)/gzip_.c \ $(OBJDIR)/http_.c \ $(OBJDIR)/http_socket_.c \ $(OBJDIR)/http_ssl_.c \ $(OBJDIR)/http_transport_.c \ $(OBJDIR)/import_.c \ $(OBJDIR)/info_.c \ $(OBJDIR)/leaf_.c \ $(OBJDIR)/login_.c \ $(OBJDIR)/main_.c \ $(OBJDIR)/manifest_.c \ $(OBJDIR)/md5_.c \ $(OBJDIR)/merge_.c \ $(OBJDIR)/merge3_.c \ | > | 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | $(OBJDIR)/gzip_.c \ $(OBJDIR)/http_.c \ $(OBJDIR)/http_socket_.c \ $(OBJDIR)/http_ssl_.c \ $(OBJDIR)/http_transport_.c \ $(OBJDIR)/import_.c \ $(OBJDIR)/info_.c \ $(OBJDIR)/json_.c \ $(OBJDIR)/leaf_.c \ $(OBJDIR)/login_.c \ $(OBJDIR)/main_.c \ $(OBJDIR)/manifest_.c \ $(OBJDIR)/md5_.c \ $(OBJDIR)/merge_.c \ $(OBJDIR)/merge3_.c \ |
︙ | ︙ | |||
276 277 278 279 280 281 282 283 284 285 286 287 288 289 | $(OBJDIR)/gzip.o \ $(OBJDIR)/http.o \ $(OBJDIR)/http_socket.o \ $(OBJDIR)/http_ssl.o \ $(OBJDIR)/http_transport.o \ $(OBJDIR)/import.o \ $(OBJDIR)/info.o \ $(OBJDIR)/leaf.o \ $(OBJDIR)/login.o \ $(OBJDIR)/main.o \ $(OBJDIR)/manifest.o \ $(OBJDIR)/md5.o \ $(OBJDIR)/merge.o \ $(OBJDIR)/merge3.o \ | > | 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | $(OBJDIR)/gzip.o \ $(OBJDIR)/http.o \ $(OBJDIR)/http_socket.o \ $(OBJDIR)/http_ssl.o \ $(OBJDIR)/http_transport.o \ $(OBJDIR)/import.o \ $(OBJDIR)/info.o \ $(OBJDIR)/json.o \ $(OBJDIR)/leaf.o \ $(OBJDIR)/login.o \ $(OBJDIR)/main.o \ $(OBJDIR)/manifest.o \ $(OBJDIR)/md5.o \ $(OBJDIR)/merge.o \ $(OBJDIR)/merge3.o \ |
︙ | ︙ | |||
361 362 363 364 365 366 367 | # the repository after running the tests. test: $(APPNAME) $(TCLSH) test/tester.tcl $(APPNAME) $(OBJDIR)/VERSION.h: $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(VERSION) $(VERSION) $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(SRCDIR)/../VERSION >$(OBJDIR)/VERSION.h | | | 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | # the repository after running the tests. test: $(APPNAME) $(TCLSH) test/tester.tcl $(APPNAME) $(OBJDIR)/VERSION.h: $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(VERSION) $(VERSION) $(SRCDIR)/../manifest.uuid $(SRCDIR)/../manifest $(SRCDIR)/../VERSION >$(OBJDIR)/VERSION.h EXTRAOBJ = $(OBJDIR)/sqlite3.o $(OBJDIR)/shell.o $(OBJDIR)/th.o $(OBJDIR)/th_lang.o $(OBJDIR)/cson_amalgamation.o $(APPNAME): $(OBJDIR)/headers $(OBJ) $(EXTRAOBJ) $(OBJDIR)/icon.o $(TCC) -o $(APPNAME) $(OBJ) $(EXTRAOBJ) $(LIB) $(OBJDIR)/icon.o # This rule prevents make from using its default rules to try build # an executable named "manifest" out of the file named "manifest.c" # |
︙ | ︙ | |||
386 387 388 389 390 391 392 | setup: $(OBJDIR) $(APPNAME) $(MAKENSIS) ./fossil.nsi $(OBJDIR)/page_index.h: $(TRANS_SRC) $(OBJDIR)/mkindex $(MKINDEX) $(TRANS_SRC) >$@ $(OBJDIR)/headers: $(OBJDIR)/page_index.h $(OBJDIR)/makeheaders $(OBJDIR)/VERSION.h | | | 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | setup: $(OBJDIR) $(APPNAME) $(MAKENSIS) ./fossil.nsi $(OBJDIR)/page_index.h: $(TRANS_SRC) $(OBJDIR)/mkindex $(MKINDEX) $(TRANS_SRC) >$@ $(OBJDIR)/headers: $(OBJDIR)/page_index.h $(OBJDIR)/makeheaders $(OBJDIR)/VERSION.h $(MAKEHEADERS) $(OBJDIR)/add_.c:$(OBJDIR)/add.h $(OBJDIR)/allrepo_.c:$(OBJDIR)/allrepo.h $(OBJDIR)/attach_.c:$(OBJDIR)/attach.h $(OBJDIR)/bag_.c:$(OBJDIR)/bag.h $(OBJDIR)/bisect_.c:$(OBJDIR)/bisect.h $(OBJDIR)/blob_.c:$(OBJDIR)/blob.h $(OBJDIR)/branch_.c:$(OBJDIR)/branch.h $(OBJDIR)/browse_.c:$(OBJDIR)/browse.h $(OBJDIR)/captcha_.c:$(OBJDIR)/captcha.h $(OBJDIR)/cgi_.c:$(OBJDIR)/cgi.h $(OBJDIR)/checkin_.c:$(OBJDIR)/checkin.h $(OBJDIR)/checkout_.c:$(OBJDIR)/checkout.h $(OBJDIR)/clearsign_.c:$(OBJDIR)/clearsign.h $(OBJDIR)/clone_.c:$(OBJDIR)/clone.h $(OBJDIR)/comformat_.c:$(OBJDIR)/comformat.h $(OBJDIR)/configure_.c:$(OBJDIR)/configure.h $(OBJDIR)/content_.c:$(OBJDIR)/content.h $(OBJDIR)/db_.c:$(OBJDIR)/db.h $(OBJDIR)/delta_.c:$(OBJDIR)/delta.h $(OBJDIR)/deltacmd_.c:$(OBJDIR)/deltacmd.h $(OBJDIR)/descendants_.c:$(OBJDIR)/descendants.h $(OBJDIR)/diff_.c:$(OBJDIR)/diff.h $(OBJDIR)/diffcmd_.c:$(OBJDIR)/diffcmd.h $(OBJDIR)/doc_.c:$(OBJDIR)/doc.h $(OBJDIR)/encode_.c:$(OBJDIR)/encode.h $(OBJDIR)/event_.c:$(OBJDIR)/event.h $(OBJDIR)/export_.c:$(OBJDIR)/export.h $(OBJDIR)/file_.c:$(OBJDIR)/file.h $(OBJDIR)/finfo_.c:$(OBJDIR)/finfo.h $(OBJDIR)/glob_.c:$(OBJDIR)/glob.h $(OBJDIR)/graph_.c:$(OBJDIR)/graph.h $(OBJDIR)/gzip_.c:$(OBJDIR)/gzip.h $(OBJDIR)/http_.c:$(OBJDIR)/http.h $(OBJDIR)/http_socket_.c:$(OBJDIR)/http_socket.h $(OBJDIR)/http_ssl_.c:$(OBJDIR)/http_ssl.h $(OBJDIR)/http_transport_.c:$(OBJDIR)/http_transport.h $(OBJDIR)/import_.c:$(OBJDIR)/import.h $(OBJDIR)/info_.c:$(OBJDIR)/info.h $(OBJDIR)/json_.c:$(OBJDIR)/json.h $(OBJDIR)/leaf_.c:$(OBJDIR)/leaf.h $(OBJDIR)/login_.c:$(OBJDIR)/login.h $(OBJDIR)/main_.c:$(OBJDIR)/main.h $(OBJDIR)/manifest_.c:$(OBJDIR)/manifest.h $(OBJDIR)/md5_.c:$(OBJDIR)/md5.h $(OBJDIR)/merge_.c:$(OBJDIR)/merge.h $(OBJDIR)/merge3_.c:$(OBJDIR)/merge3.h $(OBJDIR)/name_.c:$(OBJDIR)/name.h $(OBJDIR)/path_.c:$(OBJDIR)/path.h $(OBJDIR)/pivot_.c:$(OBJDIR)/pivot.h $(OBJDIR)/popen_.c:$(OBJDIR)/popen.h $(OBJDIR)/pqueue_.c:$(OBJDIR)/pqueue.h $(OBJDIR)/printf_.c:$(OBJDIR)/printf.h $(OBJDIR)/rebuild_.c:$(OBJDIR)/rebuild.h $(OBJDIR)/report_.c:$(OBJDIR)/report.h $(OBJDIR)/rss_.c:$(OBJDIR)/rss.h $(OBJDIR)/schema_.c:$(OBJDIR)/schema.h $(OBJDIR)/search_.c:$(OBJDIR)/search.h $(OBJDIR)/setup_.c:$(OBJDIR)/setup.h $(OBJDIR)/sha1_.c:$(OBJDIR)/sha1.h $(OBJDIR)/shun_.c:$(OBJDIR)/shun.h $(OBJDIR)/skins_.c:$(OBJDIR)/skins.h $(OBJDIR)/sqlcmd_.c:$(OBJDIR)/sqlcmd.h $(OBJDIR)/stash_.c:$(OBJDIR)/stash.h $(OBJDIR)/stat_.c:$(OBJDIR)/stat.h $(OBJDIR)/style_.c:$(OBJDIR)/style.h $(OBJDIR)/sync_.c:$(OBJDIR)/sync.h $(OBJDIR)/tag_.c:$(OBJDIR)/tag.h $(OBJDIR)/tar_.c:$(OBJDIR)/tar.h $(OBJDIR)/th_main_.c:$(OBJDIR)/th_main.h $(OBJDIR)/timeline_.c:$(OBJDIR)/timeline.h $(OBJDIR)/tkt_.c:$(OBJDIR)/tkt.h $(OBJDIR)/tktsetup_.c:$(OBJDIR)/tktsetup.h $(OBJDIR)/undo_.c:$(OBJDIR)/undo.h $(OBJDIR)/update_.c:$(OBJDIR)/update.h $(OBJDIR)/url_.c:$(OBJDIR)/url.h $(OBJDIR)/user_.c:$(OBJDIR)/user.h $(OBJDIR)/verify_.c:$(OBJDIR)/verify.h $(OBJDIR)/vfile_.c:$(OBJDIR)/vfile.h $(OBJDIR)/wiki_.c:$(OBJDIR)/wiki.h $(OBJDIR)/wikiformat_.c:$(OBJDIR)/wikiformat.h $(OBJDIR)/winhttp_.c:$(OBJDIR)/winhttp.h $(OBJDIR)/xfer_.c:$(OBJDIR)/xfer.h $(OBJDIR)/zip_.c:$(OBJDIR)/zip.h $(SRCDIR)/sqlite3.h $(SRCDIR)/th.h $(OBJDIR)/VERSION.h echo Done >$(OBJDIR)/headers $(OBJDIR)/headers: Makefile Makefile: $(OBJDIR)/add_.c: $(SRCDIR)/add.c $(OBJDIR)/translate $(TRANSLATE) $(SRCDIR)/add.c >$(OBJDIR)/add_.c |
︙ | ︙ | |||
657 658 659 660 661 662 663 664 665 666 667 668 669 670 | $(OBJDIR)/info_.c: $(SRCDIR)/info.c $(OBJDIR)/translate $(TRANSLATE) $(SRCDIR)/info.c >$(OBJDIR)/info_.c $(OBJDIR)/info.o: $(OBJDIR)/info_.c $(OBJDIR)/info.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/info.o -c $(OBJDIR)/info_.c info.h: $(OBJDIR)/headers $(OBJDIR)/leaf_.c: $(SRCDIR)/leaf.c $(OBJDIR)/translate $(TRANSLATE) $(SRCDIR)/leaf.c >$(OBJDIR)/leaf_.c $(OBJDIR)/leaf.o: $(OBJDIR)/leaf_.c $(OBJDIR)/leaf.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/leaf.o -c $(OBJDIR)/leaf_.c leaf.h: $(OBJDIR)/headers | > > > > > > > | 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 | $(OBJDIR)/info_.c: $(SRCDIR)/info.c $(OBJDIR)/translate $(TRANSLATE) $(SRCDIR)/info.c >$(OBJDIR)/info_.c $(OBJDIR)/info.o: $(OBJDIR)/info_.c $(OBJDIR)/info.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/info.o -c $(OBJDIR)/info_.c info.h: $(OBJDIR)/headers $(OBJDIR)/json_.c: $(SRCDIR)/json.c $(OBJDIR)/translate $(TRANSLATE) $(SRCDIR)/json.c >$(OBJDIR)/json_.c $(OBJDIR)/json.o: $(OBJDIR)/json_.c $(OBJDIR)/json.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/json.o -c $(OBJDIR)/json_.c json.h: $(OBJDIR)/headers $(OBJDIR)/leaf_.c: $(SRCDIR)/leaf.c $(OBJDIR)/translate $(TRANSLATE) $(SRCDIR)/leaf.c >$(OBJDIR)/leaf_.c $(OBJDIR)/leaf.o: $(OBJDIR)/leaf_.c $(OBJDIR)/leaf.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/leaf.o -c $(OBJDIR)/leaf_.c leaf.h: $(OBJDIR)/headers |
︙ | ︙ | |||
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 | $(OBJDIR)/zip.o: $(OBJDIR)/zip_.c $(OBJDIR)/zip.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/zip.o -c $(OBJDIR)/zip_.c zip.h: $(OBJDIR)/headers $(OBJDIR)/sqlite3.o: $(SRCDIR)/sqlite3.c $(XTCC) -DSQLITE_OMIT_LOAD_EXTENSION=1 -DSQLITE_THREADSAFE=0 -DSQLITE_DEFAULT_FILE_FORMAT=4 -DSQLITE_ENABLE_STAT3 -Dlocaltime=fossil_localtime -DSQLITE_ENABLE_LOCKING_STYLE=0 -c $(SRCDIR)/sqlite3.c -o $(OBJDIR)/sqlite3.o $(OBJDIR)/shell.o: $(SRCDIR)/shell.c $(SRCDIR)/sqlite3.h $(XTCC) -Dmain=sqlite3_shell -DSQLITE_OMIT_LOAD_EXTENSION=1 -c $(SRCDIR)/shell.c -o $(OBJDIR)/shell.o $(OBJDIR)/th.o: $(SRCDIR)/th.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th.c -o $(OBJDIR)/th.o $(OBJDIR)/th_lang.o: $(SRCDIR)/th_lang.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th_lang.c -o $(OBJDIR)/th_lang.o | > > > | 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 | $(OBJDIR)/zip.o: $(OBJDIR)/zip_.c $(OBJDIR)/zip.h $(SRCDIR)/config.h $(XTCC) -o $(OBJDIR)/zip.o -c $(OBJDIR)/zip_.c zip.h: $(OBJDIR)/headers $(OBJDIR)/sqlite3.o: $(SRCDIR)/sqlite3.c $(XTCC) -DSQLITE_OMIT_LOAD_EXTENSION=1 -DSQLITE_THREADSAFE=0 -DSQLITE_DEFAULT_FILE_FORMAT=4 -DSQLITE_ENABLE_STAT3 -Dlocaltime=fossil_localtime -DSQLITE_ENABLE_LOCKING_STYLE=0 -c $(SRCDIR)/sqlite3.c -o $(OBJDIR)/sqlite3.o $(OBJDIR)/cson_amalgamation.o: $(SRCDIR)/cson_amalgamation.c $(XTCC) -c $(SRCDIR)/cson_amalgamation.c -o $(OBJDIR)/cson_amalgamation.o $(OBJDIR)/shell.o: $(SRCDIR)/shell.c $(SRCDIR)/sqlite3.h $(XTCC) -Dmain=sqlite3_shell -DSQLITE_OMIT_LOAD_EXTENSION=1 -c $(SRCDIR)/shell.c -o $(OBJDIR)/shell.o $(OBJDIR)/th.o: $(SRCDIR)/th.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th.c -o $(OBJDIR)/th.o $(OBJDIR)/th_lang.o: $(SRCDIR)/th_lang.c $(XTCC) -I$(SRCDIR) -c $(SRCDIR)/th_lang.c -o $(OBJDIR)/th_lang.o |
Changes to win/Makefile.msc.
︙ | ︙ | |||
34 35 36 37 38 39 40 | BCC = $(CC) $(CFLAGS) TCC = $(CC) -c $(CFLAGS) $(MSCDEF) $(SSL) $(INCL) LIBS = $(ZLIB) ws2_32.lib advapi32.lib $(SSLLIB) LIBDIR = -LIBPATH:$(MSCDIR)\extra\lib -LIBPATH:$(ZLIBDIR) SQLITE_OPTIONS = /DSQLITE_OMIT_LOAD_EXTENSION=1 /DSQLITE_THREADSAFE=0 /DSQLITE_DEFAULT_FILE_FORMAT=4 /DSQLITE_ENABLE_STAT3 /Dlocaltime=fossil_localtime /DSQLITE_ENABLE_LOCKING_STYLE=0 | | | | 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | BCC = $(CC) $(CFLAGS) TCC = $(CC) -c $(CFLAGS) $(MSCDEF) $(SSL) $(INCL) LIBS = $(ZLIB) ws2_32.lib advapi32.lib $(SSLLIB) LIBDIR = -LIBPATH:$(MSCDIR)\extra\lib -LIBPATH:$(ZLIBDIR) SQLITE_OPTIONS = /DSQLITE_OMIT_LOAD_EXTENSION=1 /DSQLITE_THREADSAFE=0 /DSQLITE_DEFAULT_FILE_FORMAT=4 /DSQLITE_ENABLE_STAT3 /Dlocaltime=fossil_localtime /DSQLITE_ENABLE_LOCKING_STYLE=0 SRC = add_.c allrepo_.c attach_.c bag_.c bisect_.c blob_.c branch_.c browse_.c captcha_.c cgi_.c checkin_.c checkout_.c clearsign_.c clone_.c comformat_.c configure_.c content_.c db_.c delta_.c deltacmd_.c descendants_.c diff_.c diffcmd_.c doc_.c encode_.c event_.c export_.c file_.c finfo_.c glob_.c graph_.c gzip_.c http_.c http_socket_.c http_ssl_.c http_transport_.c import_.c info_.c json_.c leaf_.c login_.c main_.c manifest_.c md5_.c merge_.c merge3_.c name_.c path_.c pivot_.c popen_.c pqueue_.c printf_.c rebuild_.c report_.c rss_.c schema_.c search_.c setup_.c sha1_.c shun_.c skins_.c sqlcmd_.c stash_.c stat_.c style_.c sync_.c tag_.c tar_.c th_main_.c timeline_.c tkt_.c tktsetup_.c undo_.c update_.c url_.c user_.c verify_.c vfile_.c wiki_.c wikiformat_.c winhttp_.c xfer_.c zip_.c OBJ = $(OX)\add$O $(OX)\allrepo$O $(OX)\attach$O $(OX)\bag$O $(OX)\bisect$O $(OX)\blob$O $(OX)\branch$O $(OX)\browse$O $(OX)\captcha$O $(OX)\cgi$O $(OX)\checkin$O $(OX)\checkout$O $(OX)\clearsign$O $(OX)\clone$O $(OX)\comformat$O $(OX)\configure$O $(OX)\content$O $(OX)\db$O $(OX)\delta$O $(OX)\deltacmd$O $(OX)\descendants$O $(OX)\diff$O $(OX)\diffcmd$O $(OX)\doc$O $(OX)\encode$O $(OX)\event$O $(OX)\export$O $(OX)\file$O $(OX)\finfo$O $(OX)\glob$O $(OX)\graph$O $(OX)\gzip$O $(OX)\http$O $(OX)\http_socket$O $(OX)\http_ssl$O $(OX)\http_transport$O $(OX)\import$O $(OX)\info$O $(OX)\json$O $(OX)\leaf$O $(OX)\login$O $(OX)\main$O $(OX)\manifest$O $(OX)\md5$O $(OX)\merge$O $(OX)\merge3$O $(OX)\name$O $(OX)\path$O $(OX)\pivot$O $(OX)\popen$O $(OX)\pqueue$O $(OX)\printf$O $(OX)\rebuild$O $(OX)\report$O $(OX)\rss$O $(OX)\schema$O $(OX)\search$O $(OX)\setup$O $(OX)\sha1$O $(OX)\shun$O $(OX)\skins$O $(OX)\sqlcmd$O $(OX)\stash$O $(OX)\stat$O $(OX)\style$O $(OX)\sync$O $(OX)\tag$O $(OX)\tar$O $(OX)\th_main$O $(OX)\timeline$O $(OX)\tkt$O $(OX)\tktsetup$O $(OX)\undo$O $(OX)\update$O $(OX)\url$O $(OX)\user$O $(OX)\verify$O $(OX)\vfile$O $(OX)\wiki$O $(OX)\wikiformat$O $(OX)\winhttp$O $(OX)\xfer$O $(OX)\zip$O $(OX)\shell$O $(OX)\sqlite3$O $(OX)\th$O $(OX)\th_lang$O APPNAME = $(OX)\fossil$(E) all: $(OX) $(APPNAME) $(APPNAME) : translate$E mkindex$E headers $(OBJ) $(OX)\linkopts |
︙ | ︙ | |||
86 87 88 89 90 91 92 93 94 95 96 97 98 99 | echo $(OX)\gzip.obj >> $@ echo $(OX)\http.obj >> $@ echo $(OX)\http_socket.obj >> $@ echo $(OX)\http_ssl.obj >> $@ echo $(OX)\http_transport.obj >> $@ echo $(OX)\import.obj >> $@ echo $(OX)\info.obj >> $@ echo $(OX)\leaf.obj >> $@ echo $(OX)\login.obj >> $@ echo $(OX)\main.obj >> $@ echo $(OX)\manifest.obj >> $@ echo $(OX)\md5.obj >> $@ echo $(OX)\merge.obj >> $@ echo $(OX)\merge3.obj >> $@ | > | 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | echo $(OX)\gzip.obj >> $@ echo $(OX)\http.obj >> $@ echo $(OX)\http_socket.obj >> $@ echo $(OX)\http_ssl.obj >> $@ echo $(OX)\http_transport.obj >> $@ echo $(OX)\import.obj >> $@ echo $(OX)\info.obj >> $@ echo $(OX)\json.obj >> $@ echo $(OX)\leaf.obj >> $@ echo $(OX)\login.obj >> $@ echo $(OX)\main.obj >> $@ echo $(OX)\manifest.obj >> $@ echo $(OX)\md5.obj >> $@ echo $(OX)\merge.obj >> $@ echo $(OX)\merge3.obj >> $@ |
︙ | ︙ | |||
168 169 170 171 172 173 174 175 176 177 178 179 180 181 | $(TCC) /Fo$@ -c $** $(OX)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) /Fo$@ -c $** VERSION.h : mkversion$E $B\manifest.uuid $B\manifest $B\VERSION $** > $@ page_index.h: mkindex$E $(SRC) $** > $@ clean: -del $(OX)\*.obj -del *.obj *_.c *.h *.map | > > | 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | $(TCC) /Fo$@ -c $** $(OX)\th_lang$O : $(SRCDIR)\th_lang.c $(TCC) /Fo$@ -c $** VERSION.h : mkversion$E $B\manifest.uuid $B\manifest $B\VERSION $** > $@ $(OBJDIR)\cson_amalgamation.h : $(SRCDIR)\cson_amalgamation.h cp $(SRCDIR)\cson_amalgamation.h $@ page_index.h: mkindex$E $(SRC) $** > $@ clean: -del $(OX)\*.obj -del *.obj *_.c *.h *.map |
︙ | ︙ | |||
408 409 410 411 412 413 414 415 416 417 418 419 420 421 | translate$E $** > $@ $(OX)\info$O : info_.c info.h $(TCC) /Fo$@ -c info_.c info_.c : $(SRCDIR)\info.c translate$E $** > $@ $(OX)\leaf$O : leaf_.c leaf.h $(TCC) /Fo$@ -c leaf_.c leaf_.c : $(SRCDIR)\leaf.c translate$E $** > $@ | > > > > > > | 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 | translate$E $** > $@ $(OX)\info$O : info_.c info.h $(TCC) /Fo$@ -c info_.c info_.c : $(SRCDIR)\info.c translate$E $** > $@ $(OX)\json$O : json_.c json.h $(TCC) /Fo$@ -c json_.c json_.c : $(SRCDIR)\json.c translate$E $** > $@ $(OX)\leaf$O : leaf_.c leaf.h $(TCC) /Fo$@ -c leaf_.c leaf_.c : $(SRCDIR)\leaf.c translate$E $** > $@ |
︙ | ︙ | |||
674 675 676 677 678 679 680 | $(OX)\zip$O : zip_.c zip.h $(TCC) /Fo$@ -c zip_.c zip_.c : $(SRCDIR)\zip.c translate$E $** > $@ headers: makeheaders$E page_index.h VERSION.h | | | 683 684 685 686 687 688 689 690 691 | $(OX)\zip$O : zip_.c zip.h $(TCC) /Fo$@ -c zip_.c zip_.c : $(SRCDIR)\zip.c translate$E $** > $@ headers: makeheaders$E page_index.h VERSION.h makeheaders$E add_.c:add.h allrepo_.c:allrepo.h attach_.c:attach.h bag_.c:bag.h bisect_.c:bisect.h blob_.c:blob.h branch_.c:branch.h browse_.c:browse.h captcha_.c:captcha.h cgi_.c:cgi.h checkin_.c:checkin.h checkout_.c:checkout.h clearsign_.c:clearsign.h clone_.c:clone.h comformat_.c:comformat.h configure_.c:configure.h content_.c:content.h db_.c:db.h delta_.c:delta.h deltacmd_.c:deltacmd.h descendants_.c:descendants.h diff_.c:diff.h diffcmd_.c:diffcmd.h doc_.c:doc.h encode_.c:encode.h event_.c:event.h export_.c:export.h file_.c:file.h finfo_.c:finfo.h glob_.c:glob.h graph_.c:graph.h gzip_.c:gzip.h http_.c:http.h http_socket_.c:http_socket.h http_ssl_.c:http_ssl.h http_transport_.c:http_transport.h import_.c:import.h info_.c:info.h json_.c:json.h leaf_.c:leaf.h login_.c:login.h main_.c:main.h manifest_.c:manifest.h md5_.c:md5.h merge_.c:merge.h merge3_.c:merge3.h name_.c:name.h path_.c:path.h pivot_.c:pivot.h popen_.c:popen.h pqueue_.c:pqueue.h printf_.c:printf.h rebuild_.c:rebuild.h report_.c:report.h rss_.c:rss.h schema_.c:schema.h search_.c:search.h setup_.c:setup.h sha1_.c:sha1.h shun_.c:shun.h skins_.c:skins.h sqlcmd_.c:sqlcmd.h stash_.c:stash.h stat_.c:stat.h style_.c:style.h sync_.c:sync.h tag_.c:tag.h tar_.c:tar.h th_main_.c:th_main.h timeline_.c:timeline.h tkt_.c:tkt.h tktsetup_.c:tktsetup.h undo_.c:undo.h update_.c:update.h url_.c:url.h user_.c:user.h verify_.c:verify.h vfile_.c:vfile.h wiki_.c:wiki.h wikiformat_.c:wikiformat.h winhttp_.c:winhttp.h xfer_.c:xfer.h zip_.c:zip.h $(SRCDIR)\sqlite3.h $(SRCDIR)\th.h VERSION.h $(SRCDIR)\cson_amalgamation.h @copy /Y nul: headers |