/*
 * Copyright (c) 2004, 2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_RCSID("@(#)$Id: sm_mkdir.c,v 1.7 2007/10/25 14:42:30 ca Exp $")

#include "sm/assert.h"
#include "sm/error.h"
#include "sm/stat.h"
#include "sm/param.h"
#include "sm/string.h"

/*
**  SM_MKDIR -- create directory (mkdir -p)
**
**	Parameters:
**		path -- directory to create
**		mode -- permissions
**
**	Returns:
**		usual sm_error code
*/

sm_ret_T
sm_mkdir(const char *path, mode_t mode)
{
	char *d, *h;
	int r;
	size_t l;
	struct stat sb;
	char mypath[MAXPATHLEN];

	SM_REQUIRE(path != NULL);
	SM_REQUIRE(*path != '\0');

	/* make a copy because the path might be modified */
	l = strlcpy(mypath, path, sizeof(mypath));
	if (l >= sizeof(mypath))
		return sm_err_perm(SM_E_2BIG);	/* better error code?? */

	h = mypath + 1;
	r = 0;
	while ((d = strchr(h, '/')) != NULL)
	{
		*d = '\0';
		r = stat(mypath, &sb);
		if (r < 0)
			r = mkdir(mypath, mode);
		*d = '/';
		if (r != 0)
			break;
		h = d + 1;
	}
	if (r == 0)
		r = mkdir(mypath, mode);
	return (r == 0) ? SM_SUCCESS : sm_err_perm(errno);
}


syntax highlighted by Code2HTML, v. 0.9.1