summaryrefslogtreecommitdiffstats
path: root/src/otrplugin.cpp
blob: 323ee4472014c8eaa517b75f5cb15b3e830ae342 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/***************************************************************************
 *   Copyright (C) 2007 by Michael Zanetti                                 *
 *                                                                         *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/

#include <tqstylesheet.h>
#include <tqtimer.h>
#include <tqregexp.h>
#include <tqfile.h>
#include <tqcolor.h>

#include <kdebug.h>
#include <kaction.h>
#include <kactionclasses.h>
#include <kpopupmenu.h>
#include <kconfig.h>
#include <kgenericfactory.h>
#include <kdeversion.h>
#include <kaboutdata.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>

#include <kopetemetacontact.h>
#include <kopetecontactlist.h>
#include <kopetechatsessionmanager.h>
#include <kopetesimplemessagehandler.h>
#include <kopeteuiglobal.h>
#include <kopetecontact.h>
#include <kopetemessage.h>
#include <kopeteaccount.h>
#include <kopeteaccountmanager.h>
#include <kopetemessageevent.h>
#include <kopeteprotocol.h>

#include "otrplugin.h"
#include "otrguiclient.h"
#include "otrlchatinterface.h"
#include "kopete_otr.h"

/**
  * @author Michael Zanetti
  */



typedef KGenericFactory<OTRPlugin> OTRPluginFactory;
static const KAboutData aboutdata("kopete_otr", I18N_NOOP("OTR") , "0.7" );
K_EXPORT_COMPONENT_FACTORY( kopete_otr, OTRPluginFactory( &aboutdata )  )

OTRPlugin::OTRPlugin( TQObject *tqparent, const char *name, const TQStringList & /* args */ )
: Kopete::Plugin( OTRPluginFactory::instance(), tqparent, name )
{
	if( !pluginStatic_ )
		pluginStatic_=this;
	
	m_inboundHandler = new OtrMessageHandlerFactory(this);

	connect( Kopete::ChatSessionManager::self(), TQT_SIGNAL( aboutToSend( Kopete::Message & ) ),
		TQT_SLOT( slotOutgoingMessage( Kopete::Message & ) ) );
//	connect( Kopete::ChatSessionManager::self(), TQT_SIGNAL( aboutToDisplay( Kopete::Message & ) ),
//		this, TQT_SLOT( slotIncomingMessage( Kopete::Message & ) ) );

	connect( Kopete::ChatSessionManager::self(), TQT_SIGNAL( chatSessionCreated( Kopete::ChatSession * ) ),
			 this, TQT_SLOT( slotNewChatSessionWindow( Kopete::ChatSession * ) ) );
	TQObject::connect( this, TQT_SIGNAL( settingsChanged() ), this, TQT_SLOT( slotSettingsChanged() ) );



	//initialize the otrlib and create the interface object
	otrlChatInterface = OtrlChatInterface::self();

	//update key files when an account is ready to use
	if( TQFile::exists( TQString( KGlobal::dirs()->saveLocation( "data", "kopete_otr/", true ) ) + "privkey" ) &&
		!TQFile::exists( TQString( KGlobal::dirs()->saveLocation( "data", "kopete_otr/", true ) ) + "privkeys" ) ){
		kdDebug() << "Detected old format keyfile. Doing updates!" << endl;
		kdDebug() << "Reading old keyfile..." << endl;
		TQFile fpold( TQString(KGlobal::dirs()->saveLocation("data", "kopete_otr/", true )) + "privkey" );
		TQString line;
		TQString file;
		if( fpold.open( IO_ReadWrite ) ){
			while( fpold.readLine( line, 100 ) != -1){
				file.append( line );
			}
		}
		kdDebug() << "Writing new keyfile" << endl;
		TQFile fpnew( TQString(KGlobal::dirs()->saveLocation("data", "kopete_otr/", true )) + "privkeys" );
		fpnew.open( IO_ReadWrite );
		fpnew.writeBlock( file.latin1(), file.length() );
		fpnew.close();
		kdDebug() << "Writing backup for old keyfile" << endl;
		TQFile fpbup( TQString(KGlobal::dirs()->saveLocation("data", "kopete_otr/", true )) + "privkey.old" );
		fpbup.open( IO_ReadWrite );
		fpbup.writeBlock( file.latin1(), file.length() );
		fpbup.close();
		kdDebug() << "Deleting old keyfile" << endl;
		fpold.remove();

		kdDebug() << "Reading old fingerprintsfile..." << endl;
		TQFile fpfingerprintsold( TQString(KGlobal::dirs()->saveLocation("data", "kopete_otr/", true )) + "fingerprints" );
		line = "";
		file = "";
		if( fpfingerprintsold.open( IO_ReadWrite ) ){
			while( fpfingerprintsold.readLine( line, 100 ) != -1){
				file.append( line );
			}
		}
		kdDebug() << "Writing backup for old fingerprintsfile" << endl;
		TQFile fpfingerprintsbup( TQString(KGlobal::dirs()->saveLocation("data", "kopete_otr/", true )) + "fingerprints.old" );
		fpfingerprintsbup.open( IO_ReadWrite );
		fpfingerprintsbup.writeBlock( file.latin1(), file.length() );
		fpfingerprintsbup.close();

		kdDebug() << "Waiting for accounts to update keyfile format" << endl;
		connect( Kopete::AccountManager::self(), TQT_SIGNAL( accountRegistered( Kopete::Account * ) ),
			this, TQT_SLOT( accountReady( Kopete::Account * ) ) );
	}

	// Checking file Permissions
	OtrlChatInterface::self()->checkFilePermissions( TQString( KGlobal::dirs()->saveLocation( "data", "kopete_otr/", true ) ) + "privkeys" );
	OtrlChatInterface::self()->checkFilePermissions( TQString( KGlobal::dirs()->saveLocation( "data", "kopete_otr/", true ) ) + "fingerprints" );
	// Check also file permissions for eventuallly old beckup files
	OtrlChatInterface::self()->checkFilePermissions( TQString( KGlobal::dirs()->saveLocation( "data", "kopete_otr/", true ) ) + "privkey.old" );
	OtrlChatInterface::self()->checkFilePermissions( TQString( KGlobal::dirs()->saveLocation( "data", "kopete_otr/", true ) ) + "fingerprints.old" );

	//setting the policy
	slotSettingsChanged();

	//adding menu to contaclists menubar and contacts popup menu
	TQStringList policies;
	policies << i18n("&Default") << i18n("Al&ways") << i18n("&Opportunistic") << i18n("&Manual") << i18n("Ne&ver");
	otrPolicyMenu = new KSelectAction( i18n( "&OTR Policy" ), TQString::tqfromLatin1("kopete_otr"), 0, actionCollection(), "otr_policy" );
	otrPolicyMenu->setItems( policies );
	otrPolicyMenu->popupMenu()->insertSeparator( 1 );
	otrPolicyMenu->setEnabled( false );
	connect( otrPolicyMenu, TQT_SIGNAL( activated() ), this, TQT_SLOT( slotSetPolicy() ) );
	connect( Kopete::ContactList::self(), TQT_SIGNAL( metaContactSelected( bool ) ), this, TQT_SLOT( slotSelectionChanged( bool ) ) );


	setXMLFile( "otrui.rc" );



	//Add GUI action to all already existing kmm 
	// (if the plugin is launched when kopete already runing)
	TQValueList<Kopete::ChatSession*> sessions =
		 Kopete::ChatSessionManager::self()->sessions();
	TQValueListIterator<Kopete::ChatSession*> it;
	for (it= sessions.begin(); it!=sessions.end() ; ++it){
	  	slotNewChatSessionWindow( *it );
	}
}

OTRPlugin::~OTRPlugin()
{
	delete m_inboundHandler;
	pluginStatic_ = 0L;
	kdDebug() << "Exiting plugin" << endl;
}


OTRPlugin* OTRPlugin::plugin()
{
	return pluginStatic_ ;
}

OTRPlugin* OTRPlugin::pluginStatic_ = 0L;


void OTRPlugin::slotNewChatSessionWindow( Kopete::ChatSession *KMM )
{
	//Check if there is another user in the session.
	//If not it could be a Jabber-MUC
	//If there are more then one members it is a MUC
	// Also don't add the Button on an IRC window!
	if( KMM->members().count() == 1 && (KMM->protocol()) && ( KMM->protocol()->pluginId() != "IRCProtocol" ) ){
		new OtrGUIClient( KMM );
	}
}


void OTRPlugin::slotOutgoingMessage( Kopete::Message& msg )
{
	if( msg.direction() == Kopete::Message::Outbound ){
		TQString plainBody = msg.plainBody();
		TQString accountId = msg.manager()->account()->accountId();
		Kopete::Contact *contact = msg.to().first();
		
		TQString encBody = otrlChatInterface->encryptMessage( plainBody, accountId, msg.manager()->account()->protocol()->displayName(), contact->contactId(), msg.manager() );
		msg.setBody( encBody, Kopete::Message::Crypted );
		if( !msg.plainBody().isEmpty() ){
			messageCache.insert( encBody, plainBody  );
		}
	}
}

void  OTRPlugin::slotEnableOtr( Kopete::ChatSession *session, bool enable ){


	if( enable ){
		TQString policy = session->members().getFirst()->metaContact()->pluginData( OTRPlugin::plugin(), "otr_policy" );
		bool noerr;
		KopeteOtrKcfg::self()->readConfig();
		if( policy.toInt( &noerr, 10 ) == 4 || ( policy.toInt( &noerr, 10 ) == 0 && KopeteOtrKcfg::self()->rbNever() ) ){
			Kopete::Message msg(  session->account()->myself(), session->members(), i18n( "Your policy settings do not allow encrypted sessions to this contact." ), Kopete::Message::Internal, Kopete::Message::RichText );
			session->appendMessage( msg );
		} else {
			TQString body = otrlChatInterface->getDefaultQuery( session->account()->accountId() );
			Kopete::Message msg1( session->account()->myself(), session->members().getFirst(), TQString( body ), Kopete::Message::Outbound );
			if( otrlChatInterface->privState( session ) > 0 ){
				body = i18n("Attempting to refresh the OTR session with <b>%1</b>...").tqarg( otrlChatInterface->formatContact( session->members().getFirst()->contactId() ) );
			} else {
				body = i18n("Attempting to start a private OTR session with <b>%1</b>...").tqarg( otrlChatInterface->formatContact( session->members().getFirst()->contactId() ) );				
			}
			Kopete::Message msg2( session->account()->myself(), session->members().getFirst(), body, Kopete::Message::Internal, Kopete::Message::RichText );

			session->sendMessage( msg1 );
			session->appendMessage( msg2 );
		}
	} else {
		otrlChatInterface->disconnectSession( session );
	}

}

void OTRPlugin::slotVerifyFingerprint( Kopete::ChatSession *session ){
	otrlChatInterface->verifyFingerprint( session );
}

void OTRPlugin::slotSettingsChanged(){
	KopeteOtrKcfg::self()->readConfig();
	if( KopeteOtrKcfg::self()->rbAlways() ){
		otrlChatInterface->setPolicy( OTRL_POLICY_ALWAYS );
	} else if( KopeteOtrKcfg::self()->rbOpportunistic() ){
		otrlChatInterface->setPolicy( OTRL_POLICY_OPPORTUNISTIC );
	} else if( KopeteOtrKcfg::self()->rbManual() ){
		otrlChatInterface->setPolicy( OTRL_POLICY_MANUAL );
	} else if( KopeteOtrKcfg::self()->rbNever() ){
		otrlChatInterface->setPolicy( OTRL_POLICY_NEVER );
	} else {
		otrlChatInterface->setPolicy( OTRL_POLICY_DEFAULT );
	}
}

void OTRPlugin::emitGoneSecure( Kopete::ChatSession *session, int status){
	emit goneSecure( session, status );
}

TQMap<TQString, TQString> OTRPlugin::getMessageCache(){
	return messageCache;
}

void OtrMessageHandler::handleMessage( Kopete::MessageEvent *event ){
	Kopete::Message msg = event->message();
	Kopete::ChatSession *session = msg.manager();
	TQMap<TQString, TQString> messageCache = OTRPlugin::plugin()->getMessageCache();
	
	if( msg.direction() == Kopete::Message::Inbound ){
		TQString body = msg.parsedBody();
kdDebug() << "Received Message: " << msg.parsedBody() << endl;
		TQString accountId = msg.manager()->account()->accountId();
		TQString contactId = msg.from()->contactId();
		int ignoremessage = OtrlChatInterface::self()->decryptMessage( &body, accountId, msg.manager()->account()->protocol()->displayName(), contactId, msg.manager() );
		msg.setBody( body, Kopete::Message::RichText );
		if( ignoremessage | OtrlChatInterface::self()->shouldDiscard( msg.plainBody() ) ){
			event->discard();
			return;
		}
	} else if( msg.direction() == Kopete::Message::Outbound ){
		if( messageCache.tqcontains( msg.plainBody() ) ){
			msg.setBody( messageCache[msg.plainBody()] );
			messageCache.remove( messageCache[msg.plainBody()] );
			if(messageCache.count() > 5) messageCache.clear();
		}
		// Check if Message is an OTR message. Should it be discarded or shown?
		if( OtrlChatInterface::self()->shouldDiscard( msg.plainBody() ) ){
			event->discard();
			kdDebug() << "discarding" << endl;
			return;
		}
		// If the message is sent while a Finished state libotr deletes the messagetext.
		// This prevents the empty message from beeing shown in out chatwindow
		if( msg.plainBody().isEmpty() ){
			event->discard();
			return;
		}
	}
	
	event->setMessage( msg );

	MessageHandler::handleMessage( event );
}


void OTRPlugin::slotSelectionChanged( bool single){
	otrPolicyMenu->setEnabled( single );

	if ( !single )
		return;

	Kopete::MetaContact *metaContact = Kopete::ContactList::self()->selectedMetaContacts().first();

	TQString policy = metaContact->pluginData( this, "otr_policy" );

	bool noerr;
	if ( !policy.isEmpty() && policy != "null" )
		otrPolicyMenu->setCurrentItem( policy.toInt( &noerr, 10 ));
	else
		otrPolicyMenu->setCurrentItem( 0 );

}

void OTRPlugin::slotSetPolicy(){
	kdDebug() << "Setting contact policy" << endl;
	Kopete::MetaContact *metaContact = Kopete::ContactList::self()->selectedMetaContacts().first();
	if( metaContact ){
		metaContact->setPluginData( this, "otr_policy", TQString::number( otrPolicyMenu->currentItem() ) );		
	}
}

void OTRPlugin::accountReady( Kopete::Account *account ){
	kdDebug() << "Account " << account->accountId() << " ready. Calling update function."<< endl;
	otrlChatInterface->updateKeyfile( account );
}


#include "otrplugin.moc"

// vim: set noet ts=4 sts=4 sw=4: