/*
 *  Unix SMB/CIFS implementation.
 *  RPC Pipe client / server routines for Dfs
 *  Copyright (C) Shirish Kalele	2000.
 *  Copyright (C) Jeremy Allison	2001-2007.
 *  Copyright (C) Jelmer Vernooij	2005-2006.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  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.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

/* This is the implementation of the dfs pipe. */

#include "includes.h"
#include "ntdomain.h"
#include "librpc/rpc/dcesrv_core.h"
#include "librpc/gen_ndr/ndr_dfs.h"
#include "librpc/gen_ndr/ndr_dfs_scompat.h"
#include "msdfs.h"
#include "smbd/smbd.h"
#include "smbd/globals.h"
#include "smbd/dir.h"
#include "auth.h"
#include "source3/lib/global_contexts.h"
#include "source3/lib/substitute.h"

#undef DBGC_CLASS
#define DBGC_CLASS DBGC_MSDFS

/*********************************************************************
 Creates a junction structure from a DFS pathname
**********************************************************************/

static bool create_junction(TALLOC_CTX *ctx,
			    const char *dfs_path,
			    struct junction_map *jucn)
{
	const struct loadparm_substitution
		*lp_sub = loadparm_s3_global_substitution();
	int snum;
	char *servicename = NULL;
	char *reqpath = NULL;
	NTSTATUS status;

	status = parse_dfs_path_strict(
		ctx, dfs_path, NULL, &servicename, &reqpath);
	if (!NT_STATUS_IS_OK(status)) {
		return False;
	}

	/* Check for a non-DFS share */
	snum = lp_servicenumber(servicename);

	if (snum < 0 || !lp_msdfs_root(snum)) {
		DEBUG(4,("create_junction: %s is not an msdfs root.\n",
			servicename));
		return False;
	}

	/* Junction create paths are always non-POSIX. */
	status = check_path_syntax(reqpath, false);
	if (!NT_STATUS_IS_OK(status)) {
		return false;
	}

	jucn->service_name = talloc_strdup(ctx, servicename);
	jucn->volume_name = talloc_strdup(ctx, reqpath);
	jucn->comment = lp_comment(ctx, lp_sub, snum);

	if (!jucn->service_name || !jucn->volume_name || !jucn->comment) {
		return False;
	}
	return True;
}

/**********************************************************************
 Forms a valid Unix pathname from the junction
 **********************************************************************/

static bool junction_to_local_path_tos(const struct junction_map *jucn,
				       struct auth_session_info *session_info,
				       char **pp_path_out,
				       connection_struct **conn_out)
{
	const struct loadparm_substitution
		*lp_sub = loadparm_s3_global_substitution();
	struct conn_wrap *w = NULL;
	int snum;
	char *path_out = NULL;
	NTSTATUS status;

	snum = lp_servicenumber(jucn->service_name);
	if (snum < 0) {
		return False;
	}
	status = create_conn_struct_chdir(talloc_tos(),
					  global_messaging_context(),
					  snum,
					  lp_path(talloc_tos(), lp_sub, snum),
					  session_info,
					  &w);
	if (!NT_STATUS_IS_OK(status)) {
		return False;
	}

	path_out = talloc_asprintf(w,
				   "%s/%s",
				   lp_path(talloc_tos(), lp_sub, snum),
				   jucn->volume_name);
	if (path_out == NULL) {
		TALLOC_FREE(w);
		return False;
	}
	*pp_path_out = path_out;
	*conn_out = conn_wrap_connection(w);
	return True;
}

static bool create_msdfs_link(const struct junction_map *jucn,
			      struct auth_session_info *session_info)
{
	TALLOC_CTX *frame = talloc_stackframe();
	char *path = NULL;
	connection_struct *conn;
	struct smb_filename *smb_fname = NULL;
	struct smb_filename *parent_fname = NULL;
	struct smb_filename *at_fname = NULL;
	bool ok;
	NTSTATUS status;
	bool ret = false;

	ok = junction_to_local_path_tos(jucn, session_info, &path, &conn);
	if (!ok) {
		goto out;
	}

	if (!CAN_WRITE(conn)) {
		const struct loadparm_substitution
			*lp_sub = loadparm_s3_global_substitution();
		int snum = lp_servicenumber(jucn->service_name);

		DBG_WARNING("Can't create DFS entry on read-only share %s\n",
			    lp_servicename(frame, lp_sub, snum));
		goto out;
	}

	smb_fname = cp_smb_basename(frame, path);
	if (smb_fname == NULL) {
		goto out;
	}

	status = parent_pathref(
		frame, conn->cwd_fsp, smb_fname, &parent_fname, &at_fname);
	if (!NT_STATUS_IS_OK(status)) {
		goto out;
	}

	status = SMB_VFS_CREATE_DFS_PATHAT(conn,
					   parent_fname->fsp,
					   at_fname,
					   jucn->referral_list,
					   jucn->referral_count);
	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_COLLISION)) {
			int retval = SMB_VFS_UNLINKAT(conn,
						      parent_fname->fsp,
						      at_fname,
						      0);
			if (retval != 0) {
				goto out;
			}
		}
		status = SMB_VFS_CREATE_DFS_PATHAT(conn,
						   parent_fname->fsp,
						   at_fname,
						   jucn->referral_list,
						   jucn->referral_count);
		if (!NT_STATUS_IS_OK(status)) {
			DBG_WARNING("SMB_VFS_CREATE_DFS_PATHAT failed "
				    "%s - Error: %s\n",
				    path,
				    nt_errstr(status));
			goto out;
		}
	}

	ret = true;

out:
	TALLOC_FREE(frame);
	return ret;
}

static bool remove_msdfs_link(const struct junction_map *jucn,
			      struct auth_session_info *session_info)
{
	TALLOC_CTX *frame = talloc_stackframe();
	char *path = NULL;
	connection_struct *conn;
	bool ret = False;
	struct smb_filename *smb_fname;
	struct smb_filename *parent_fname = NULL;
	struct smb_filename *at_fname = NULL;
	NTSTATUS status;
	bool ok;
	int retval;

	ok = junction_to_local_path_tos(jucn, session_info, &path, &conn);
	if (!ok) {
		TALLOC_FREE(frame);
		return false;
	}

	if (!CAN_WRITE(conn)) {
		const struct loadparm_substitution
			*lp_sub = loadparm_s3_global_substitution();
		int snum = lp_servicenumber(jucn->service_name);

		DBG_WARNING("Can't remove DFS entry on read-only share %s\n",
			    lp_servicename(frame, lp_sub, snum));
		goto fail;
	}

	smb_fname = cp_smb_basename(frame, path);
	if (smb_fname == NULL) {
		TALLOC_FREE(frame);
		errno = ENOMEM;
		goto fail;
	}

	status = parent_pathref(
		frame, conn->cwd_fsp, smb_fname, &parent_fname, &at_fname);
	if (!NT_STATUS_IS_OK(status)) {
		errno = map_errno_from_nt_status(status);
		goto fail;
	}

	retval = SMB_VFS_UNLINKAT(conn, parent_fname->fsp, at_fname, 0);
	if (retval == 0) {
		ret = True;
	}

fail:
	TALLOC_FREE(frame);
	return ret;
}

/*********************************************************************
 Return the number of DFS links at the root of this share.
*********************************************************************/

static size_t count_dfs_links(TALLOC_CTX *ctx,
			      struct auth_session_info *session_info,
			      int snum)
{
	TALLOC_CTX *frame = talloc_stackframe();
	const struct loadparm_substitution
		*lp_sub = loadparm_s3_global_substitution();
	size_t cnt = 0;
	const char *dname = NULL;
	char *talloced = NULL;
	const char *connect_path = lp_path(frame, lp_sub, snum);
	const char *msdfs_proxy = lp_msdfs_proxy(frame, lp_sub, snum);
	struct conn_wrap *w = NULL;
	connection_struct *conn = NULL;
	NTSTATUS status;
	struct smb_filename *smb_fname = NULL;
	struct smb_Dir *dir_hnd = NULL;

	if (*connect_path == '\0') {
		TALLOC_FREE(frame);
		return 0;
	}

	/*
	 * Fake up a connection struct for the VFS layer.
	 */

	status = create_conn_struct_chdir(talloc_tos(),
					  global_messaging_context(),
					  snum,
					  connect_path,
					  session_info,
					  &w);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(3, ("create_conn_struct failed: %s\n",
			  nt_errstr(status)));
		TALLOC_FREE(frame);
		return 0;
	}
	conn = conn_wrap_connection(w);

	/* Count a link for the msdfs root - convention */
	cnt = 1;

	/* No more links if this is an msdfs proxy. */
	if (*msdfs_proxy != '\0') {
		goto out;
	}

	smb_fname = cp_smb_basename(frame, ".");
	if (smb_fname == NULL) {
		goto out;
	}

	/* Now enumerate all dfs links */
	status = OpenDir(frame, conn, smb_fname, NULL, 0, &dir_hnd);
	if (!NT_STATUS_IS_OK(status)) {
		errno = map_errno_from_nt_status(status);
		goto out;
	}

	while ((dname = ReadDirName(dir_hnd, &talloced)) != NULL) {
		struct smb_filename *smb_dname = cp_smb_basename(frame, dname);
		if (smb_dname == NULL) {
			goto out;
		}
		if (is_msdfs_link(dir_hnd_fetch_fsp(dir_hnd), smb_dname)) {
			if (cnt + 1 < cnt) {
				cnt = 0;
				goto out;
			}
			cnt++;
		}
		TALLOC_FREE(talloced);
		TALLOC_FREE(smb_dname);
	}

out:
	TALLOC_FREE(frame);
	return cnt;
}

/*********************************************************************
*********************************************************************/

static int form_junctions(TALLOC_CTX *ctx,
			  struct auth_session_info *session_info,
			  int snum,
			  struct junction_map *jucn,
			  size_t jn_remain)
{
	TALLOC_CTX *frame = talloc_stackframe();
	const struct loadparm_substitution
		*lp_sub = loadparm_s3_global_substitution();
	size_t cnt = 0;
	const char *dname = NULL;
	char *talloced = NULL;
	const char *connect_path = lp_path(frame, lp_sub, snum);
	char *service_name = lp_servicename(frame, lp_sub, snum);
	const char *msdfs_proxy = lp_msdfs_proxy(frame, lp_sub, snum);
	struct conn_wrap *w = NULL;
	connection_struct *conn = NULL;
	struct referral *ref = NULL;
	struct smb_filename *smb_fname = NULL;
	struct smb_Dir *dir_hnd = NULL;
	NTSTATUS status;

	if (jn_remain == 0) {
		TALLOC_FREE(frame);
		return 0;
	}

	if (*connect_path == '\0') {
		TALLOC_FREE(frame);
		return 0;
	}

	/*
	 * Fake up a connection struct for the VFS layer.
	 */

	status = create_conn_struct_chdir(talloc_tos(),
					  global_messaging_context(),
					  snum,
					  connect_path,
					  session_info,
					  &w);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(3, ("create_conn_struct failed: %s\n",
			  nt_errstr(status)));
		TALLOC_FREE(frame);
		return 0;
	}
	conn = conn_wrap_connection(w);

	/* form a junction for the msdfs root - convention
	   DO NOT REMOVE THIS: NT clients will not work with us
	   if this is not present
	*/
	jucn[cnt].service_name = talloc_strdup(ctx, service_name);
	jucn[cnt].volume_name = talloc_strdup(ctx, "");
	if (!jucn[cnt].service_name || !jucn[cnt].volume_name) {
		goto out;
	}
	jucn[cnt].comment = "";
	jucn[cnt].referral_count = 1;

	ref = jucn[cnt].referral_list = talloc_zero(ctx, struct referral);
	if (jucn[cnt].referral_list == NULL) {
		goto out;
	}

	ref->proximity = 0;
	ref->ttl = REFERRAL_TTL;
	if (*msdfs_proxy != '\0') {
		ref->alternate_path = talloc_strdup(ctx, msdfs_proxy);
	} else {
		ref->alternate_path = talloc_asprintf(ctx,
						      "\\\\%s\\%s",
						      get_local_machine_name(),
						      service_name);
	}

	if (!ref->alternate_path) {
		goto out;
	}
	cnt++;

	/* Don't enumerate if we're an msdfs proxy. */
	if (*msdfs_proxy != '\0') {
		goto out;
	}

	smb_fname = cp_smb_basename(frame, ".");
	if (smb_fname == NULL) {
		goto out;
	}

	/* Now enumerate all dfs links */
	status = OpenDir(frame, conn, smb_fname, NULL, 0, &dir_hnd);
	if (!NT_STATUS_IS_OK(status)) {
		errno = map_errno_from_nt_status(status);
		goto out;
	}

	while ((dname = ReadDirName(dir_hnd, &talloced)) != NULL) {
		struct smb_filename *smb_dname = NULL;

		if (cnt >= jn_remain) {
			DEBUG(2, ("form_junctions: ran out of MSDFS "
				"junction slots\n"));
			TALLOC_FREE(talloced);
			goto out;
		}
		smb_dname = cp_smb_basename(talloc_tos(), dname);
		if (smb_dname == NULL) {
			TALLOC_FREE(talloced);
			goto out;
		}

		status = SMB_VFS_READ_DFS_PATHAT(conn,
						 ctx,
						 conn->cwd_fsp,
						 smb_dname,
						 &jucn[cnt].referral_list,
						 &jucn[cnt].referral_count);

		if (NT_STATUS_IS_OK(status)) {
			jucn[cnt].service_name = talloc_strdup(ctx,
							       service_name);
			jucn[cnt].volume_name = talloc_strdup(ctx, dname);
			if (!jucn[cnt].service_name || !jucn[cnt].volume_name)
			{
				TALLOC_FREE(talloced);
				goto out;
			}
			jucn[cnt].comment = "";
			cnt++;
		}
		TALLOC_FREE(talloced);
		TALLOC_FREE(smb_dname);
	}

out:
	TALLOC_FREE(frame);
	return cnt;
}

static struct junction_map *enum_msdfs_links(
	TALLOC_CTX *ctx,
	struct auth_session_info *session_info,
	size_t *p_num_jn)
{
	struct junction_map *jn = NULL;
	int i = 0;
	size_t jn_count = 0;
	int sharecount = 0;

	*p_num_jn = 0;
	if (!lp_host_msdfs()) {
		return NULL;
	}

	/* Ensure all the usershares are loaded. */
	become_root();
	load_registry_shares();
	sharecount = load_usershare_shares(NULL, connections_snum_used);
	unbecome_root();

	for (i = 0; i < sharecount; i++) {
		if (lp_msdfs_root(i)) {
			jn_count += count_dfs_links(ctx, session_info, i);
		}
	}
	if (jn_count == 0) {
		return NULL;
	}
	jn = talloc_array(ctx, struct junction_map, jn_count);
	if (!jn) {
		return NULL;
	}
	for (i = 0; i < sharecount; i++) {
		if (*p_num_jn >= jn_count) {
			break;
		}
		if (lp_msdfs_root(i)) {
			*p_num_jn += form_junctions(ctx,
						    session_info,
						    i,
						    &jn[*p_num_jn],
						    jn_count - *p_num_jn);
		}
	}
	return jn;
}

/* This function does not return a WERROR or NTSTATUS code but rather 1 if
   dfs exists, or 0 otherwise. */

void _dfs_GetManagerVersion(struct pipes_struct *p, struct dfs_GetManagerVersion *r)
{
	if (lp_host_msdfs()) {
		*r->out.version = DFS_MANAGER_VERSION_NT4;
	} else {
		*r->out.version = (enum dfs_ManagerVersion)0;
	}
}

WERROR _dfs_Add(struct pipes_struct *p, struct dfs_Add *r)
{
	struct dcesrv_call_state *dce_call = p->dce_call;
	struct dcesrv_connection *dcesrv_conn = dce_call->conn;
	const struct tsocket_address *local_address =
		dcesrv_connection_get_local_address(dcesrv_conn);
	const struct tsocket_address *remote_address =
		dcesrv_connection_get_remote_address(dcesrv_conn);
	struct auth_session_info *session_info =
		dcesrv_call_session_info(dce_call);
	struct junction_map *jn = NULL;
	bool self_ref = False;
	size_t consumedcnt = 0;
	char *altpath = NULL;
	NTSTATUS status;
	TALLOC_CTX *ctx = talloc_tos();
	const char *pathnamep = r->in.path;

	if (session_info->unix_token->uid != sec_initial_uid()) {
		DBG_DEBUG("uid != 0. Access denied.\n");
		return WERR_ACCESS_DENIED;
	}

	jn = talloc_zero(ctx, struct junction_map);
	if (!jn) {
		return WERR_NOT_ENOUGH_MEMORY;
	}

	DBG_INFO("Request to add %s -> %s\\%s.\n",
		 r->in.path,
		 r->in.server,
		 r->in.share);

	altpath = talloc_asprintf(ctx, "%s\\%s",
			r->in.server,
			r->in.share);
	if (!altpath) {
		return WERR_NOT_ENOUGH_MEMORY;
	}

	while (IS_DIRECTORY_SEP(pathnamep[0]) &&
	       IS_DIRECTORY_SEP(pathnamep[1])) {
		pathnamep++;
	}

	/* The following call can change the cwd. */
	status = get_referred_path(ctx,
				   session_info,
				   pathnamep,
				   remote_address,
				   local_address,
				   jn, &consumedcnt, &self_ref);
	if(!NT_STATUS_IS_OK(status) &&
	   !NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_PATH_NOT_FOUND))
	{
		return ntstatus_to_werror(status);
	}

	jn->referral_count += 1;
	if (jn->referral_count < 1) {
		return WERR_NOT_ENOUGH_MEMORY;
	}

	jn->referral_list = talloc_realloc(ctx,
					   jn->referral_list,
					   struct referral,
					   jn->referral_count);
	if(jn->referral_list == NULL) {
		DBG_ERR("talloc failed for referral list!\n");
		return WERR_NERR_DFSINTERNALERROR;
	}

	jn->referral_list[jn->referral_count-1].proximity = 0;
	jn->referral_list[jn->referral_count-1].ttl = REFERRAL_TTL;
	jn->referral_list[jn->referral_count-1].alternate_path = altpath;

	if (!create_msdfs_link(jn, session_info)) {
		return WERR_NERR_DFSCANTCREATEJUNCTIONPOINT;
	}

	return WERR_OK;
}

WERROR _dfs_Remove(struct pipes_struct *p, struct dfs_Remove *r)
{
	struct dcesrv_call_state *dce_call = p->dce_call;
	struct dcesrv_connection *dcesrv_conn = dce_call->conn;
	const struct tsocket_address *local_address =
		dcesrv_connection_get_local_address(dcesrv_conn);
	const struct tsocket_address *remote_address =
		dcesrv_connection_get_remote_address(dcesrv_conn);
	struct auth_session_info *session_info =
		dcesrv_call_session_info(dce_call);
	struct junction_map *jn = NULL;
	bool self_ref = False;
	size_t consumedcnt = 0;
	bool found = False;
	TALLOC_CTX *ctx = talloc_tos();
	char *altpath = NULL;
	NTSTATUS status;
	const char *pathnamep = r->in.dfs_entry_path;

	if (session_info->unix_token->uid != sec_initial_uid()) {
		DBG_DEBUG("uid != 0. Access denied.\n");
		return WERR_ACCESS_DENIED;
	}

	jn = talloc_zero(ctx, struct junction_map);
	if (!jn) {
		return WERR_NOT_ENOUGH_MEMORY;
	}

	if (r->in.servername && r->in.sharename) {
		altpath = talloc_asprintf_strlower_m(ctx,
						     "%s\\%s",
						     r->in.servername,
						     r->in.sharename);
		if (!altpath) {
			return WERR_NOT_ENOUGH_MEMORY;
		}
		DBG_INFO("Request to remove %s -> %s\\%s.\n",
			 r->in.dfs_entry_path,
			 r->in.servername,
			 r->in.sharename);
	}

	while (IS_DIRECTORY_SEP(pathnamep[0]) &&
	       IS_DIRECTORY_SEP(pathnamep[1])) {
		pathnamep++;
	}

	status = get_referred_path(ctx,
				   session_info,
				   pathnamep,
				   remote_address,
				   local_address,
				   jn, &consumedcnt, &self_ref);
	if(!NT_STATUS_IS_OK(status)) {
		return WERR_NERR_DFSNOSUCHVOLUME;
	}

	/* if no server-share pair given, remove the msdfs link completely */
	if(!r->in.servername && !r->in.sharename) {
		if(!remove_msdfs_link(jn, session_info)) {
			return WERR_NERR_DFSNOSUCHVOLUME;
		}
	} else {
		size_t i = 0;
		/* compare each referral in the list with the one to remove */
		DBG_DEBUG("altpath: .%s. refcnt: %zu\n",
				altpath,
				jn->referral_count);
		for(i=0;i<jn->referral_count;i++) {
			char *refpath = talloc_strdup(ctx,
					jn->referral_list[i].alternate_path);
			if (!refpath) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
			trim_char(refpath, '\\', '\\');
			DBG_DEBUG("refpath: .%s.\n", refpath);
			if(strequal(refpath, altpath)) {
				*(jn->referral_list[i].alternate_path)='\0';
				DBG_DEBUG("Removal request matches "
					  "referral %s\n",
					  refpath);
				found = True;
			}
		}

		if(!found) {
			return WERR_NERR_DFSNOSUCHSHARE;
		}

		/* Only one referral, remove it */
		if(jn->referral_count == 1) {
			if(!remove_msdfs_link(jn, session_info)) {
				return WERR_NERR_DFSNOSUCHVOLUME;
			}
		} else {
			if(!create_msdfs_link(jn, session_info)) {
				return WERR_NERR_DFSCANTCREATEJUNCTIONPOINT;
			}
		}
	}

	return WERR_OK;
}

static bool init_reply_dfs_info_1(TALLOC_CTX *mem_ctx, struct junction_map* j,struct dfs_Info1* dfs1)
{
	dfs1->path = talloc_asprintf(mem_ctx,
				"\\\\%s\\%s\\%s", lp_netbios_name(),
				j->service_name, j->volume_name);
	if (dfs1->path == NULL)
		return False;

	DBG_INFO("initing entrypath: %s\n", dfs1->path);
	return True;
}

static bool init_reply_dfs_info_2(TALLOC_CTX *mem_ctx, struct junction_map* j, struct dfs_Info2* dfs2)
{
	dfs2->path = talloc_asprintf(mem_ctx,
			"\\\\%s\\%s\\%s", lp_netbios_name(), j->service_name, j->volume_name);
	if (dfs2->path == NULL)
		return False;
	dfs2->comment = talloc_strdup(mem_ctx, j->comment);
	dfs2->state = 1; /* set up state of dfs junction as OK */
	dfs2->num_stores = j->referral_count;
	return True;
}

static bool init_reply_dfs_info_3(TALLOC_CTX *mem_ctx, struct junction_map* j, struct dfs_Info3* dfs3)
{
	size_t ii;
	if (j->volume_name[0] == '\0')
		dfs3->path = talloc_asprintf(mem_ctx, "\\\\%s\\%s",
			lp_netbios_name(), j->service_name);
	else
		dfs3->path = talloc_asprintf(mem_ctx, "\\\\%s\\%s\\%s", lp_netbios_name(),
			j->service_name, j->volume_name);

	if (dfs3->path == NULL)
		return False;

	dfs3->comment = talloc_strdup(mem_ctx, j->comment);
	dfs3->state = 1;
	dfs3->num_stores = j->referral_count;

	/* also enumerate the stores */
	if (j->referral_count) {
		dfs3->stores = talloc_array(mem_ctx, struct dfs_StorageInfo, j->referral_count);
		if (!dfs3->stores)
			return False;
		memset(dfs3->stores, '\0', j->referral_count * sizeof(struct dfs_StorageInfo));
	} else {
		dfs3->stores = NULL;
	}

	for(ii=0;ii<j->referral_count;ii++) {
		char* p;
		char *path = NULL;
		struct dfs_StorageInfo* stor = &(dfs3->stores[ii]);
		struct referral* ref = &(j->referral_list[ii]);

		path = talloc_strdup(mem_ctx, ref->alternate_path);
		if (!path) {
			return False;
		}
		trim_char(path,'\\','\0');
		p = strrchr_m(path,'\\');
		if(p==NULL) {
			DBG_INFO("invalid path: no \\ found in %s\n", path);
			continue;
		}
		*p = '\0';
		DBG_INFO("storage %zu: %s.%s\n",ii,path,p+1);
		stor->state = 2; /* set all stores as ONLINE */
		stor->server = talloc_strdup(mem_ctx, path);
		stor->share = talloc_strdup(mem_ctx, p+1);
	}
	return True;
}

static bool init_reply_dfs_info_100(TALLOC_CTX *mem_ctx, struct junction_map* j, struct dfs_Info100* dfs100)
{
	dfs100->comment = talloc_strdup(mem_ctx, j->comment);
	return True;
}

WERROR _dfs_Enum(struct pipes_struct *p, struct dfs_Enum *r)
{
	struct dcesrv_call_state *dce_call = p->dce_call;
	struct auth_session_info *session_info =
		dcesrv_call_session_info(dce_call);
	struct junction_map *jn = NULL;
	size_t num_jn = 0;
	size_t i;
	TALLOC_CTX *ctx = talloc_tos();

	jn = enum_msdfs_links(ctx, session_info, &num_jn);
	if (!jn || num_jn == 0) {
		num_jn = 0;
		jn = NULL;
	}

	DBG_INFO("%zu junctions found in Dfs, doing level %" PRIu32 "\n",
		 num_jn,
		 r->in.level);

	*r->out.total = num_jn;

	/* Create the return array */
	switch (r->in.level) {
	case 1:
		if (num_jn) {
			if ((r->out.info->e.info1->s = talloc_array(ctx, struct dfs_Info1, num_jn)) == NULL) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
		} else {
			r->out.info->e.info1->s = NULL;
		}
		r->out.info->e.info1->count = num_jn;
		break;
	case 2:
		if (num_jn) {
			if ((r->out.info->e.info2->s = talloc_array(ctx, struct dfs_Info2, num_jn)) == NULL) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
		} else {
			r->out.info->e.info2->s = NULL;
		}
		r->out.info->e.info2->count = num_jn;
		break;
	case 3:
		if (num_jn) {
			if ((r->out.info->e.info3->s = talloc_array(ctx, struct dfs_Info3, num_jn)) == NULL) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
		} else {
			r->out.info->e.info3->s = NULL;
		}
		r->out.info->e.info3->count = num_jn;
		break;
	default:
		return WERR_INVALID_PARAMETER;
	}

	for (i = 0; i < num_jn; i++) {
		switch (r->in.level) {
		case 1:
			init_reply_dfs_info_1(ctx, &jn[i], &r->out.info->e.info1->s[i]);
			break;
		case 2:
			init_reply_dfs_info_2(ctx, &jn[i], &r->out.info->e.info2->s[i]);
			break;
		case 3:
			init_reply_dfs_info_3(ctx, &jn[i], &r->out.info->e.info3->s[i]);
			break;
		default:
			return WERR_INVALID_PARAMETER;
		}
	}

	return WERR_OK;
}

WERROR _dfs_GetInfo(struct pipes_struct *p, struct dfs_GetInfo *r)
{
	struct dcesrv_call_state *dce_call = p->dce_call;
	struct dcesrv_connection *dcesrv_conn = dce_call->conn;
	const struct tsocket_address *local_address =
		dcesrv_connection_get_local_address(dcesrv_conn);
	const struct tsocket_address *remote_address =
		dcesrv_connection_get_remote_address(dcesrv_conn);
	struct auth_session_info *session_info =
		dcesrv_call_session_info(dce_call);
	size_t consumedcnt = 0;
	struct junction_map *jn = NULL;
	bool self_ref = False;
	TALLOC_CTX *ctx = talloc_tos();
	bool ret;
	NTSTATUS status;
	const char *pathnamep = r->in.dfs_entry_path;

	jn = talloc_zero(ctx, struct junction_map);
	if (!jn) {
		return WERR_NOT_ENOUGH_MEMORY;
	}

	while (IS_DIRECTORY_SEP(pathnamep[0]) &&
	       IS_DIRECTORY_SEP(pathnamep[1])) {
		pathnamep++;
	}

	ret = create_junction(ctx, pathnamep, jn);
	if (!ret) {
		return WERR_NERR_DFSNOSUCHSERVER;
	}

	/* The following call can change the cwd. */
	status = get_referred_path(ctx,
				   session_info,
				   pathnamep,
				   remote_address,
				   local_address,
				   jn, &consumedcnt, &self_ref);
	if(!NT_STATUS_IS_OK(status) || consumedcnt < strlen(pathnamep)) {
		return WERR_NERR_DFSNOSUCHVOLUME;
	}

	switch (r->in.level) {
		case 1:
			r->out.info->info1 = talloc_zero(ctx,struct dfs_Info1);
			if (!r->out.info->info1) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
			ret = init_reply_dfs_info_1(ctx, jn, r->out.info->info1);
			break;
		case 2:
			r->out.info->info2 = talloc_zero(ctx,struct dfs_Info2);
			if (!r->out.info->info2) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
			ret = init_reply_dfs_info_2(ctx, jn, r->out.info->info2);
			break;
		case 3:
			r->out.info->info3 = talloc_zero(ctx,struct dfs_Info3);
			if (!r->out.info->info3) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
			ret = init_reply_dfs_info_3(ctx, jn, r->out.info->info3);
			break;
		case 100:
			r->out.info->info100 = talloc_zero(ctx,struct dfs_Info100);
			if (!r->out.info->info100) {
				return WERR_NOT_ENOUGH_MEMORY;
			}
			ret = init_reply_dfs_info_100(ctx, jn, r->out.info->info100);
			break;
		default:
			r->out.info->info1 = NULL;
			return WERR_INVALID_PARAMETER;
	}

	if (!ret)
		return WERR_INVALID_PARAMETER;

	return WERR_OK;
}

WERROR _dfs_SetInfo(struct pipes_struct *p, struct dfs_SetInfo *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_Rename(struct pipes_struct *p, struct dfs_Rename *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_Move(struct pipes_struct *p, struct dfs_Move *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_ManagerGetConfigInfo(struct pipes_struct *p, struct dfs_ManagerGetConfigInfo *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_ManagerSendSiteInfo(struct pipes_struct *p, struct dfs_ManagerSendSiteInfo *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_AddFtRoot(struct pipes_struct *p, struct dfs_AddFtRoot *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_RemoveFtRoot(struct pipes_struct *p, struct dfs_RemoveFtRoot *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_AddStdRoot(struct pipes_struct *p, struct dfs_AddStdRoot *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_RemoveStdRoot(struct pipes_struct *p, struct dfs_RemoveStdRoot *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_ManagerInitialize(struct pipes_struct *p, struct dfs_ManagerInitialize *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_AddStdRootForced(struct pipes_struct *p, struct dfs_AddStdRootForced *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_GetDcAddress(struct pipes_struct *p, struct dfs_GetDcAddress *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_SetDcAddress(struct pipes_struct *p, struct dfs_SetDcAddress *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_FlushFtTable(struct pipes_struct *p, struct dfs_FlushFtTable *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_Add2(struct pipes_struct *p, struct dfs_Add2 *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_Remove2(struct pipes_struct *p, struct dfs_Remove2 *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_EnumEx(struct pipes_struct *p, struct dfs_EnumEx *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

WERROR _dfs_SetInfo2(struct pipes_struct *p, struct dfs_SetInfo2 *r)
{
	/* FIXME: Implement your code here */
	p->fault_state = DCERPC_FAULT_OP_RNG_ERROR;
	return WERR_NOT_SUPPORTED;
}

/* include the generated boilerplate */
#include "librpc/gen_ndr/ndr_dfs_scompat.c"
