gs2parser.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #include "gs2parser.h"
00024
00025 #include <stdint.h>
00026
00027
00028
00029
00030
00031
00032
00033 int
00034 gs2_parser (const char *token, size_t toklen, struct gs2_token *out)
00035 {
00036 uint32_t context_length, wrap_length;
00037
00038 if (!out)
00039 return -1;
00040
00041
00042 if (toklen <= 8)
00043 return -1;
00044
00045 context_length =
00046 (token[0] << 24) & 0xFF000000 |
00047 (token[1] << 16) & 0xFF0000 |
00048 (token[2] << 8) & 0xFF00 | (token[3]) & 0xFF;
00049
00050 wrap_length =
00051 (token[4] << 24) & 0xFF000000 |
00052 (token[5] << 16) & 0xFF0000 |
00053 (token[6] << 8) & 0xFF00 | (token[7]) & 0xFF;
00054
00055
00056 if (context_length > toklen || wrap_length > toklen ||
00057 context_length + wrap_length + 8 != toklen)
00058 return -1;
00059
00060 out->context_length = context_length;
00061 if (context_length > 0)
00062 out->context_token = token + 8;
00063 else
00064 out->context_token = NULL;
00065
00066 out->wrap_length = wrap_length;
00067 if (wrap_length > 0)
00068 out->wrap_token = token + 8 + context_length;
00069 else
00070 out->wrap_token = NULL;
00071
00072 return 0;
00073 }
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083 int
00084 gs2_encode (const char *context, size_t context_length,
00085 const char *wrap, size_t wrap_length, char **out, size_t * outlen)
00086 {
00087 size_t totlen = 4 + context_length + wrap_length;
00088 uint32_t ctxlen;
00089
00090
00091 if (totlen > UINT32_MAX || totlen < context_length || totlen < wrap_length)
00092 return -1;
00093
00094
00095 if (context == NULL && context_length != 0)
00096 return -2;
00097 if (wrap == NULL && wrap_length != 0)
00098 return -3;
00099
00100 if (outlen)
00101 *outlen = totlen;
00102
00103 if (!out)
00104 return 0;
00105
00106 *out = malloc (*outlen);
00107 if (!*out)
00108 return -4;
00109
00110 (*out)[0] = (context_length >> 24) & 0xFF;
00111 (*out)[1] = (context_length >> 16) & 0xFF;
00112 (*out)[2] = (context_length >> 8) & 0xFF;
00113 (*out)[3] = context_length & 0xFF;
00114
00115 if (context)
00116 memcpy (*out + 4, context, context_length);
00117 if (wrap)
00118 memcpy (*out + 4 + context_length, wrap, wrap_length);
00119
00120 return 0;
00121 }