#!/usr/bin/python

#
# If you read this:
# 	Select the "run in terminal" option
#	or open this file by command line:
#	./onionmail-wizard
#

#
# Copyright (C) 2014-2015 by Tramaci.Org & OnionMail.info & mes3hacklab
# This file is a wizard to subscribe and configure onionmail in TAILS
# (PGP keys, Claws-Mail, VMAT address and etc...)
#
# onionmail-wizard 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 source code 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 source code; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

import os
import socket
import string
import sys
import subprocess
import shutil
import time
import re
import tty
import random

import traceback #

#
# Non modificare qui'. Modifica la sezione distros
#

CONF= { "version" : "1.8.3" }
CONF['requestw']=1
CONF['home']=os.environ['HOME']
CONF['user']=os.environ['USER']
CONF['setusr']=""
CONF['selvmat']=0

pha2=0
pha1=len(sys.argv)-1
for idx in range(len(sys.argv)):
	par=sys.argv[idx]
	if pha2!=0:
		continue

	if par == "-u":
		if idx == pha1:
			print "Syntax error"
			sys.exit(1)

		CONF['user'] = sys.argv[idx+1]
		if CONF['user'] == "root":
			CONF['home']="/root"
		else:
			CONF['home']="/home/"+CONF['user']
		CONF['setusr'] = CONF['user']
		if not os.path.isdir(CONF['home']):
			print "Invalid home directory"
			sys.exit(1)
		pha2=1

	if par == "-uh":
		if idx == pha1:
			print "Syntax error"
			sys.exit(1)

		CONF['home'] = sys.argv[idx+1]
		if not os.path.isdir(CONF['home']):
			print "Invalid home directory"
			sys.exit(1)
		pha2=1


CONF['base']=CONF['home']+"/.claws-mail"
CONF['certpath']=CONF['base']+"/certs"
CONF['accountrc']=CONF['base']+"/accountrc"
CONF['maildir']=CONF['home']+"/OnionMail"
CONF['mhome']="OnionMail/"
CONF['infofile']=CONF['home']+"/onionmail-info-account"
CONF['tarprofile']="profile.tar.gz"
CONF['tarmail']="maildir.tar.gz"
CONF['tarlib']="/var/lib/onionmail-wizard"
CONF['clawsmail']="torify /usr/bin/claws-mail"
CONF['clawsexit']="claws-mail --exit"
CONF['mkpgp']=1
CONF['torport']=9050
CONF['torip']="127.0.0.1"
CONF['torrc']="/etc/tor/torrc"
CONF['saveinfo']=1
CONF['list']="onionmail.lst"
CONF['gpgcommentv']="OnionMail VMAT address"
CONF['complflg']=0
CONF['distok']=0
CONF['opensslelf']="/usr/bin/openssl"
CONF['tmp']="/tmp"
CONF['tempath']=CONF['tmp']
CONF['wget']="torify wget"
CONF['gpg']="gpg"
CONF['gpg-send']="torify gpg"
CONF['retor']="/etc/init.d/tor restart"
CONF['fretor']=0
CONF['apt']="apt-get install %X%"
CONF['cwd']=os.path.realpath(__file__)
CONF['cwd']=os.path.dirname(CONF['cwd'])
CONF['conftor']=1
CONF['lastmsg']="remember to use: torify claws-mail"
CONF['debug']=0
CONF['beep']="\x07\x07\x07\a\a\a\n"
CONF['autorave']=1
CONF['reqelf'] = [
		{ "b" : "/usr/bin/claws-mail"	, "p" : "claws-mail"	},
		{ "b" : "/usr/bin/tor"		, "p" : "tor"		},
		{ "b" : "/usr/bin/torsocks" 	, "p" : "torsocks"	},
		{ "b" : "/usr/bin/torify" 	, "p" : "torsocks"	}
		]

CONF['rnd']=time.ctime()
random.seed(CONF['rnd'])
CONF['rnd']=CONF['tmp']+'/'+str(random.randrange(1000000,9999999))+"-"+str(random.randrange(1000000,9999999)) + ".tmp"
CONF['ssltmp'] = str(random.randrange(1000000,9999999))+"-"+str(random.randrange(1000000,9999999)) + ".tmp"

CONF['gpgSection'] = """
[GPG]
auto_check_signatures=1
use_gpg_agent=1
store_passphrase=0
store_passphrase_timeout=0
passphrase_grab=0
gpg_warning=1
gpg_ask_create_key=0
skip_encryption_warning=
"""

CONF['pluginsCommon'] = """
[Plugins_Common]

"""

CONF['pluginGPG'] = [
	"/usr/lib/claws-mail/plugins/pgpcore.so",
	"/usr/lib/claws-mail/plugins/pgpmime.so",
	"/usr/lib/claws-mail/plugins/pgpinline.so"
	]

CONF['dekstop'] = """
[Desktop Entry]
Version=1.0
Name=Tofified Claws Mail
GenericName=TOR E-mail client
Exec=%X%
Icon=claws-mail
Categories=GTK;Network;Email;
Comment=Claws-Mail for your OnionMail
Terminal=false
Type=Application
StartupNotify=true
MimeType=x-scheme-handler/mailto;
X-Info=Claws Mail
"""
CONF['desktoppos'] = "/usr/share/applications"
CONF['desktopfile'] = "tor-claws-mail.desktop"
CONF['deskexec'] = "torify /usr/bin/claws-mail"
CONF['deksreload'] = "gnome-panel --replace > /dev/null 2>/dev/null &" #"killall gnome-panel"

Col = {}
Col["0"] = "\033[0m"    
Col["red"] = "\033[0;31m"         
Col["green"] = "\033[0;32m"       
Col["yellow"] = "\033[0;33m"     
Col["blue"] = "\033[0;34m"       
Col["purple"] = "\033[0;35m"     
Col["cyan"] = "\033[0;36m"       
Col["white"] = "\033[0;37m"       
Col["ored"] = "\033[41m"     
Col["ogreen"] = "\033[42m"     
Col["oyellow"] = "\033[43m"     
Col["oblue"] = "\033[44m"       
Col["opurple"] = "\033[45m"    
Col["ocyan"] = "\033[46m"      

distros = [
		{ 
			"d" : "tails" 	,
			"f" : "amnesia"	,
			"n" : ""	,
			"c" : [
					{
					"k"	:	"maildir"	, 
					"v"	:	"%X%/Persistent/OnionMail",
					"c"	:	"home"		}
					,
					{
					"k"	:	"gpg-send"	, 
					"v"	:	"%X%",
					"c"	:	"gpg"		}
					,
					{
					"k"	:	"wget"		, 
					"v"	:	"wget"		}
					,
					{
					"k"	:	"autorave"	, 
					"v"	:	0		}
					,
					{
					"k"	:	"beep"		, 
					"v"	:	""		}
					,
					{
					"k"	:	"lastmsg"	,
					"v"	:	""		}
					,
					{
					"k"	:	"clawsmail"	,
					"v"	:	"/usr/local/bin/torified-claws-mail &"}
					,
					{
					"k"	:	"mhome"		,
					"v"	:	"Persistent/OnionMail/"}
					,
					{
					"k"	:	"infofile"	,
					"v"	:	"%X%/Persistent/OnionMail/onionmail-info-account",
					"c"	:	"home"		}
					]	,

			"x" : "distTails"	}
		,
		{ 
			"d" : "debian" 	,
			"f" : "Debian"	,
			"n" : "amnesia"	,
			"c" : [
					{
					"k"	:	"maildir"	, 
					"v"	:	"%X%/OnionMail" ,
					"c"	:	"home"		}
					,
					{
					"k"	:	"mhome"		,
					"v"	:	"OnionMail/"}
					,
					{
					"k"	:	"clawsmail"	,
					"v"	:	"torify /usr/bin/claws-mail"}
					,
					{
					"k"	:	"infofile"	,
					"v"	:	"%X%/onionmail-info-account",
					"c"	:	"home"		}
					]	,
					
			"x"	:	""
			}
	]

startpath=os.getcwd()
stat=1
ret="NOP"
USER=""
PEMCRT=""

DEFAULT_CONFIG="""
[Account: __number__]
account_name=__onionmail__
is_default=__is_default__
name=__username__
address=__onionmail__
organization=__nick__
protocol=0
receive_server=__onion__
smtp_server=__onion__
nntp_server=
local_mbox=/var/mail
use_mail_command=0
mail_command=/usr/sbin/sendmail -t -i
use_nntp_auth=0
use_nntp_auth_onconnect=0
user_id=__username__
password=__pop3password__
use_apop_auth=0
remove_mail=1
message_leave_time=7
message_leave_hour=0
enable_size_limit=0
size_limit=1024
filter_on_receive=1
filterhook_on_receive=1
imap_auth_method=0
receive_at_get_all=1
max_news_articles=300
inbox=#mh/__mhinbox__/inbox
local_inbox=#mh/__mhinbox__/inbox
imap_directory=
imap_subsonly=1
low_bandwidth=0
generate_msgid=1
generate_xmailer=1
add_custom_header=0
msgid_with_addr=0
use_smtp_auth=1
smtp_auth_method=16
smtp_user_id=__username__
smtp_password=__smtppassword__
pop_before_smtp=0
pop_before_smtp_timeout=5
signature_type=0
signature_path=
auto_signature=0
signature_separator=-- 
set_autocc=0
auto_cc=
set_autobcc=0
auto_bcc=
set_autoreplyto=0
auto_replyto=
enable_default_dictionary=0
default_dictionary=de
enable_default_alt_dictionary=0
default_alt_dictionary=de
compose_with_format=0
compose_subject_format=
compose_body_format=
reply_with_format=0
reply_quotemark=
reply_body_format=
forward_with_format=0
forward_quotemark=
forward_body_format=
default_privacy_system=
default_encrypt=0
default_encrypt_reply=1
default_sign=0
default_sign_reply=0
save_clear_text=0
encrypt_to_self=0
privacy_prefs=gpg=REVGQVVMVA==
ssl_pop=2
ssl_imap=0
ssl_nntp=0
ssl_smtp=2
use_nonblocking_ssl=1
in_ssl_client_cert_file=
in_ssl_client_cert_pass=!
out_ssl_client_cert_file=
out_ssl_client_cert_pass=!
set_smtpport=1
smtp_port=25
set_popport=1
pop_port=110
set_imapport=0
imap_port=143
set_nntpport=0
nntp_port=119
set_domain=0
domain=
gnutls_set_priority=0
gnutls_priority=
mark_crosspost_read=0
crosspost_color=0
set_sent_folder=0
sent_folder=
set_queue_folder=0
queue_folder=
set_draft_folder=0
draft_folder=
set_trash_folder=0
trash_folder=
imap_use_trash=1
"""

DEFAULT_FOLDERLIST="""
    <folder type="mh" path="__BOXNAME__" sort="0" collapsed="0" name="__USER__">
        <folderitem last_seen="0" order="0" watched="0" ignore="0" locked="0" forwarded="0" replied="0" total="0" marked="0" unreadmarked="0" unread="0" new="0" mtime="__TIMESTAMP__" sort_type="ascending" sort_key="date" hidedelmsgs="0" hidereadmsgs="0" threaded="1" thread_collapsed="0" collapsed="0" path="trash" name="trash" type="trash" />
        <folderitem last_seen="0" order="0" watched="0" ignore="0" locked="0" forwarded="0" replied="0" total="0" marked="0" unreadmarked="0" unread="0" new="0" mtime="__TIMESTAMP__" sort_type="ascending" sort_key="date" hidedelmsgs="0" hidereadmsgs="0" threaded="1" thread_collapsed="0" collapsed="0" path="draft" name="draft" type="draft" />
        <folderitem last_seen="0" order="0" watched="0" ignore="0" locked="0" forwarded="0" replied="0" total="0" marked="0" unreadmarked="0" unread="0" new="0" mtime="__TIMESTAMP__" sort_type="ascending" sort_key="date" hidedelmsgs="0" hidereadmsgs="0" threaded="1" thread_collapsed="0" collapsed="0" path="queue" name="queue" type="queue" />
        <folderitem last_seen="0" order="0" watched="0" ignore="0" locked="0" forwarded="0" replied="0" total="0" marked="0" unreadmarked="0" unread="0" new="0" mtime="__TIMESTAMP__" sort_type="ascending" sort_key="date" hidedelmsgs="0" hidereadmsgs="0" threaded="1" thread_collapsed="0" collapsed="0" path="sent" name="sent" type="outbox" />
        <folderitem last_seen="0" order="0" watched="0" ignore="0" locked="0" forwarded="0" replied="0" total="0" marked="0" unreadmarked="0" unread="0" new="0" mtime="__TIMESTAMP__" sort_type="ascending" sort_key="date" hidedelmsgs="0" hidereadmsgs="0" threaded="1" thread_collapsed="0" collapsed="0" path="inbox" name="inbox" type="inbox" />
    </folder>
"""

PGPkey="""
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBFOAlMcBCAC+wkTButileTiDjr50NYLspDF1Etk3hyFssAG8rALJVifb8inX
e/J7vYUf8EsrWL/FR1iOQbjDrwjzI5r9b5TZN5wmgroVaqiJKGe/e1VllRBpazn9
ie0eunj2Kjvu1YCVb1+Mixf3/Dg8RIMkArJDzNCqYz7FyM75fsZLWlppM46vLFLf
E6NPzcsg19S/8bhjOxMemz3PbbVxGdiTne8qH9V6w8a4HV7sGqiiXumPQgvYp4On
0bxzOh1ZINcC3WFMX3eiH7UEIF8crukoksAQ93s9cxCfw6u7qtZrMsXdrjQ3Ooym
e4r8Wf1G9MBd/0o43hKQi+iqlr003YEJE9V7ABEBAAG0Yk9uaW9uTWFpbCBOZXR3
b3JrIEFwcGxpY2F0aW9uIChPbmlvbk1haWwgTmV0d29yayBhcHBsaWNhdGlvbikg
PG5ldHdvcmsuYXBwQGxvdWhsYmd5dXBna3Rzdzcub25pb24+iQE2BBMBAgAgBQJT
gJTHAhsPBgsJCAcDAgQVAggDBBYCAwECHgECF4AACgkQkRuYZnag/amWawgAk6VX
V1kBC4EwRgkt4/R+mn7wSB12bCvK1ldCjedXbLydCT1O4P9gW7aVJHm3Xs6xD9cx
l7weAIPCGNaszAf0mJqrUunJ8mpYqzTa2QaQpLQTbGljin5NK0iQlddtluJ0tIcu
n7EKLiQ3fCMj9IXxkmRFy6RTW9f9jBNm5iXD2UYz98wlJa/paEs4ABsyjswqK0VV
bQvep41s/ruZl07bi0Tdi6ZU/SCFxyn+Egw0KBARROS/sUGS9gHCNL7hE83bZOS/
kK8Bqdb4lgOm8lmy1KqL0yVt7PnGF/7+iFont6yhUFIyKoXSwHXRQT8RcmStjucA
fzajq8SWv9iM65gqLIkCHAQTAQIABgUCU4CVrgAKCRDJxSQSgoghaxALD/930uXF
jMVbOVJzZCOF3lE2sg2dkDJE4RSbRUuRdEKg9rQUK2KxWM9JFp4b3JpTSvum0B4O
bnezjBbEYabwya3/xYCw5QmCJfu67b7diUtSMs4uVLV16Q0AvULRcjSnINLY6v7C
HJV103znU9xq4V3axMw8ypT8+jQpmNVs1htArTzb4/Lx51GwQo0jhR79kKCGbBe1
RmKjeKNqJb57YEVW2YnpqYRwn/NxlyXgRkcU6M1wivTXTdG7Fva+/2cEHnTVILsW
CoBkDgL2nLA8fVErVyiC5OJU+jUmdaAG8uU0O/EyrLHn15oZgmEbEnY5RQarQckp
LW5AtfXl2mvzhHS0j1nR2W2ih9Mo8UjHz5Gbwi6iyzUzkynSxKFs2RyCST8ZpQm1
ySZ11KhIwyK7VLw42v9detBkSQ1KMhVuHUJ4jKOZ39rqmjtQEf5RHNZ9FsjjT/oZ
afmr0idnTe3+KGiZz/GYA6dmvbNbMQjZ60zbKLxVmGyeC7CqGMwVeGI7JucB0E67
uKCBqBCeZ6IRPOCDL5tTaiwMTZf6pqXutrDcKBTQUIP3PejivBLEGWoWgW8LA83s
PlI6+cUsdUV2QdB7q4LE+bHMnOMxBu23pGEDv6fd4Ppsgu5t+2Pyb8hk+dOLTwIL
UTWOect0S+GEQ8Ey+K6QCefEX03846vccP6Z+w==
=TTj4
-----END PGP PUBLIC KEY BLOCK-----
"""
PGPkey=PGPkey+"\032\n"
PGPFir="A9CD12C1F84476DB879DF642911B986676A0FDA9"
PGPId="911B986676A0FDA9"
MainServer="http://louhlbgyupgktsw7.onion/network/"

QBMatrix = [
	[ 8,0,0,7,0,3,0,9,9,0,0,0,3,7,0,0,8,	Col["purple"]+"Entropy generator"+Col["cyan"]+" V1.0"	]	,
	[ 0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,0,0,	Col["green"]+" Using AutoRave" 				]	,
	[ 0,4,0,0,0,0,5,7,7,5,0,0,0,0,0,4,0,	Col["blue"]+"Current entropy: %ent%"			]	,
	[ 7,4,0,1,1,0,0,1,8,0,0,1,1,0,0,4,7,	Col["blue"]+"N. loops: %c%" 				]	,
	[ 7,4,0,1,1,0,0,2,4,0,0,1,1,0,0,4,7,	Col["white"]+"-----------------------"			]	,
	[ 0,4,0,0,0,0,5,7,7,5,0,0,0,0,0,4,0,	Col["blue"]+"Readed KB: %rbyk%" 			]	,
	[ 0,0,0,8,0,0,0,0,0,0,0,0,0,0,4,0,0,	Col["blue"]+"Writed KB: %wbyk%" 			]	,
	[ 8,0,0,7,0,3,0,9,9,0,0,0,7,3,0,0,8,	Col["blue"]+"Time elapsed: %tmp% S" 			]	]
	# La matrice e'prodotta in modo da generare le stesse forme se non ci sono
	# numeri da random.


def csh(arg):
        return '"%s"' % (
                arg
                .replace('\\','\\\\')
                .replace('"','\\"')
                .replace('$','\\$')
                .replace('`','\\`')
        )

def AutoRave(proc):
	try:
		os.system("stty -echo")
		print Col["red"]+"Move your mouse as randomly as possible. The longer you move it, the better."
		print "This significantly increases the system entropy and cryptographic stregth of the encryption keys."
		print Col["purple"]+"I try to creare some entropy by the AutoRave."+Col["0"]
		print Col["blue"]+"If you want to interrupt this processpress CTRL+C"+Col["0"]+"\n"
		R = open("/dev/urandom","r")

		Pal = Col.values()
		MPal = len(Pal)

		Alfa="0123456789"
		MAlfa = len(Alfa)
		print "  ABCDEFGHIJKLMNO"
		for y in range(8):
			print y

		O = open("/dev/null","w")
		rd=""
		TX = { "c" : 0 , "rby" : 0, "wby" : 0};
		STime = int(time.time())

		while proc.poll() == None:
			X = open("/proc/sys/kernel/random/entropy_avail","r")
			TX['ent'] = X.read()
			TX['ent'] = TX['ent'].strip()
			X.close()
			TX['c'] = TX['c']+1
			TX['tmp'] = int(time.time()) - STime
			reg = 8
			rs = len(rd)
			TX['rby'] = TX['rby'] + rs
			TX['rbyk'] = int(TX['rby']/1024)
			TX['wbyk'] = int(TX['wby']/1024)
			O.write(rd)
			if rs>4:
				rs=4

			for x in range(rs):
				o = ord(rd[x])
				b = o & 7
				a = int(o/8) & 15
				QBMatrix[b][a] ^= o

			print "\033[9A"
			qq=""
			for y in range(8):
				st=""
				for x in range(15):
					c = QBMatrix[y][x]
					c = c + QBMatrix[ (y+1) & 7 ][ (x+1) & 15]
					c = c + QBMatrix[ (y-1) & 7 ][ (x-1) & 15]
					c = c + QBMatrix[ (y+1) & 7 ][ (x-1) & 15]
					c = c + QBMatrix[ (y-1) & 7 ][ (x+1) & 15]
					c = c ^ int(c/2)
					reg = reg ^ c
					c = c & 255
					QBMatrix[y][x] = c
					n = c % MAlfa
					n = Alfa[n]
					c = c % MPal
					c = Pal[c]
					st = st + c + n
				print y,st+Col["0"],
				t = QBMatrix[y][17]

				for k,v in TX.items():
					t = t.replace("%"+k+"%",Col["green"]+str(v))

				print "\t",t+Col["0"]
				qq = qq + st+"\n"
			reg=reg&15
			rd = R.read(1+reg*100)
			O.write(qq)
			TX['wby'] = TX['wby'] + len(qq)+len(rd)
			random.seed( random.randrange(1,9999999) + reg)
			r = reg + random.randrange(1,100)
			r = 2 + (r % 10)
			time.sleep(1/r)
		R.close()
		O.close()
	except KeyboardInterrupt:
		print "\033[2J\033[0;0H\n"
		proc.kill()
		print Col["red"]+" Key generation interrupted! "+Col["0"]
		print Col["cyan"]+"No GPG key available!"+Col["0"]+"\n"		
	except:
		print "\033[2J\033[0;0H\n"
		print Col["red"]+" AutoRave Error!!! "+Col["0"]
	os.system("stty echo")	
	print "\n"

def getDesktop():
	base = os.environ['HOME']
	base = base + "/.config/user-dirs.dirs"
	if not os.path.isfile(base):
		return ""

	cmd="cat "+csh(base)+""" | egrep -iEv '\s*\#' | egrep -m 1 -iE '\s*XDG\_DESKTOP\_DIR\s*=\s*\"' | egrep -iEo '\"[^"]+\"' | egrep -iEo '[^"]+'"""
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	rs = p.stdout.read()
	if p.wait()!=0:
		return ""

	rs=rs.strip()
	for k,v in os.environ.items():
		rs=rs.replace('$'+k,v)
	return rs

def gnomeIcon(asRoot):
	global CONF
	print Col["cyan"]+"Installing new menu icon ... "+Col["0"],

	if asRoot==1:
		if os.environ['USER'] != "root":
			print Col["red"]+"Error"+Col["0"]
			print "This function requires ROOT permissions"
			sys.exit(1)
		
		pat = CONF['desktoppos'] + "/" + CONF['desktopfile']
	else:
		pat = getDesktop()
		if pat == "":
			print Col["red"]+"Can't find the Desktop path!"+Col["0"]
			return
		pat = pat + "/" + CONF['desktopfile']

	if not os.path.isfile(pat):
		c = open(pat,"w")
		d = CONF['dekstop'].replace("%X%",CONF['deskexec'])
		c.write(d)
		c.close()
		os.system("chmod a=r,u=rw "+csh(pat))    
		if CONF['deksreload'] != "":
			os.system(CONF['deksreload'])    
		print Col["cyan"]+" Done!!!"+Col["0"]

def getTORConfig():
	global CONF
	print Col["purple"]+"Get TOR SocksPort ..."+Col["0"],
	try:
		p = subprocess.Popen(
			"cat "+csh(CONF['torrc'])+" | egrep -iEv '^\#' | egrep -iEv '^\s+\#' | egrep -iEo 'SocksPort\s+[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{4,5}' | egrep -iEo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{4,5}' -m 1",
			shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
		rs = p.stdout.read()
		rs = rs.strip()
		if p.wait()!=0:
			raise Exception("Process error")
		if rs == "":
			raise Exception("Can't find SocksPort in torrc")
		try:
			ip, port = rs.split(":")
			print Col["cyan"]+"IP",ip,"Port",port,Col["0"]
			CONF['torip'] = ip
			CONF['torport'] = port
		except:
			raise Exception("Can't find IP and Port in torrc")

		prog = re.compile("[0-9]{4,5}")
		if prog.match(port) == "":
			raise Exception("Invalid SocksPort")

		prog = re.compile("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
		if prog.match(ip) == "":
			raise Exception("Invalid SocksPort IP address")

	except Exception as E:
		getTORConfig2()

def importPGPServKey(onion,nick):
	
	try:
		print Col["cyan"]+"Try to import server's PGP key..."+Col["0"]
		cmd = "wget -qO - "+csh("http://"+onion+"/"+nick+".asc")+" | gpg --import -"
		p = subprocess.Popen( cmd,
			shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
		rs = p.stdout.read()
		print rs
		print Col["purple"]+"Press enter to continue"+Col["0"]
		cp = sys.stdin.readline()
	except Exception as E:
		print Col["red"]+E+Col["0"]

def getTORConfig2():
	global CONF
	print Col["purple"]+"."+Col["0"],
	try:
		p = subprocess.Popen(
			"cat "+csh(CONF['torrc'])+" | egrep -iEo 'SocksPort\s+[0-9]{4,5}' | egrep -iEv '\#' | egrep -iEo '[0-9]{4,5}' -m 1",
			shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
		rs = p.stdout.read()
		rs = rs.strip()
		if p.wait()!=0:
			raise Exception("Process error")
		if rs == "":
			raise Exception("Can't find SocksPort in torrc")
		ip="127.0.0.1"
		port = rs
		prog = re.compile("[0-9]{4,5}")
		if prog.match(port) == "":
			raise Exception("Invalid SocksPort")
		
	except Exception as E:
		print Col["red"]+E+Col["0"]
		print "\t"+Col["cyan"]+"Using default: IP",CONF['torip'],"Port",CONF['torport'],Col["0"]


def endProc(retco):
	global CONF
	if not CONF['rnd'] == "":
		if not CONF["tempath"] == CONF["tmp"]:
			p = subprocess.Popen("rm -R -f "+csh(CONF["tempath"])+" > /dev/null",shell=True)
			ret = p.wait()
			if ret!=0:
				print "Can't delete tmp files!"

	if CONF['rnd'] == "":
		for tmp in [ 
			CONF['list'] 		, 
			CONF['tarprofile'] 	, 
			CONF['tarmail'] 	,
			CONF['ssltmp'] 		,
			CONF['list'] 		+ ".asc"	, 
			CONF['tarprofile'] 	+ ".asc"	, 
			CONF['tarmail'] 	+ ".asc"	] :

			tmp = CONF['tmp']+"/"+tmp
			if os.path.isfile(tmp):
				p = subprocess.Popen("rm -f "+csh(tmp)+" > /dev/null",shell=True)
				ret = p.wait()
				if ret!=0:
					print "Can't delete: "+csh(tmp)
	
	sys.exit(retco)

def distTails(dist):
	if not os.path.isdir("/home/amnesia/Persistent"):
		print "\n"+Col['red']+"This wizard requires the persistence activated!"+Col['0']
		print "\nPress enter to exit wizard"
		rs = sys.stdin.readline()
		endProc(0)

def setdistro(dist):
	"Set the disto parameters"	
	global CONF
	for chg in dist['c']:
		v = chg['v']
		if chg.has_key('c') :
			v=v.replace('%X%',CONF[chg['c']])

		CONF[chg['k']]=v

	CONF['distro'] = dist['d']
	CONF['distok'] = 1
	if dist.has_key('m') :
		CONF['lastmsg'] = dist['m']
	if dist['x'] != "":
		globals()[dist['x']](dist)

def getdistro():
	"Find the distro via uname"
	global distros
	print Col["purple"]+"Get the distro info ...",Col["0"],
	cmd="uname -a"
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	rs = p.stdout.read()
	if p.wait()!=0:
		ferro("Can't detect distro type")

	cmd="uname -n"
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	rs = rs+"<"+p.stdout.read()+">"
	if p.wait()!=0:
		ferro("Can't detect distro type")	

	rs=rs.replace("\n","")	

	for dist in distros:
		if rs.find(dist['f']) != -1 :
			if dist['n'] != "" and rs.find(dist['n']) !=-1 :
				continue
			print Col["purple"],dist['d'],Col["0"]
			setdistro(dist)
			break
	if CONF['distok'] != 1:
		print Col["purple"]+"N/A",Col["0"]
		print Col["cyan"]+"\tCompatibility mode: Try to run as Debian"+Col["0"]
		print Col["cyan"]+"\tPress enter to continue."+Col["0"]+"\n"
		pha2 = sys.stdin.readline()

class PException(Exception): pass

def download(out,dest):
	outasc=out+".asc"
	destf=dest+"/"+out+".asc"
	desto=dest+"/"+out
	cmd=CONF['wget']+" "+csh(MainServer+outasc)+" -q -t 2 -U \"onion.py (TAILS)\" -O "+csh(destf)
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	if p.wait()!=0:
		ferro("Can't download from "+MainServer)

	cmd=CONF['gpg']+" --status-fd=2 --no-verbose --batch --quiet --output - --verify "+csh(destf)
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	rs = p.stdout.read()
	if p.wait()!=0:
		ferro("Invalid signature in file outasc")

	rs=string.upper(rs)
	rs=string.replace(rs," ","")
	rs=string.split(rs,"\n")
	pa=0
	pb=0
	pat1="[GNUPG:]GOODSIG"+PGPId
	pat2="[GNUPG:]VALIDSIG"+PGPFir
	for line in rs:
		if string.find(line,pat1)!=-1:
			pa=1
		if string.find(line,pat2)!=-1:
			pb=1

	if pa==0 or pb==0:
		print "\t",Col["red"],"Sign error ", pa, bp, Col["0"]
		ferro("This file is not signed by "+PGPId)
	
	cmd=CONF['gpg']+" --status-fd=2 --no-verbose --quiet --batch --output "+csh(desto)+" --decrypt "+csh(destf)
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	if p.wait()!=0:
		ferro("Can't decrypt "+destf)

	if not os.path.isfile(desto):
		ferro("Can't decrypt to "+desto)

	os.remove(destf)

def importmypgp():
	p = subprocess.Popen(CONF['gpg']+" --batch --yes --import",shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	p.stdin.write(PGPkey)
	p.stdin.close()
	if p.wait()!=0:
		ferro("Can't import my PGP key! All downloaded data will be insecure!")

def retShell(cmd):
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	rs = p.stdout.read()
	if p.wait()!=0:
		return ""

	return rs.strip()
	

def chkGPG():
	clawsrc = CONF['base']+"/clawsrc"
	cgpg = retShell("egrep -Ei '^/usr/lib/claws-mail/plugins/pgpcore.so$' -m 1 "+csh(clawsrc))
	if cgpg=="":
		print Col["red"] + "GPG Extension not enabled!"+Col["0"]
		print Col["cyan"] + "You must enable it manually"+Col["0"]
		print Col["cyan"]+"Press enter to continue."+Col["0"]
		cp = sys.stdin.readline()
		return
	print Col["green"] + "GPG Extension enabled"+Col["0"]
	cgpg = retShell("egrep -Ei '^/usr/lib/claws-mail/plugins/pgpmime.so$' -m 1 "+csh(clawsrc))
	if cgpg=="":
		print Col["red"] + "GPG MIME Extension not enabled!"+Col["0"]
		print Col["cyan"] + "You must enable it manually"+Col["0"]
		print Col["cyan"]+"Press enter to continue."+Col["0"]
		cp = sys.stdin.readline()
		return
	print Col["green"] + "GPG MIME Extension enabled"+Col["0"]

def iniGPGCore():
	print Col["cyan"]+"Check GPG extensions"+Col["0"]

	clawsrc = CONF['base']+"/clawsrc"
	cgpg = retShell("egrep -Ei '^\[GPG\]$' -m 1 "+csh(clawsrc))
	if cgpg=="":
		with open(clawsrc, 'a') as f:
			f.write(CONF['gpgSection'])
	
	cgpg = retShell("egrep -Ei '^\[Plugins_Common\]$' -m 1 "+csh(clawsrc))
	if cgpg=="":
		with open(clawsrc, 'a') as f:
			f.write(CONF['pluginsCommon'])

	cgpg = retShell("egrep -Ei '^\[Plugins_GTK2\]$' -m 1 "+csh(clawsrc))
	if cgpg=="":
		with open(clawsrc, 'a') as f:
			f.write("[Plugins_GTK2]\n")

	add=""
	for fil in CONF['pluginGPG']:
		cgpg = retShell("egrep -Ei '^"+fil+"$' -m 1 "+csh(clawsrc))	
		if cgpg=="" and os.path.exists(fil):
			add = add + fil + "\n"

	if add=="":
		print Col["cyan"] + "GPG: Nothing to enable." +Col["0"]
		chkGPG()
		return

	with open(clawsrc) as f:
		text=f.read()

	text=text.replace("[Plugins_GTK2]","[Plugins_GTK2]\n"+add,1)
	
	with open(clawsrc,'w') as f:
		f.write(text)

	print Col["cyan"] + "GPG Extensions enabled" +Col["0"]
	chkGPG()


def inittheclaws():
    if os.path.exists(CONF['base'])==False or os.path.isfile(CONF['base']+"/folderlist.xml")==False:
        print Col["cyan"]+"Building the Claws-Mail's profile"+Col["0"]

        if os.path.exists(CONF['base'])==False:
		os.makedirs(CONF['base'])

        p = subprocess.Popen("tar -xzf "+csh(CONF['ctarprofile'])+" -C "+csh(CONF['base']) + " > /dev/null", shell=True)
        ret = p.wait()
        if ret==0:
            if CONF['setusr'] !="" :
            	os.system("chown "+CONF['setusr']+":"+CONF['setusr']+" -R "+csh(CONF['base']))
            	os.system("chmod a=-,u=rwx -R "+csh(CONF['base']))
            print "\t" + Col["blue"]+"Done!!!"+Col["0"]
        else:
            print "\t" + Col["red"]+"Error "+str(ret)+Col["0"]
            endProc(1)
    
    try:
    	iniGPGCore()
    except Exception as E:
    	print Col["red"]+"Error: "+E+Col["0"]


def creategpgkey(mail,name,bits,passwd):
    "Generates a PGP key via gpg"
    cmd = "--batch --gen-key --yes"
    sti ="Key-Type: RSA\n"
    sti = sti + "Key-Length: "+str(bits)+"\n"
    sti = sti + "Passphrase: "+passwd+"\n"
    sti = sti + "Expire-Date: 0\n"
    sti = sti + "Subkey-Length: "+str(bits)+"\n"
    sti = sti + "Subkey-Type: RSA\n"
    sti = sti + "Name-Real: "+name+"\n"
    sti = sti + "Name-Email: "+mail+"\n"
    sti = sti + "%commit\n"
    sti = sti + "%save\n"
    sti = sti + "%echo done\n"
    sti = sti + "\031\n\032\n"

    p = subprocess.Popen(CONF['gpg']+" "+cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
    p.stdin.write(sti)
    p.stdin.close() #Whi pgp don't create a key in debian?
    if CONF['autorave'] == 1:
    	AutoRave(p)
    return p.wait()

def addgpguid(curmail,newmail,name,passwd,comment):
	cmd=CONF['gpg']+" --yes --passphrase-fd 0 --command-fd 0 --batch --edit-key "+csh(curmail)+" adduid save"
	sti=passwd+"\n"+name+"\n"+newmail+"\n"+comment+"\n"
	p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
	p.stdin.write(sti)
	rs=p.wait()
	return rs
    
def perro(st):
    if stat==0:
        print Col["red"] + st + Col["0"]
        sok.close()
        raise PException("PERRO")

def sendkeys(mailaddr):
	try:	
		cmd=CONF['gpg']+" --batch --no-tty --with-colon --fingerprint "+mailaddr
		p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
		rs = p.stdout.read()
		if not p.wait()==0:
			raise PException("PERRO")
	
		rs=string.split(rs,"\n")
		KeyId=""
		for line in rs:
			tok=string.split(line,":")
			if tok[0]=="pub":
				KeyId=tok[4]
				break
		
		if not KeyId=="":
			print Col["cyan"]+"Sending you GPG public key..."+Col["0"]
			cmd=CONF['gpg-send']+" --batch --no-tty --send-keys "+KeyId
			p = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
			rs = p.stdout.read()
			if not p.wait() == 0:
				raise PException("PERRO")
			print Col["green"]+rs+Col["0"]
		else:
			raise PException("PERRO")
	except:
		print Col["red"]+"Can't send your public GPG key "+mailaddr+Col["0"]

def writedata(dta):
    "Sends multiline data in POP3 protocol"
    dta=string.strip(dta)
    if dta!="":
        dta=string.replace(dta,"\r\n","\n")
        dta=string.replace(dta,"\r","")
        dta=string.split(dta,"\n")
        for lin in dta:
            send(lin)
            
    send(".")
            
def rdln():
    "Read a line from raw socket"
    i = 0
    li=""
    while i<80:
        ch = sok.recv(1)
        if ch=="\r":
            break
    
        if ch!="\n":
            li = li + ch
        
        i = i +1
    return li

def rdcmd():
    "Read a cmd result"
    global stat
    global ret
    
    data = rdln()
    tok = string.split(data," ")
    if len(tok) <2:
        ret=""
    else:
        ret=tok[1]

    if tok[0]=="+OK":
        stat=1
    else:
        stat=0
    return tok

def rdcmdm():
    "This read a multi line POP3 command return"
    st = rdcmd()
    if ret==0:
        return ""
    i=0
    rs=""
    while i<4000:
        i = i+1
        li = rdln()
        if li == ".":
            break
        rs = rs+li+"\n"
    return rs

def send(cmd):
    "Send a POP3 command"
    st=cmd+"\r\n"
    sok.sendall(st)

def parseheaders(dta):
    "Parse a string as headers"
    dta=string.strip(dta)
    dta=string.replace(dta,"\r\n","\n")
    dta=string.split(dta,"\n")
    hldr = {}
    for cli in dta:
        if string.find(cli,":") != -1:
            tok = string.split(cli,":",2)
            tok[0] = string.strip(tok[0])
            tok[1] = string.strip(tok[1])
            tok[0] = string.lower(tok[0])
            hldr[tok[0]]=tok[1]
    
    return hldr

def replacer(orig,hldr):
    "Replace __key__ from hldr"
    rs=orig
    for key in hldr:
        k1 = "__"+key+"__"
        rs=string.replace(rs,k1,hldr[key])
    return rs

def folderxml(fil,nam,usr):
	fh = open(fil,"r")
	li = fh.read()
	fh.close()
	xmlc = DEFAULT_FOLDERLIST
	par={
		"TIMESTAMP"	: str(int(time.time())) ,
		"USER"		: usr			,
		"BOXNAME"	: nam			}
	
	xmlc = replacer(xmlc, par)
	li=string.replace(li,"</folderlist>",xmlc)
	li=li+"</folderlist>"
	fh = open(fil,"w")
	fh.write(li)
	fh.close()

def ferro(st):
    if st=="":
        st="Invalid USER data from server"
    print "\n"+Col["ored"]+st+Col["0"]
    raise PException("FERRO")

def checkuser():
    "Test user data"
    global USER
    ma = re.match(r'^[a-z0-9]{16}\.onion$',USER["onion"])
    if ma==False:
        ferro("")
    
    ma = re.match(r'^[a-z0-9\_\-\.]{1,40}\@[a-z0-9]{16}\.onion$',USER["onionmail"])
    if ma==False:
        ferro("")
    
    ma = re.match(r'^[a-z0-9\-\_\.]{1,40}$',USER["username"])
    if ma==False:
        ferro("")

def configuser():
    "Configure claws-mail"
    global USER

    print Col["cyan"]+"Check MailDir ... "+Col["0"],
    if not os.path.isdir(CONF['maildir']):
	try:
    		os.makedirs(CONF['maildir'])
    	except Exception:
    		print "-",

	try:
    		os.mkdir(CONF['maildir'])
    	except Exception:
    		print ".",

    print Col["green"]+"Ok"+Col["0"]+"\n"
    USER["inbox"]=CONF['maildir']+"/OnionMailBox201"
    USER["number"]="201"
    USER["is_default"]="0"

    if os.path.isfile(CONF['accountrc']):
	conf = open(CONF['accountrc'],"r")
    	dt = conf.read()
    	conf.close()
    else:
	dt=""

    for index in range(1,200):
        if string.find(dt,"[Account: " + str(index)+"]")==-1:
            USER["number"] = str(index)
            if not os.path.exists(CONF['maildir'] + "/OnionMailBox"+USER["number"]):
            	break

    USER["inbox"]=CONF['maildir'] + "/OnionMailBox"+USER["number"]
    USER["mhinbox"]=CONF['mhome'] + "OnionMailBox"+USER["number"]

    ua = DEFAULT_CONFIG
    ua = replacer(ua,USER)
    dt = dt + ua
    ua=""

    conf = open(CONF['accountrc'],"w")
    conf.write(dt)
    conf.close()
    
    os.makedirs(USER["inbox"])
    p = subprocess.Popen("tar -xf "+csh(CONF['ctarmail'])+" -C "+csh(USER["inbox"]) +" > /dev/null", shell=True)
    ret = p.wait()
    if ret!=0:
        ferro("Error 1/"+str(ret))

    if ret==0:
    	os.system("rm -f -R "+csh(USER["inbox"])+"/__tagsdb > /dev/null") 
    	if CONF['setusr'] !="" :
    		os.system("chown "+CONF['setusr']+":"+CONF['setusr']+" -R "+vsh(USER["inbox"]))
    		os.system("chmod a=-,u=rwx -R "+USER["inbox"])

    folderxml(CONF['base']+"/folderlist.xml",USER["mhinbox"],"OnionMail"+USER["number"]+" "+USER["username"])

def configssl(outp, pemcrt):
    "Config SSL certificate"
    temp=CONF['tempath']+"/"+CONF['ssltmp']
    fi = open(temp,"w")
    fi.write(pemcrt)
    fi.close()
    p = subprocess.Popen("openssl x509 -in "+csh(temp)+" -inform PEM -out "+csh(temp)+".out -outform DER", shell=True)
    ret = p.wait()
    os.remove(temp)
    temp=temp+".out"
    if os.path.exists(CONF['certpath'])==False:
        os.makedirs(CONF['certpath'])

    shutil.copyfile(temp,CONF['certpath']+"/"+outp+".25.cert")
    shutil.move(temp,CONF['certpath']+"/"+outp+".110.cert")
    return ret

def TORSocket(host):
	"Create a raw socket over TOR network"
	sok = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sok.connect((CONF['torip'],int(CONF['torport'])))
	sok.sendall("\x04\x01\x00\x6e\x00\x00\x00\x01\x00" + host + "\x00")
	ret = sok.recv(8)
	if ret[1] != "\x5a":
		if ret[1] == "\x5b":
			raise Exception("SOCKS: Request failed")
		if ret[1] == "\x5c":
			raise Exception("SOCKS: Can't connect ident")
		if ret[1] == "\x5d":
			raise Exception("SOCKS: Error USERID")
		raise Exception("SOCKS: Error "+ord(ret[1]))
	return sok

def onionmail(hiddenserv,nickserv):
	global stat
	global ret
	global sok
	global USER
	global PEMCRT
	global CONF

	print Col["purple"] + "Connecting to hidden service '"+Col["cyan"]+hiddenserv+Col["purple"]+"' ..."+Col["0"]
	try:
		sok = TORSocket(hiddenserv)
	except IOError:
		print Col["ored"]+"\tError: Can't connect to this hidden service!"+Col["0"]
		raise

	print "\t"+Col["blue"]+"Connected!!!"+Col["0"]

	rs = rdcmd()
	perro("Error on POP3 server")

	send("CAPA")
	rs = rdcmdm()
	perro("Error in POP3 session")

	if string.find(rs,"\nRQEX\n") != -1:
		CONF['selvmat']=1
	else:
		CONF['selvmat']=0

	if string.find(rs,"\nRQUS\n") == -1:
	    send("QUIT")
	    rs = rdcmd()
	    sok.close()
	    print Col["ored"]+"This server doesn't support RQUS"+Col["0"]
	    raise PException("PERRO")

	print Col["cyan"]+"New user request"+Col["0"]    
	
	if CONF['selvmat'] == 1:
		send("RQEX")
		rs = rdcmdm()
		lst = string.split(rs,"\n")
		print Col["cyan"]+"Select the exit server:"+Col["0"]
		print Col["purple"]+"Leave a blank line to set as default."+Col["0"]	
		index=1;
		for val in lst:
			if val != "":
				print Col["cyan"]+str(index)+"\t"+Col["cyan"]+val+Col["0"]
			index=index+1
		
		print Col["cyan"]+"> "+Col["0"],
		try:
			cp = sys.stdin.readline()
			cp = string.strip(cp)
			if cp != "":
				cp = int(cp)-1
				send("RQEX "+lst[cp])
				rs = rdcmd()
				print Col["purple"]+" Exit server: "+Col["green"] + lst[cp] +Col["0"]
				print "\n"
		except:
			print Col["red"]+"Ivalid selection."+Col["0"]

	print Col["purple"]+"Now the server may ask a CAPTCHA code."
	print "You will be shown a picture in ascii art, you will need to recognize the characters and enter the code."+Col["0"]
	print Col["red"]+"Be careful there may be some strange symbols to ignore."+Col["0"]
	print Col["red"]+"Please wait to otherside reply after press enter.\nSometime the hidden services may be slow.\n"+Col["0"]
	print Col["purple"]+"Press enter to continue"+Col["0"]

	cp = sys.stdin.readline()
	send("RQUS")
	while 1:
	    rs=rdcmdm()
	    if ret!="CAPTCHA":
		perro("Too many error")
		break

	    print rs
	    print Col["purple"] + "Enter CAPTCHA:"+Col["0"]
	    cp = sys.stdin.readline()
	    cp = string.strip(cp)
	    send(cp)

	print Col["cyan"]+"If you've got an invite voucher code enter it now.\n\tOtherwise, leave a blank line."+Col["0"]
	print Col["purple"]+"Enter voucher code:"+Col["0"]
	cp = sys.stdin.readline()
	cp = string.strip(cp)
	send(cp)
	rs=rdcmd()
	perro("Operation not permitted to this server")

	while 1:
	    print Col["purple"]+"Enter Username:"+Col["0"]
	    cp = sys.stdin.readline()
	    cp = string.strip(cp)
	    send(cp)
	    rs=rdcmd()
	    if ret!="USERNAME":
		perro("Too many error")
		break

	print Col["cyan"]+"The server is creating the new user, please wait..."+Col["0"]
	print "\t"+Col["cyan"]+"The current operations can take several minutes..."+Col["0"]
	writedata("")    
	USER=rdcmdm()
	perro("User subscription error")
	print "\t"+Col["purple"]+"Done!!!"+Col["0"]

	print Col["cyan"]+"Configuring Claws-Mail ..."

	USER=parseheaders(USER)
	checkuser()
	configuser()

	send("PEM")
	PEMCRT=rdcmdm()
	sok.close()

	if os.path.isfile(CONF['opensslelf']):
		cp = configssl(USER["onion"],PEMCRT)
		if cp!=0:
		    print Col["ored"] + "Error on SSL configuration"+Col["0"]
		    print Col["red"] + "Check the SSL certificate manually"+Col["0"]
		    print "\t"+Col["blue"]+"SHA1: "+Col["yellow"]+USER["sha1"]+Col["0"]

	if not os.path.isfile(CONF['opensslelf']):
		print Col["red"] + "Check the SSL certificate manually"+Col["0"]
		print "\t"+Col["blue"]+"SHA1: "+Col["yellow"]+USER["sha1"]+Col["0"]

	print Col["purple"]+"Claws-Mail:\tDone!!!"+Col["0"]

	if CONF['mkpgp']!=0:
	    print Col["cyan"]+"Generating a new PGP key"+Col["0"]
	    os.system("stty -echo")
	    
	    while 1:
		print Col["purple"]+"Enter the passphrase:"+Col["0"]
		pha1 = sys.stdin.readline()
		pha1 = string.strip(pha1)
		sys.stdout.write(Col["yellow"])
		for cp in xrange(len(pha1)):
		    sys.stdout.write("*")
		
		print Col["0"]
		print Col["purple"]+"Enter the passphrase again:"+Col["0"]
		pha2 = sys.stdin.readline()
		pha2 = string.strip(pha2)
		sys.stdout.write(Col["yellow"])
		for cp in xrange(len(pha2)):
		    sys.stdout.write("*")
		
		print Col["0"]
		if pha1==pha2:
		    break
		
		print Col["ored"]+"ERROR!"+Col["0"]
		print Col["red"]+"Retry"+Col["0"]

	    os.system("stty echo")

	    while 1:
		print Col["purple"]+"Enter your name:"+Col["0"]
		print Col["purple"]+"Leave blank if you want \"anonymous user\""+Col["0"]
		pha2 = sys.stdin.readline()
		pha2 = string.strip(pha2)
		if len(pha2)==0:
			pha2="Anonymous User"

		if len(pha2)>8:
		    break
		
		print Col["red"]+"Too short! Min. = 8 char."+Col["0"]
	
	if CONF['saveinfo']==1:
		inf=""
		for key in USER:
		    inf = inf + key + " =\t" + USER[key] + "\n"

		conf=open(CONF['infofile']+USER["number"]+".txt","w")
		conf.write(inf)
		conf.close()

	if CONF['mkpgp']!=0:
	    print Col["purple"]+"Choose the key size"+Col["0"]
	    print "\t",Col["cyan"],"(1)",Col["green"]," = ", Col["blue"] , "2048 bits\tNormal",Col["0"]
	    print "\t",Col["cyan"],"(2)",Col["green"]," = ", Col["yellow"] , "4096 bits\tGood",Col["0"]
	    print "\t",Col["cyan"],"(3)",Col["green"]," = ", Col["green"] , "8192 bits\tStrong",Col["0"]
	    print "\t",Col["cyan"],"(4)",Col["green"]," = ", Col["red"] , "16384 bits\tVery strong",Col["0"]
	    inf = { "1" : 2048 , "2": 4096, "3" : 8192, "4" : 16384 }
	    ttl = { "1" : 5    , "2": 10  , "3" : 20  , "4" : 45 } 
	    ttlx= 5
	    while 1:
		print "> ",
		bitsi=sys.stdin.readline()
		bitsi=string.strip(bitsi)
		if bitsi in inf:
			bits=inf[bitsi]
			ttlx=ttl[bitsi]
			break			
	    
	    print "\033[2J\033[0;0H\n"
	    print Col["cyan"]+"I'm building a new PGP key (",bits," bits).\n\tWait a few minutes... The processing is very complex."+Col["0"]
	    print Col["cyan"]+"This may take about "+str(ttlx)+" minutes.\nDo other activities to increase randomness of the data."+Col["0"]
	    if CONF["beep"] != "":
	    	print Col["cyan"]+"An the end of the operation will try to send a beep."+Col["0"]
	    ret = creategpgkey(USER["onionmail"],pha2,bits,pha1)
	    print "\t",str(ret)," ",Col["blue"],"Done!!!",Col["0"]
	    if CONF["beep"] != "":
	    	print CONF["beep"]

	    if "vmatmail" in USER:
		print Col["cyan"]+"Add new uid to VMAT address..."+Col["0"]
		ret = addgpguid(USER["onionmail"],USER["vmatmail"],pha2,pha1,CONF['gpgcommentv'])
		print "\t",str(ret)," ",Col["blue"],"Done!!!",Col["0"]

	    pha2=""
	    pha1=""

	print Col["cyan"]+"Account "+Col["green"]+USER["username"]+Col["cyan"]+" created successfully"+Col["0"]
	sendkeys(USER["onionmail"])
	print Col["cyan"]+"Press enter to continue."+Col["0"]
	cp = sys.stdin.readline()
	importPGPServKey(hiddenserv,nickserv)
	print "\033[2J\033[0;0H\n"	
	print Col["purple"]+"Your email account has been successfully activated."+Col["0"]
	print "Your email address is ",USER["onionmail"]
	if "vmatmail" in USER:
		print Col["cyan"]+"A VMAT virtual address is now active:"+Col["0"]
		print Col["purple"]+"Your address now appear:"+Col["0"]
		print "\t"+USER["vmatmail"]
		print Col["purple"]+"This address is used in Internet and Tor networks"+Col["0"],"\n"
	else:
		print Col["yellow"]+"Do not have an address VMAT, read the manual to know how to do."+Col["0"]
		print Col["purple"]+"Your address will translated to Internet compatibility via MAT protocol."+Col["0"],"\n"

	if CONF['saveinfo']==1:
		print Col["purple"]+"All your account informations has been saved to this file:"+Col["0"]
		print "\t"+CONF['infofile']+USER["number"]+".txt"
	
	print "\nSend a message to your server with subject the word \"RULEZ\" to get more help."
	print "Server address:",Col["cyan"]+"server@"+USER["onion"],Col["0"]
	print "\tOR ",Col["cyan"]+"server@iam.onion",Col["0"]
	print "Server administators:",Col["cyan"]+"sysop@"+USER["onion"],Col["0"]
	print "\tOR ",Col["cyan"]+"sysop@iam.onion",Col["0"]
	print "\nNow you can open Claws-Mail, everything should already be configured."
	print "If you want to activate another OnionMail, run this wizard again."
	print Col["purple"]+"See http://onionmail.info to get more information.",Col["0"]+"\n"
	print Col["cyan"]+"Press enter to continue.",Col["0"]
	cp = sys.stdin.readline()
	print "\033[2J\033[0;0H\n"	
	if CONF['clawsmail']!="":
		os.system(CONF['clawsmail'])
	
	print "\033[2J\033[0;0H\n"	
	print Col["cyan"]+"Setup wizard complete..."+Col["0"]+"\n"
	print Col["red"]+"\n Do not close this window before close Claws-Mail"+Col["0"]
	print Col["cyan"]+CONF["lastmsg"]+Col["0"]
	print "\n\t\"In the future, maybe we will implement the anonymous coffee!"
	print "\t\tToday, only OnionMail ;)\" \n"
	print "\n\n\nPress enter to close (It can close Claws-Mail)."
	cp = sys.stdin.readline()
	endProc(0) #Forza l'uscita per eliminare i file tmp!

def adj(st,sz):
	if len(st)>sz:
		st=st[0:sz]
	return string.ljust(st,sz)+" "

def serverlist():
	fd = open(CONF['clist'],"r")
	conf = fd.read()
	fd.close()
	conf = string.strip(conf)
	conf = string.split(conf,"\n")
	lst=[]
	for cli in conf:
		tok = string.split(cli,",")
		gro = "-"
		sty = "-"
		if len(tok)>4:
			gro=tok[4]
			gro=string.strip(gro)

		if len(tok)>5:
			sty=tok[5]
			sty=string.strip(sty)
	
		if len(tok)>3:
			lst.append({"nick":tok[0] , "onion":tok[1], "flg":tok[2],"per":int(tok[3]) ,"grp":gro, "typ":sty, "c1":Col["cyan"], "c2":Col["blue"], "c3":Col["green"]})

	print "\033[2J\033[0;0H"+Col["purple"]+"Select an OnionMail server:"+Col["0"]
	print " "+ adj("Opt.",5)+ adj("Nick name",16) + adj("Group",14)+ adj("Address",22) + "Status Type"
	for index in range(len(lst)):
		cur = lst[index]
		ava = Col["red"]+"DISAB."

		if cur["per"]==0:
			ava=Col["red"] + "N/A"

		if cur["per"]==0 and cur["flg"]=="V":
			ava="VOUCHER"
			cur["c3"]=Col["yellow"]

		if cur["per"]>1 and cur["per"]<25:
			ava=str(cur["per"])
			cur["c3"]=Col["yellow"]
	
		if cur["per"]>24 and cur["per"]<51:
			ava=str(cur["per"])
			cur["c3"]=Col["yellow"]

		if cur["per"]>50:
			ava=str(cur["per"])

		if cur["typ"]=="EXP":
			cur["typ"]="Test"
			cur["c1"]=Col["red"]
			cur["c2"]=Col["red"]
			cur["c3"]=Col["red"]

		if cur["typ"]=="CLO":
			cur["typ"]="Close"
			cur["c1"]=Col["red"]
			cur["c2"]=Col["red"]
			cur["c3"]=Col["red"]

		if cur["typ"]=="STA":
			cur["typ"]="Full"
			cur["c1"]=Col["red"]
			cur["c2"]=Col["red"]
			cur["c3"]=Col["red"]

		if cur["typ"]=="GRP":
			cur["typ"]="Group"
			cur["c1"]=Col["green"]
			cur["c2"]=Col["yellow"]
			cur["c3"]=Col["red"]

		if cur["typ"]=="BIG":
			cur["typ"]="Big"

		if cur["typ"]=="HUG":
			cur["typ"]="Huge"

		if cur["typ"]=="UNK":
			cur["typ"]="-"

		if cur["typ"]=="NOR":
			cur["typ"]="-"

		print " "+Col["purple"] + adj("(" +str(index+1) + ")",5)+cur["c1"]+ adj(cur["nick"],16) + Col["cyan"] + adj(cur["grp"],14) + cur["c2"] + adj(cur["onion"],22) + cur["c3"] + adj(ava,6) + cur["c3"] + cur["typ"] + Col["0"] 
	
		if (index%21)==20:
			os.system("stty -echo")			
			print Col["cyan"],"Scroll?",Col["0"]
			pha2 = sys.stdin.readline()
			os.system("stty echo")
			print " "+ adj("Opt.",5)+ adj("Nick name",16) + adj("Group",14)+ adj("Address",22) + "Status Type"

	hserv=""
	print " "+Col["purple"] + adj("(^C)",5)+Col["cyan"]+ "Exit wizard."+ Col["0"]	

	while 1:
		print Col["cyan"]+"> "+Col["0"],
		pha2 = sys.stdin.readline()
		pha2 = string.strip(pha2)
		try:
			pha2=int(pha2)
			if pha2>0 and pha2<=len(lst):
				pha2=pha2-1
				hserv=lst[pha2]
				return hserv
			print Col["red"],"Invalid!",Col["0"]

		except:
			print Col["red"],"Invalid!",Col["0"]	
			pha2=0


#
############# START ########################
#

try:
	print "\033[2J\033[0;0H\n"
	print Col["blue"]+" OnionMail"+Col["blue"]+" account wizard"+Col["green"]+" Ver "+CONF['version']+Col["0"]
	print "\t"+Col["blue"]+"(C) 2014-2015 OnionMail Project & "+Col["cyan"]+"mes3hacklab"+Col["0"]+"\n"

	pha2=0
	pha1=len(sys.argv)-1
	for idx in range(len(sys.argv)):
		par=sys.argv[idx]
		if pha2!=0:
			continue

		if par == "-q":
			CONF['requestw']=0

		if par == "-g":
			CONF['mkgpg']=0

		if par == "-t":
			CONF['conftor']=0	

		if par == "-tr":
			CONF['fretor']=1

		if par == "-c":
			CONF['clawsmail']=""

		if par == "-d":
			CONF['debug']=1

		if par == "-ar":
			CONF['autorave']=0

		if par == "+ar":
			CONF['autorave']=1

		if par == "-nk":
			CONF['deksreload']=""

		if par == "-gi":
			gnomeIcon(0)

		if par == "-gir":
			gnomeIcon(1)

		if par == "-Q":
			sys.exit(0)

		if par == "-tip":
			if idx == pha1:
				print "Syntax error"
				sys.exit(1)

			pha2=argv[idx+1]
			x = re.compile("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
			if x.match(pha2) == "":
				print Col["red"]+"Invalid TOR IP address"+Col["0"]
				sys.exit(1)
			CONF["torip"]=pha2
			pha2=1
			CONF['conftor']=0
			
		if par == "-tp":
			if idx == pha1:
				print "Syntax error"
				sys.exit(1)
			pha2=argv[idx+1]
			x = re.compile("[0-9]{1,5}")
			if x.match(pha2) == "":
				print Col["red"]+"Invalid TOR Port"+Col["0"]
				sys.exit(1)
			CONF["torport"]=int(pha2)
			pha2=1		
			CONF['conftor']=0

		if par == "-dl":
			print "Available distro configurations:"
			for dist in distros:
				print "\t"+dist['d']	

			print ""
			sys.exit(0)		

		if par == "-h" or par == "-?":
			print " Usage:\n\tonionmail-wizard [-q] [-g] [-t] [-c] [-d]"
			print "\t\t\t [-tip <TorIP>] [-tp <TorPort>] [-tr] [-dl] [-gi]"
			print "\t\t\t [-u <user>] [-uh <home>] [-gir] [-Q] [-nk] [-ar|+ar]\n"
			print "  -q\tRun the wizard without user prompt."
			print "  -g\tDo not create any GPG keys."
			print "  -t\tUse default TOR configuration: "+CONF["torip"]+":"+str(CONF["torport"])
			print "  -c\tDon't start Claws-Mail."
			print "  -tip\tSet the TOR SOCKS IP address."
			print "  -tp\tSet the TOR SOCKS Port."
			print "  -tr\tForce TOR to restart before run the wizard."
			print "  -dl\tList the supported distro configurations and exit."
			print "  -gi\tInstall the torified claws-mail icon on Desktop."
			print "  -nk\tDo not reset gnome-panel."
			print "  -ar\tDo not use AutoRave."
			print "  +ar\tUse AutoRave."
			print "  -Q\tDon't run the wizard and exit."
			print " Options: (only root user)"
			print "  -gir\tInstall the menu icon."
			print "  -uh\tSet home dir."
			print "  -u\tSet the user."
			print "  -h\tSet the user's home path."
			print "  -d\tEnable the debug mode (print the exception on error).\n"
			sys.exit(0) # Non devo eliminare alcun tmp!

	if not os.path.isdir(CONF['rnd']):
		try:
			os.mkdir(CONF['rnd'])
			CONF['tempath']=CONF['rnd']
		except:
			CONF['rnd']=""
	
	os.system("stty echo")
	os.system(CONF['clawsexit'])
	
	print Col["cyan"]+"This program will subscribe/configure your OnionMail on Claws-Mail client."+Col["0"]
	print Col["blue"]+"Use this wizard only with Claws-Mail client."+Col["0"]
	print "\n"

	getdistro()	
	if CONF['conftor'] == 1:
		getTORConfig()

	if not os.path.isfile(CONF['opensslelf']):
		print "\n"+Col["oyellow"]+"Warning: "+Col["red"]+"This wizard requires openssl"+Col["0"]
		print Col["cyan"]+"Can't configure SSL certificates automatically"+Col["0"]
		print "Press enter to continue\n"
		pha2 = sys.stdin.readline()

	for elf in CONF["reqelf"]:
		pha2=0
		if not os.path.isfile(elf['b']):
			print "\n"+Col["ored"]+"Warning: "+Col["red"]+"This wizard requires "+elf['p']+Col["0"]
			print Col["cyan"]+"Please install "+elf['p']+" first!"+Col["0"]
			print "\trun:\n\t# "+CONF['apt'].replace("%X%",elf['p'])+"\n"
			pha2=1

		if pha2==1:
			print "Press enter to exit\n"
			pha2 = sys.stdin.readline()
			endProc(0)

	if CONF['requestw']==1:
		print Col["purple"]+"\nDo wou want to automatically configure your onion/mailbox now?"+Col["0"]
		print "\t"+Col["purple"]+"(Y)"+Col["0"],"=",Col["cyan"]+"Yes"+Col["0"]
		print "\t"+Col["purple"]+"(N)"+Col["0"],"=",Col["cyan"]+"No"+Col["0"]
	
		while 1:
			print Col["purple"]+"\t>"+Col["0"],
			pha2 = sys.stdin.readline()
			print ""
			pha2 = string.strip(pha2)
			pha2 = string.lower(pha2)
			if pha2=="y":
				break
	
			if pha2=="n":
				print "\033[2J\033[0;0H\n"
				print Col["green"]+"Ok, Goodbye"+Col["0"],"\n"
				endProc(1)

	if CONF['fretor'] == 1:
		print Col["cyan"] + " Reset tor ..."+Col["0"]
		p = subprocess.Popen(CONF['retor']+"> /dev/null", shell=True)
		if p.wait()!=0:
			print Col["red"]+"Can't reatart TOR"+Col["0"]
		time.sleep( 10 )
		print Col["cyan"] + "Done!!!"+Col["0"]+"\n"

	CONF['complflg']=1
	print "\033[2J\033[0;0H\n"
	print Col["cyan"],"\nRunning setup wizard:\n",Col["0"]

	print Col["cyan"],"Importing my PGP key...",Col["0"]
	importmypgp()
	print "\t",Col["blue"],"Done!!!",Col["0"]
	###

	print Col["cyan"],"Checking important files...",Col["0"]

	CONF['ctarprofile']=""
	CONF['ctarmail']=""
	
	for inf in [ 'tarprofile', 'tarmail']:
		for pox in [ CONF['cwd'] , CONF['tarlib'] ]:
			fp = pox+"/"+CONF[inf]
			if os.path.isfile(fp):
				CONF['c'+inf]=fp
				break
			
		if CONF['c'+inf] == "":
			print Col["purple"],"Download ",CONF[inf]," ... "+Col["0"]
			download(CONF[inf],CONF['tempath'])
			print "\t",Col["blue"],"Done!!!"+Col["0"]
			CONF['c'+inf] = CONF['tempath']+"/"+CONF[inf]
	
	print "\n",Col["purple"],"Download OnionMail servers'status list...",Col["0"]
	download(CONF['list'],CONF['tempath'])
	print "\t",Col["blue"],"Done!!!",Col["0"]
	CONF['clist']=CONF['tempath']+"/"+CONF['list']

	if not os.path.isfile(CONF['ctarprofile']) or not os.path.isfile(CONF['ctarmail']) or not os.path.isfile(CONF['clist']):
	    ferro("There is a lack of important files. Maybe you lost some part of the program.")

	print Col["cyan"],"Ok\n\tReady to go..."+Col["purple"]+"\tBegin configuration wizard.\n"+Col["0"]
	
	inittheclaws()
	while 1:
		srv = serverlist()
		try:
			print "\033[2J\033[0;0H"+Col["cyan"]+"Connecting to "+Col["green"]+srv["nick"]+Col["0"]+"\n"
			onionmail(srv["onion"],srv["nick"])
			break

		except PException:
			print Col["red"] + "Error occurred on "+Col["yellow"]+srv["nick"]+Col["red"]+" server"
			print Col["purple"] + "Press enter to try another server."+Col["0"]
			pha2 = sys.stdin.readline()
			os.system("stty echo")

		except KeyboardInterrupt:
			print Col["ored"] + " Interrupted by user "+Col["0"]
			print Col["red"] + "Some operations maybe incomplete!"+Col["0"]
			print "\nServer operations interrupted."
			print "Press enter to back server list, Press CTRL+C to end wizard\n"
			pha2 = sys.stdin.readline()
			os.system("stty echo")
			
		except Exception as E:
			print Col["red"] + "Error occurred in application"
			print Col["purple"] + "Press enter to try another server."+Col["0"]
			if CONF["debug"]==1:
				print type(E)
				print E.args
				print E
				print traceback.format_exc()

			pha2 = sys.stdin.readline()
			os.system("stty echo")

except KeyboardInterrupt:
	print Col["ored"] + " Interrupted by user "+Col["0"]
	print Col["red"] + "Some operations maybe incomplete!"+Col["0"]
	print "\nWizard aborted.\n"
	os.system("stty echo")
	print Col["purple"] + "Press enter to exit."+Col["0"]
	pha2 = sys.stdin.readline()
	os.chdir(startpath)
	endProc(1)

except Exception as E:
	if not CONF['complflg']==0:
		print Col["ored"] + "Application fatal error!"+Col["0"]
		print Col["red"] + "Some operations maybe incomplete!"+Col["0"]
	print "\nWizard aborted.\n"
	os.system("stty echo")
	print Col["purple"] + "Press enter to exit."+Col["0"]
	pha2 = sys.stdin.readline()
	os.chdir(startpath)
	if CONF["debug"]==1:
		print type(E)
		print E.args
		print E
		print traceback.format_exc()
	endProc(1)
		

