/* 
   Unix SMB/CIFS implementation.

   FRITZ!OS Event Logging

   Copyright (C) 2016 AVM 
   
   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 2 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, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/


#ifdef AVM_FRITZBOX

#include "includes.h"

#include "avm_eventlog.h"

/* dont allow any ' in '%s'-arg of system() */
static char *make_safe_arg_for_system(const char *arg)
{
	char *s = arg;
	if (strchr(s, '\'')) {
		s = strdup(arg);
		if (s) {
			char *p;
			for (p = s; *p; p++) {
				if (*p == '\'') *p = '.';
			}
		}
	}
	return s;
}

void AccessEventLog(unsigned event_id, const char *name, const char *addr_str)
{
	char cmd[256];
	char *safe_name;

	// assert (0 == strchr(addr_str, '\''));

	if ('@' == name[0]) return;

	safe_name = make_safe_arg_for_system(name);
	if (!safe_name) return;

	snprintf(cmd, sizeof(cmd)-1, "/sbin/eventadd %u '%s' '%s' >/dev/null 2>/dev/null", event_id, safe_name, addr_str);
	cmd[sizeof(cmd)-1] = '\0';
	(void)system(cmd);
	if (safe_name != name) free(safe_name);
}

char *GetAppDisplayName(const char *username)
{
	char buf[512];
	char *app_name = 0;
	FILE *fp = fopen("/var/tmp/apps.map", "r");
	
	if (fp) {
		while (!app_name && (buf == fgets(buf, sizeof(buf), fp))) {
			char *p;
			while((p = strrchr(buf, '\n')) || (p = strrchr(buf, '\r'))) {
				*p = '\0';
			}
			p = strchr(buf, '=');
			if (p) {
				*p = 0;
				if (0 == strcmp(buf, username)) {
					app_name = strdup(p + 1);
				}
			}
		}
		
		fclose(fp);
	}
	return app_name;
}

#endif /*  AVM_FRITZBOX */