csum.c 1.93 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * csum.c
 *
 * Copyright (C) 2014 SUSE.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License version 2 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.  See the GNU
 * General Public License for more details.
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
20 21
#include <string.h>
#include <strings.h>
22 23 24 25 26 27 28

#include "csum.h"
#include "debug.h"

unsigned int	digest_len = 0;
char		hash_type[8];

29
static struct csum_module *modules[] = {
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
	&csum_module_murmur3,
	&csum_module_xxhash,
	NULL,
};

struct csum_module *csum_mod = NULL;

int init_csum_module(const char *type)
{
	int ret;
	struct csum_module *m = modules[0];
	int i = 0;

	while (m) {
		if (strcasecmp(type, m->name) == 0)
			break;
		m = modules[++i];
	}

	if (!m)
		return EINVAL;

	csum_mod = m;
	strncpy(hash_type, csum_mod->hash_type, 8);

	ret = csum_mod->ops->init(&digest_len);
	if (ret)
		return ret;

	abort_on(digest_len == 0 || digest_len > DIGEST_LEN_MAX);

	return 0;
}

64
void debug_print_digest_len(FILE *stream, unsigned char *digest, int len)
65 66 67
{
	uint32_t i;

68 69 70
	abort_on(len > digest_len);

	for (i = 0; i < len; i++)
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
		fprintf(stream, "%.2x", digest[i]);
}

void checksum_block(char *buf, int len, unsigned char *digest)
{
	csum_mod->ops->checksum_block(buf, len, digest);
}

struct running_checksum *start_running_checksum(void)
{
	return csum_mod->ops->start_running_checksum();
}

void add_to_running_checksum(struct running_checksum *c,
			     unsigned int len, unsigned char *buf)
{
	csum_mod->ops->add_to_running_checksum(c, len, buf);
}

void finish_running_checksum(struct running_checksum *c, unsigned char *digest)
{
	csum_mod->ops->finish_running_checksum(c, digest);
}