/**
 * Copyright 2020 German Tischler-Höhle
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **/
#if ! defined(LIBSECRECY_YARROW_HPP)
#define LIBSECRECY_YARROW_HPP

#include <libsecrecy/LockedMemory.hpp>
#include <sys/random.h>
#include <nettle/yarrow.h>

namespace libsecrecy
{
	struct Yarrow
	{
		private:
		LockedMemory<yarrow256_ctx> lctx;
		yarrow256_ctx * ctx;

		Yarrow & operator=(Yarrow const &);
		Yarrow(Yarrow const &);

		public:
		Yarrow() : lctx(1), ctx(lctx.get())
		{
			yarrow256_init(ctx,0,nullptr);

			LockedMemory<uint8_t> pseed(YARROW256_SEED_FILE_SIZE);

			uint8_t * p = pseed.get();
			std::size_t toread = YARROW256_SEED_FILE_SIZE;

			while ( toread )
			{
				::ssize_t const r = getrandom(p,toread,GRND_RANDOM);

				if ( r < 0 )
				{
					int const error = errno;

					switch ( error )
					{
						case EAGAIN:
						case EINTR:
							break;
						default:
						{
							std::ostringstream ostr;
							ostr << "libsecrecy::Yarrow: getrandom call failed: " << strerror(errno) << std::endl;
							throw std::runtime_error(ostr.str());
						}
					}
				}

				toread -= r;
				p += r;
			}

			p = pseed.get();

			yarrow256_seed(ctx,YARROW256_SEED_FILE_SIZE,p);
			yarrow256_random(ctx,YARROW256_SEED_FILE_SIZE,p);
		}

		void operator()(uint8_t * dst, ::std::size_t const l)
		{
			yarrow256_random(ctx,l,dst);
		}
	};
}
#endif
