blob: fb985234756befbcf432a6aec0db42ed7f819bab [file] [log] [blame]
Michal Vasko1324b6c2018-09-07 11:16:23 +02001/**
2 * @file common.c
3 * @author Michal Vasko <mvasko@cesnet.cz>
4 * @brief common internal definitions for libyang
5 *
6 * Copyright (c) 2018 CESNET, z.s.p.o.
7 *
8 * This source code is licensed under BSD 3-Clause License (the "License").
9 * You may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * https://opensource.org/licenses/BSD-3-Clause
13 */
Michal Vasko841d1a92018-09-07 15:40:31 +020014#define _XOPEN_SOURCE
Michal Vasko1324b6c2018-09-07 11:16:23 +020015
16#include <stdlib.h>
Michal Vasko841d1a92018-09-07 15:40:31 +020017#include <stdio.h>
18#include <ctype.h>
19#include <string.h>
20#include <time.h>
21
22#include "tree_schema.h"
Michal Vasko1324b6c2018-09-07 11:16:23 +020023
24void *
25ly_realloc(void *ptr, size_t size)
26{
27 void *new_mem;
28
29 new_mem = realloc(ptr, size);
30 if (!new_mem) {
31 free(ptr);
32 }
33
34 return new_mem;
35}
Michal Vasko841d1a92018-09-07 15:40:31 +020036
37int
38lysp_check_date(struct ly_ctx *ctx, const char *date, int date_len)
39{
40 int i;
41 struct tm tm, tm_;
42 char *r;
43
44 if (date_len != LY_REV_SIZE - 1) {
45 goto error;
46 }
47
48 /* check format */
49 for (i = 0; i < date_len; i++) {
50 if (i == 4 || i == 7) {
51 if (date[i] != '-') {
52 goto error;
53 }
54 } else if (!isdigit(date[i])) {
55 goto error;
56 }
57 }
58
59 /* check content, e.g. 2018-02-31 */
60 memset(&tm, 0, sizeof tm);
61 r = strptime(date, "%Y-%m-%d", &tm);
62 if (!r || r != &date[LY_REV_SIZE - 1]) {
63 goto error;
64 }
65 memcpy(&tm_, &tm, sizeof tm);
66 mktime(&tm_); /* mktime modifies tm_ if it refers invalid date */
67 if (tm.tm_mday != tm_.tm_mday) { /* e.g 2018-02-29 -> 2018-03-01 */
68 /* checking days is enough, since other errors
69 * have been checked by strptime() */
70 goto error;
71 }
72
73 return 0;
74
75error:
Michal Vasko2b792542018-09-07 16:00:33 +020076 fprintf(stderr, "Invalid date format \"%.*s\".\n", date_len, date);
Michal Vasko841d1a92018-09-07 15:40:31 +020077 return -1;
78}