httpJson.c 14.3 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * 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.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
21
#include <errno.h>
H
hzcheng 已提交
22 23 24 25 26 27

#include "http.h"
#include "httpCode.h"
#include "httpJson.h"
#include "httpResp.h"
#include "taosmsg.h"
S
slguan 已提交
28
#include "httpLog.h"
S
slguan 已提交
29
#include "taoserror.h"
H
hzcheng 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

#define MAX_NUM_STR_SZ 25

char JsonItmTkn = ',';
char JsonObjStt = '{';
char JsonObjEnd = '}';
char JsonArrStt = '[';
char JsonArrEnd = ']';
char JsonStrStt = '\"';
char JsonStrEnd = '\"';
char JsonPairTkn = ':';
char JsonNulTkn[] = "null";
char JsonTrueTkn[] = "true";
char JsonFalseTkn[] = "false";

45
int httpWriteBufByFd(struct HttpContext* pContext, const char* buf, int sz) {
H
hzcheng 已提交
46 47
  int       len;
  int       countWait = 0;
48
  int       writeLen = 0;
H
hzcheng 已提交
49 50

  do {
51 52 53 54 55 56 57
    if (pContext->fd > 2){
      len = (int)send(pContext->fd, buf + writeLen, (size_t)(sz - writeLen), MSG_NOSIGNAL);
    }
    else {
      return sz;
    }

H
hzcheng 已提交
58
    if (len < 0) {
59 60 61 62 63
      httpTrace("context:%p, fd:%d, ip:%s, socket write errno:%d, times:%d",
                pContext, pContext->fd, pContext->ipstr, errno, countWait);
      if (++countWait > HTTP_WRITE_RETRY_TIMES) break;
      taosMsleep(HTTP_WRITE_WAIT_TIME_MS);
      continue;
H
hzcheng 已提交
64
    } else if (len == 0) {
65 66 67
      httpTrace("context:%p, fd:%d, ip:%s, socket write errno:%d, connect already closed",
                pContext, pContext->fd, pContext->ipstr, errno);
      break;
H
hzcheng 已提交
68 69
    } else {
      countWait = 0;
70
      writeLen += len;
H
hzcheng 已提交
71
    }
72
  } while (writeLen < sz);
H
hzcheng 已提交
73

74
  return writeLen;
H
hzcheng 已提交
75 76
}

S
slguan 已提交
77
int httpWriteBuf(struct HttpContext *pContext, const char *buf, int sz) {
78 79
  int writeSz = httpWriteBufByFd(pContext, buf, sz);
  if (writeSz != sz) {
S
slguan 已提交
80
    httpError("context:%p, fd:%d, ip:%s, dataSize:%d, writeSize:%d, failed to send response:\n%s",
81
              pContext, pContext->fd, pContext->ipstr, sz, writeSz, buf);
H
hzcheng 已提交
82
  } else {
S
slguan 已提交
83
    httpTrace("context:%p, fd:%d, ip:%s, dataSize:%d, writeSize:%d, response:\n%s",
84
              pContext, pContext->fd, pContext->ipstr, sz, writeSz, buf);
H
hzcheng 已提交
85 86 87 88 89
  }

  return writeSz;
}

S
slguan 已提交
90 91 92 93 94 95 96 97 98 99 100
int httpWriteBufNoTrace(struct HttpContext *pContext, const char *buf, int sz) {
  int writeSz = httpWriteBufByFd(pContext, buf, sz);
  if (writeSz != sz) {
    httpError("context:%p, fd:%d, ip:%s, dataSize:%d, writeSize:%d, failed to send response",
              pContext, pContext->fd, pContext->ipstr, sz, writeSz);
  }

  return writeSz;
}

int httpWriteJsonBufBody(JsonBuf* buf, bool isTheLast) {
H
hzcheng 已提交
101
  int remain = 0;
S
slguan 已提交
102 103 104
  char sLen[24];
  uint64_t srcLen = (uint64_t) (buf->lst - buf->buf);

H
hzcheng 已提交
105
  if (buf->pContext->fd <= 0) {
S
slguan 已提交
106
    httpTrace("context:%p, fd:%d, ip:%s, write json body error", buf->pContext, buf->pContext->fd, buf->pContext->ipstr);
H
hzcheng 已提交
107 108 109
    buf->pContext->fd = -1;
  }

S
slguan 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123
  /*
   * HTTP servers often use compression to optimize transmission, for example
   * with Content-Encoding: gzip or Content-Encoding: deflate.
   * If both compression and chunked encoding are enabled, then the content stream is first compressed, then chunked;
   * so the chunk encoding itself is not compressed, and the data in each chunk is not compressed individually.
   * The remote endpoint then decodes the stream by concatenating the chunks and uncompressing the result.
   */

  if (buf->pContext->acceptEncoding == HTTP_COMPRESS_IDENTITY) {
    if (buf->lst == buf->buf) {
      httpTrace("context:%p, fd:%d, ip:%s, no data need dump", buf->pContext, buf->pContext->fd, buf->pContext->ipstr);
      return 0;  // there is no data to dump.
    } else {
      int len = sprintf(sLen, "%lx\r\n", srcLen);
L
lihui 已提交
124
      httpTrace("context:%p, fd:%d, ip:%s, write body, chunkSize:%" PRIu64 ", response:\n%s",
S
slguan 已提交
125 126 127 128
                buf->pContext, buf->pContext->fd, buf->pContext->ipstr, srcLen, buf->buf);
      httpWriteBufNoTrace(buf->pContext, sLen, len);
      remain = httpWriteBufNoTrace(buf->pContext, buf->buf, (int) srcLen);
    }
H
hzcheng 已提交
129
  } else {
S
slguan 已提交
130 131 132 133 134 135
    char compressBuf[JSON_BUFFER_SIZE] = {0};
    int32_t compressBufLen = JSON_BUFFER_SIZE;
    int ret = httpGzipCompress(buf->pContext, buf->buf, srcLen, compressBuf, &compressBufLen, isTheLast);
    if (ret == 0) {
      if (compressBufLen > 0) {
        int len = sprintf(sLen, "%x\r\n", compressBufLen);
L
lihui 已提交
136
        httpTrace("context:%p, fd:%d, ip:%s, write body, chunkSize:%" PRIu64 ", compressSize:%d, last:%d, response:\n%s",
S
slguan 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149
                  buf->pContext, buf->pContext->fd, buf->pContext->ipstr, srcLen, compressBufLen, isTheLast, buf->buf);
        httpWriteBufNoTrace(buf->pContext, sLen, len);
        remain = httpWriteBufNoTrace(buf->pContext, (const char *) compressBuf, (int) compressBufLen);
      } else {
        httpTrace("context:%p, fd:%d, ip:%s, last:%d, compress already dumped, response:\n%s",
                buf->pContext, buf->pContext->fd, buf->pContext->ipstr, isTheLast, buf->buf);
        return 0;  // there is no data to dump.
      }
    } else {
      httpError("context:%p, fd:%d, ip:%s, failed to compress data, chunkSize:%d, last:%d, error:%d, response:\n%s",
                buf->pContext, buf->pContext->fd, buf->pContext->ipstr, srcLen, isTheLast, ret, buf->buf);
      return 0;
    }
H
hzcheng 已提交
150 151
  }

S
slguan 已提交
152 153
  httpWriteBufNoTrace(buf->pContext, "\r\n", 2);
  buf->total += (int) (buf->lst - buf->buf);
H
hzcheng 已提交
154
  buf->lst = buf->buf;
S
slguan 已提交
155 156
  memset(buf->buf, 0, (size_t) buf->size);
  return remain;
H
hzcheng 已提交
157 158 159 160 161 162 163 164 165 166
}

void httpWriteJsonBufHead(JsonBuf* buf) {
  if (buf->pContext->fd <= 0) {
    buf->pContext->fd = -1;
  }

  char msg[1024] = {0};
  int  len = -1;

S
slguan 已提交
167
  if (buf->pContext->acceptEncoding == HTTP_COMPRESS_IDENTITY) {
H
hzcheng 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    len = sprintf(msg, httpRespTemplate[HTTP_RESPONSE_CHUNKED_UN_COMPRESS], httpVersionStr[buf->pContext->httpVersion],
                  httpKeepAliveStr[buf->pContext->httpKeepAlive]);
  } else {
    len = sprintf(msg, httpRespTemplate[HTTP_RESPONSE_CHUNKED_COMPRESS], httpVersionStr[buf->pContext->httpVersion],
                  httpKeepAliveStr[buf->pContext->httpKeepAlive]);
  }

  httpWriteBuf(buf->pContext, (const char*)msg, len);
}

void httpWriteJsonBufEnd(JsonBuf* buf) {
  if (buf->pContext->fd <= 0) {
    httpTrace("context:%p, fd:%d, ip:%s, json buf fd is 0", buf->pContext, buf->pContext->fd, buf->pContext->ipstr);
    buf->pContext->fd = -1;
  }

S
slguan 已提交
184 185
  httpWriteJsonBufBody(buf, true);
  httpWriteBufNoTrace(buf->pContext, "0\r\n\r\n", 5);  // end of chunked resp
H
hzcheng 已提交
186 187 188 189 190 191 192 193 194
}

void httpInitJsonBuf(JsonBuf* buf, struct HttpContext* pContext) {
  buf->lst = buf->buf;
  buf->total = 0;
  buf->size = JSON_BUFFER_SIZE;  // option setting
  buf->pContext = pContext;
  memset(buf->lst, 0, JSON_BUFFER_SIZE);

S
slguan 已提交
195 196 197 198 199
  if (pContext->acceptEncoding == HTTP_COMPRESS_GZIP) {
    httpGzipCompressInit(buf->pContext);
  }

  httpTrace("context:%p, fd:%d, ip:%s, json buffer initialized", buf->pContext, buf->pContext->fd, buf->pContext->ipstr);
H
hzcheng 已提交
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
}

void httpJsonItemToken(JsonBuf* buf) {
  char c = *(buf->lst - 1);
  if (c == JsonArrStt || c == JsonObjStt || c == JsonPairTkn || c == JsonItmTkn) {
    return;
  }
  if (buf->lst > buf->buf) httpJsonToken(buf, JsonItmTkn);
}

void httpJsonString(JsonBuf* buf, char* sVal, int len) {
  httpJsonItemToken(buf);
  httpJsonToken(buf, JsonStrStt);
  httpJsonPrint(buf, sVal, len);
  httpJsonToken(buf, JsonStrEnd);
}

void httpJsonOriginString(JsonBuf* buf, char* sVal, int len) {
  httpJsonItemToken(buf);
  httpJsonPrint(buf, sVal, len);
}

void httpJsonStringForTransMean(JsonBuf* buf, char* sVal, int maxLen) {
  httpJsonItemToken(buf);
  httpJsonToken(buf, JsonStrStt);

  if (sVal != NULL) {
    // dispose transferred meaning byte
    char* lastPos = sVal;
    char* curPos = sVal;

    for (int i = 0; i < maxLen; ++i) {
      if (*curPos == 0) {
        break;
      }

      if (*curPos == '\"') {
        httpJsonPrint(buf, lastPos, (int)(curPos - lastPos));
        curPos++;
        lastPos = curPos;
        httpJsonPrint(buf, "\\\"", 2);
      } else if (*curPos == '\\') {
        httpJsonPrint(buf, lastPos, (int)(curPos - lastPos));
        curPos++;
        lastPos = curPos;
        httpJsonPrint(buf, "\\\\", 2);
      } else {
        curPos++;
      }
    }

    if (*lastPos) {
      httpJsonPrint(buf, lastPos, (int)(curPos - lastPos));
    }
  }

  httpJsonToken(buf, JsonStrEnd);
}

void httpJsonInt64(JsonBuf* buf, int64_t num) {
  httpJsonItemToken(buf);
  httpJsonTestBuf(buf, MAX_NUM_STR_SZ);
L
lihui 已提交
262
  buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "%" PRId64, num);
H
hzcheng 已提交
263 264
}

S
slguan 已提交
265 266 267 268 269 270 271
void httpJsonTimestamp(JsonBuf* buf, int64_t t, bool us) {
  char ts[35] = {0};
  struct tm *ptm;
  int precision = 1000;
  if (us) {
    precision = 1000000;
  }
H
hzcheng 已提交
272

S
slguan 已提交
273
  time_t tt = t / precision;
H
hzcheng 已提交
274
  ptm = localtime(&tt);
S
slguan 已提交
275 276 277 278 279 280
  int length = (int) strftime(ts, 35, "%Y-%m-%d %H:%M:%S", ptm);
  if (us) {
    length += snprintf(ts + length, 8, ".%06ld", t % precision);
  } else {
    length += snprintf(ts + length, 5, ".%03ld", t % precision);
  }
H
hzcheng 已提交
281

S
slguan 已提交
282
  httpJsonString(buf, ts, length);
S
slguan 已提交
283 284
}

S
slguan 已提交
285 286
void httpJsonUtcTimestamp(JsonBuf* buf, int64_t t, bool us) {
  char ts[40] = {0};
S
slguan 已提交
287
  struct tm *ptm;
S
slguan 已提交
288 289 290 291 292 293
  int precision = 1000;
  if (us) {
    precision = 1000000;
  }

  time_t tt = t / precision;
S
slguan 已提交
294
  ptm = localtime(&tt);
S
slguan 已提交
295 296 297 298 299 300 301
  int length = (int) strftime(ts, 40, "%Y-%m-%dT%H:%M:%S", ptm);
  if (us) {
    length += snprintf(ts + length, 8, ".%06ld", t % precision);
  } else {
    length += snprintf(ts + length, 5, ".%03ld", t % precision);
  }
  length += (int) strftime(ts + length, 40 - length, "%z", ptm);
S
slguan 已提交
302

S
slguan 已提交
303
  httpJsonString(buf, ts, length);
H
hzcheng 已提交
304 305 306 307 308 309 310 311 312 313 314
}

void httpJsonInt(JsonBuf* buf, int num) {
  httpJsonItemToken(buf);
  httpJsonTestBuf(buf, MAX_NUM_STR_SZ);
  buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "%d", num);
}

void httpJsonFloat(JsonBuf* buf, float num) {
  httpJsonItemToken(buf);
  httpJsonTestBuf(buf, MAX_NUM_STR_SZ);
S
slguan 已提交
315 316 317
  if (isinf(num) || isnan(num)) {
    buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "null");
  } else if (num > 1E10 || num < -1E10) {
H
hzcheng 已提交
318 319 320 321 322 323 324 325 326
    buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "%.5e", num);
  } else {
    buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "%.5f", num);
  }
}

void httpJsonDouble(JsonBuf* buf, double num) {
  httpJsonItemToken(buf);
  httpJsonTestBuf(buf, MAX_NUM_STR_SZ);
S
slguan 已提交
327 328 329
  if (isinf(num) || isnan(num)) {
    buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "null");
  } else if (num > 1E10 || num < -1E10) {
H
hzcheng 已提交
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
    buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "%.9e", num);
  } else {
    buf->lst += snprintf(buf->lst, MAX_NUM_STR_SZ, "%.9f", num);
  }
}

void httpJsonNull(JsonBuf* buf) { httpJsonString(buf, "null", 4); }

void httpJsonBool(JsonBuf* buf, int val) {
  if (val == 0)
    httpJsonPrint(buf, JsonFalseTkn, sizeof(JsonFalseTkn));
  else
    httpJsonPrint(buf, JsonTrueTkn, sizeof(JsonTrueTkn));
}

void httpJsonPairHead(JsonBuf* buf, char* name, int len) {
  httpJsonItemToken(buf);
  httpJsonString(buf, name, len);
  httpJsonToken(buf, JsonPairTkn);
}

void httpJsonPair(JsonBuf* buf, char* name, int nameLen, char* sVal, int valLen) {
  httpJsonPairHead(buf, name, nameLen);
  httpJsonString(buf, sVal, valLen);
}

void httpJsonPairOriginString(JsonBuf* buf, char* name, int nameLen, char* sVal, int valLen) {
  httpJsonPairHead(buf, name, nameLen);
  httpJsonOriginString(buf, sVal, valLen);
}

void httpJsonPairIntVal(JsonBuf* buf, char* name, int nNameLen, int num) {
  httpJsonPairHead(buf, name, nNameLen);
  httpJsonInt(buf, num);
}

void httpJsonPairInt64Val(JsonBuf* buf, char* name, int nNameLen, int64_t num) {
  httpJsonPairHead(buf, name, nNameLen);
  httpJsonInt64(buf, num);
}

void httpJsonPairBoolVal(JsonBuf* buf, char* name, int nNameLen, int num) {
  httpJsonPairHead(buf, name, nNameLen);
  httpJsonBool(buf, num);
}

void httpJsonPairFloatVal(JsonBuf* buf, char* name, int nNameLen, float num) {
  httpJsonPairHead(buf, name, nNameLen);
  httpJsonFloat(buf, num);
}

void httpJsonPairDoubleVal(JsonBuf* buf, char* name, int nNameLen, double num) {
  httpJsonPairHead(buf, name, nNameLen);
  httpJsonDouble(buf, num);
}

void httpJsonPairNullVal(JsonBuf* buf, char* name, int nNameLen) {
  httpJsonPairHead(buf, name, nNameLen);
  httpJsonNull(buf);
}

void httpJsonPairArray(JsonBuf* buf, char* name, int len, httpJsonBuilder fnBuilder, void* dsHandle) {
  httpJsonPairHead(buf, name, len);
  httpJsonArray(buf, fnBuilder, dsHandle);
}

void httpJsonPairObject(JsonBuf* buf, char* name, int len, httpJsonBuilder fnBuilder, void* dsHandle) {
  httpJsonPairHead(buf, name, len);
  httpJsonObject(buf, fnBuilder, dsHandle);
}

void httpJsonObject(JsonBuf* buf, httpJsonBuilder fnBuilder, void* dsHandle) {
  httpJsonItemToken(buf);
  httpJsonToken(buf, JsonObjStt);
  (*fnBuilder)(buf, dsHandle);
  httpJsonToken(buf, JsonObjEnd);
}

void httpJsonArray(JsonBuf* buf, httpJsonBuilder fnBuilder, void* jsonHandle) {
  httpJsonItemToken(buf);
  httpJsonToken(buf, JsonArrStt);
  (*fnBuilder)(buf, jsonHandle);
  httpJsonToken(buf, JsonArrEnd);
}

void httpJsonTestBuf(JsonBuf* buf, int safety) {
  if ((buf->lst - buf->buf + safety) < buf->size) return;
  // buf->slot = *buf->lst;
S
slguan 已提交
418
  httpWriteJsonBufBody(buf, false);
H
hzcheng 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431
}

void httpJsonToken(JsonBuf* buf, char c) {
  httpJsonTestBuf(buf, MAX_NUM_STR_SZ);  // maybe object stack
  *buf->lst++ = c;
}

void httpJsonPrint(JsonBuf* buf, const char* json, int len) {
  if (len == 0 || len >= JSON_BUFFER_SIZE) {
    return;
  }

  if (len > buf->size) {
S
slguan 已提交
432
    httpWriteJsonBufBody(buf, false);
H
hzcheng 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    httpJsonPrint(buf, json, len);
    // buf->slot = json[len - 1];
    return;
  }
  httpJsonTestBuf(buf, len + 2);
  memcpy(buf->lst, json, (size_t)len);
  buf->lst += len;
}

void httpJsonPairStatus(JsonBuf* buf, int code) {
  if (code == 0) {
    httpJsonPair(buf, "status", 6, "succ", 4);
  } else {
    httpJsonPair(buf, "status", 6, "error", 5);
    httpJsonItemToken(buf);
    httpJsonPairIntVal(buf, "code", 4, code);
    if (code >= 0) {
      httpJsonItemToken(buf);
      if (code == TSDB_CODE_DB_NOT_SELECTED) {
        httpJsonPair(buf, "desc", 4, "failed to create database", 23);
      } else if (code == TSDB_CODE_INVALID_TABLE) {
        httpJsonPair(buf, "desc", 4, "failed to create table", 22);
      } else
S
slguan 已提交
456
        httpJsonPair(buf, "desc", 4, (char*)tstrerror(code), (int)strlen(tstrerror(code)));
H
hzcheng 已提交
457 458
    }
  }
S
slguan 已提交
459
}