Michal Vasko | 1324b6c | 2018-09-07 11:16:23 +0200 | [diff] [blame] | 1 | /** |
| 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 Vasko | 841d1a9 | 2018-09-07 15:40:31 +0200 | [diff] [blame] | 14 | #define _XOPEN_SOURCE |
Michal Vasko | 1324b6c | 2018-09-07 11:16:23 +0200 | [diff] [blame] | 15 | |
| 16 | #include <stdlib.h> |
Michal Vasko | 841d1a9 | 2018-09-07 15:40:31 +0200 | [diff] [blame] | 17 | #include <stdio.h> |
| 18 | #include <ctype.h> |
| 19 | #include <string.h> |
| 20 | #include <time.h> |
| 21 | |
| 22 | #include "tree_schema.h" |
Michal Vasko | 1324b6c | 2018-09-07 11:16:23 +0200 | [diff] [blame] | 23 | |
| 24 | void * |
| 25 | ly_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 Vasko | 841d1a9 | 2018-09-07 15:40:31 +0200 | [diff] [blame] | 36 | |
| 37 | int |
| 38 | lysp_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 | |
| 75 | error: |
Michal Vasko | 2b79254 | 2018-09-07 16:00:33 +0200 | [diff] [blame^] | 76 | fprintf(stderr, "Invalid date format \"%.*s\".\n", date_len, date); |
Michal Vasko | 841d1a9 | 2018-09-07 15:40:31 +0200 | [diff] [blame] | 77 | return -1; |
| 78 | } |