# $Id:$
#
# Provides a function that requests a particular connection from the
# Time Machine and stores the subsequent reassembled payload into a
# local file.

@load time-machine

module TimeMachine;

export {
	global save_contents:
		function(filename_prefix: string, c: connection,
				in_mem: bool, descr: string);

	global save_contents_id:
		function(filename_prefix: string, id: conn_id, start: time,
				in_mem: bool, descr: string);

	const contents_dir = "tm-contents" &redef;
	}

# Table associating TM tag with filename.
global requested_conns: table[string] of string;

function save_contents(filename_prefix: string, c: connection,
			in_mem: bool, descr: string)
	{
	if ( is_external_connection(c) )
		return;

	save_contents_id(filename_prefix, c$id, c$start_time, in_mem, descr);
	}

function save_contents_id(filename_prefix: string, id: conn_id, start: time,
				in_mem: bool, descr: string)
	{
	TimeMachine::suspend_cut_off_id(id, descr);
	local qtag = TimeMachine::request_connection_id(id, start, in_mem, descr);
	if ( qtag == "" )
		return;

	requested_conns[qtag] = filename_prefix;
	}

event connection_external(c: connection, tag: string)
	{
	if ( tag !in requested_conns )
		return;

	local fn = requested_conns[tag];
	local id = c$id;
	local idstr = fmt("%s.%d-%s.%d", id$orig_h, id$orig_p, id$resp_h, id$resp_p);

	local orig_f = open(fmt("%s/%s.%s.orig.dat", contents_dir, fn, idstr));
	local resp_f = open(fmt("%s/%s.%s.resp.dat", contents_dir, fn, idstr));
	set_contents_file(c$id, CONTENTS_ORIG, orig_f);
	set_contents_file(c$id, CONTENTS_RESP, resp_f);
	}

event bro_init()
	{
	mkdir(contents_dir);
	}
