JingleConnection.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import java.util.ArrayList;
  4import java.util.HashMap;
  5import java.util.Iterator;
  6import java.util.List;
  7import java.util.Map.Entry;
  8
  9import android.util.Log;
 10
 11import eu.siacs.conversations.entities.Account;
 12import eu.siacs.conversations.entities.Conversation;
 13import eu.siacs.conversations.entities.Message;
 14import eu.siacs.conversations.services.XmppConnectionService;
 15import eu.siacs.conversations.xml.Element;
 16import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 17import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
 18import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 19import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
 20import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 21
 22public class JingleConnection {
 23
 24	private JingleConnectionManager mJingleConnectionManager;
 25	private XmppConnectionService mXmppConnectionService;
 26	
 27	public static final int STATUS_INITIATED = 0;
 28	public static final int STATUS_ACCEPTED = 1;
 29	public static final int STATUS_TERMINATED = 2;
 30	public static final int STATUS_CANCELED = 3;
 31	public static final int STATUS_FINISHED = 4;
 32	public static final int STATUS_TRANSMITTING = 5;
 33	public static final int STATUS_FAILED = 99;
 34	
 35	private int status = -1;
 36	private Message message;
 37	private String sessionId;
 38	private Account account;
 39	private String initiator;
 40	private String responder;
 41	private List<JingleCandidate> candidates = new ArrayList<JingleCandidate>();
 42	private HashMap<String, SocksConnection> connections = new HashMap<String, SocksConnection>();
 43	
 44	private String transportId;
 45	private Element fileOffer;
 46	private JingleFile file = null;
 47	
 48	private boolean receivedCandidate = false;
 49	private boolean sentCandidate = false;
 50	
 51	private JingleTransport transport = null;
 52	
 53	private OnIqPacketReceived responseListener = new OnIqPacketReceived() {
 54		
 55		@Override
 56		public void onIqPacketReceived(Account account, IqPacket packet) {
 57			if (packet.getType() == IqPacket.TYPE_ERROR) {
 58				mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 59				status = STATUS_FAILED;
 60			}
 61		}
 62	};
 63	
 64	final OnFileTransmitted onFileTransmitted = new OnFileTransmitted() {
 65		
 66		@Override
 67		public void onFileTransmitted(JingleFile file) {
 68			if (responder.equals(account.getFullJid())) {
 69				sendSuccess();
 70				mXmppConnectionService.markMessage(message, Message.STATUS_RECIEVED);
 71			}
 72			Log.d("xmppService","sucessfully transmitted file. sha1:"+file.getSha1Sum());
 73		}
 74	};
 75	
 76	private OnProxyActivated onProxyActivated = new OnProxyActivated() {
 77		
 78		@Override
 79		public void success() {
 80			if (initiator.equals(account.getFullJid())) {
 81				Log.d("xmppService","we were initiating. sending file");
 82				transport.send(file,onFileTransmitted);
 83			} else {
 84				transport.receive(file,onFileTransmitted);
 85				Log.d("xmppService","we were responding. receiving file");
 86			}
 87		}
 88		
 89		@Override
 90		public void failed() {
 91			Log.d("xmppService","proxy activation failed");
 92		}
 93	};
 94	
 95	public JingleConnection(JingleConnectionManager mJingleConnectionManager) {
 96		this.mJingleConnectionManager = mJingleConnectionManager;
 97		this.mXmppConnectionService = mJingleConnectionManager.getXmppConnectionService();
 98	}
 99	
100	public String getSessionId() {
101		return this.sessionId;
102	}
103	
104	public String getAccountJid() {
105		return this.account.getFullJid();
106	}
107	
108	public String getCounterPart() {
109		return this.message.getCounterpart();
110	}
111	
112	public void deliverPacket(JinglePacket packet) {
113		
114		if (packet.isAction("session-terminate")) {
115			Reason reason = packet.getReason();
116			if (reason!=null) {
117				if (reason.hasChild("cancel")) {
118					this.cancel();
119				} else if (reason.hasChild("success")) {
120					this.finish();
121				}
122			} else {
123				Log.d("xmppService","remote terminated for no reason");
124				this.cancel();
125			}
126			} else if (packet.isAction("session-accept")) {
127			accept(packet);
128		} else if (packet.isAction("transport-info")) {
129			transportInfo(packet);
130		} else {
131			Log.d("xmppService","packet arrived in connection. action was "+packet.getAction());
132		}
133	}
134	
135	public void init(Message message) {
136		this.message = message;
137		this.account = message.getConversation().getAccount();
138		this.initiator = this.account.getFullJid();
139		this.responder = this.message.getCounterpart();
140		this.sessionId = this.mJingleConnectionManager.nextRandomId();
141		if (this.candidates.size() > 0) {
142			this.sendInitRequest();
143		} else {
144			this.mJingleConnectionManager.getPrimaryCandidate(account, new OnPrimaryCandidateFound() {
145				
146				@Override
147				public void onPrimaryCandidateFound(boolean success, final JingleCandidate candidate) {
148					if (success) {
149						final SocksConnection socksConnection = new SocksConnection(JingleConnection.this, candidate);
150						connections.put(candidate.getCid(), socksConnection);
151						socksConnection.connect(new OnSocksConnection() {
152							
153							@Override
154							public void failed() {
155								Log.d("xmppService","connection to our own primary candidete failed");
156								sendInitRequest();
157							}
158							
159							@Override
160							public void established() {
161								Log.d("xmppService","succesfully connected to our own primary candidate");
162								mergeCandidate(candidate);
163								sendInitRequest();
164							}
165						});
166						mergeCandidate(candidate);
167					} else {
168						Log.d("xmppService","no primary candidate of our own was found");
169						sendInitRequest();
170					}
171				}
172			});
173		}
174		
175	}
176	
177	public void init(Account account, JinglePacket packet) {
178		this.status = STATUS_INITIATED;
179		Conversation conversation = this.mXmppConnectionService.findOrCreateConversation(account, packet.getFrom().split("/")[0], false);
180		this.message = new Message(conversation, "receiving image file", Message.ENCRYPTION_NONE);
181		this.message.setType(Message.TYPE_IMAGE);
182		this.message.setStatus(Message.STATUS_RECIEVING);
183		String[] fromParts = packet.getFrom().split("/");
184		this.message.setPresence(fromParts[1]);
185		this.account = account;
186		this.initiator = packet.getFrom();
187		this.responder = this.account.getFullJid();
188		this.sessionId = packet.getSessionId();
189		Content content = packet.getJingleContent();
190		this.transportId = content.getTransportId();
191		this.mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
192		this.fileOffer = packet.getJingleContent().getFileOffer();
193		if (fileOffer!=null) {
194			this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message);
195			Element fileSize = fileOffer.findChild("size");
196			Element fileName = fileOffer.findChild("name");
197			this.file.setExpectedSize(Long.parseLong(fileSize.getContent()));
198			conversation.getMessages().add(message);
199			this.mXmppConnectionService.databaseBackend.createMessage(message);
200			if (this.mXmppConnectionService.convChangedListener!=null) {
201				this.mXmppConnectionService.convChangedListener.onConversationListChanged();
202			}
203			if (this.file.getExpectedSize()<=this.mJingleConnectionManager.getAutoAcceptFileSize()) {
204				Log.d("xmppService","auto accepting file from "+packet.getFrom());
205				this.sendAccept();
206			} else {
207				Log.d("xmppService","not auto accepting new file offer with size: "+this.file.getExpectedSize()+" allowed size:"+this.mJingleConnectionManager.getAutoAcceptFileSize());
208			}
209		} else {
210			Log.d("xmppService","no file offer was attached. aborting");
211		}
212	}
213	
214	private void sendInitRequest() {
215		JinglePacket packet = this.bootstrapPacket("session-initiate");
216		Content content = new Content();
217		if (message.getType() == Message.TYPE_IMAGE) {
218			content.setAttribute("creator", "initiator");
219			content.setAttribute("name", "a-file-offer");
220			content.setTransportId(this.transportId);
221			this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message);
222			content.setFileOffer(this.file);
223			this.transportId = this.mJingleConnectionManager.nextRandomId();
224			content.setTransportId(this.transportId);
225			content.socks5transport().setChildren(getCandidatesAsElements());
226			packet.setContent(content);
227			this.sendJinglePacket(packet);
228			this.status = STATUS_INITIATED;
229		}
230	}
231	
232	private List<Element> getCandidatesAsElements() {
233		List<Element> elements = new ArrayList<Element>();
234		for(JingleCandidate c : this.candidates) {
235			elements.add(c.toElement());
236		}
237		return elements;
238	}
239	
240	private void sendAccept() {
241		status = STATUS_ACCEPTED;
242		this.mJingleConnectionManager.getPrimaryCandidate(this.account, new OnPrimaryCandidateFound() {
243			
244			@Override
245			public void onPrimaryCandidateFound(boolean success,final JingleCandidate candidate) {
246				final JinglePacket packet = bootstrapPacket("session-accept");
247				final Content content = new Content();
248				content.setFileOffer(fileOffer);
249				content.setTransportId(transportId);
250				if ((success)&&(!equalCandidateExists(candidate))) {
251					final SocksConnection socksConnection = new SocksConnection(JingleConnection.this, candidate);
252					connections.put(candidate.getCid(), socksConnection);
253					socksConnection.connect(new OnSocksConnection() {
254						
255						@Override
256						public void failed() {
257							Log.d("xmppService","connection to our own primary candidate failed");
258							content.socks5transport().setChildren(getCandidatesAsElements());
259							packet.setContent(content);
260							sendJinglePacket(packet);
261							connectNextCandidate();
262						}
263						
264						@Override
265						public void established() {
266							Log.d("xmppService","connected to primary candidate");
267							mergeCandidate(candidate);
268							content.socks5transport().setChildren(getCandidatesAsElements());
269							packet.setContent(content);
270							sendJinglePacket(packet);
271							connectNextCandidate();
272						}
273					});
274				} else {
275					Log.d("xmppService","did not find a primary candidate for ourself");
276					content.socks5transport().setChildren(getCandidatesAsElements());
277					packet.setContent(content);
278					sendJinglePacket(packet);
279					connectNextCandidate();
280				}
281			}
282		});
283		
284	}
285	
286	private JinglePacket bootstrapPacket(String action) {
287		JinglePacket packet = new JinglePacket();
288		packet.setAction(action);
289		packet.setFrom(account.getFullJid());
290		packet.setTo(this.message.getCounterpart());
291		packet.setSessionId(this.sessionId);
292		packet.setInitiator(this.initiator);
293		return packet;
294	}
295	
296	private void sendJinglePacket(JinglePacket packet) {
297		//Log.d("xmppService",packet.toString());
298		account.getXmppConnection().sendIqPacket(packet,responseListener);
299	}
300	
301	private void accept(JinglePacket packet) {
302		Content content = packet.getJingleContent();
303		mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
304		this.status = STATUS_ACCEPTED;
305		this.connectNextCandidate();
306		IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
307		account.getXmppConnection().sendIqPacket(response, null);
308	}
309
310	private void transportInfo(JinglePacket packet) {
311		Content content = packet.getJingleContent();
312		if (content.hasSocks5Transport()) {
313			if (content.socks5transport().hasChild("activated")) {
314				onProxyActivated.success();
315			} else if (content.socks5transport().hasChild("activated")) {
316				onProxyActivated.failed();
317			} else if (content.socks5transport().hasChild("candidate-error")) {
318				Log.d("xmppService","received candidate error");
319				this.receivedCandidate = true;
320				if (status == STATUS_ACCEPTED) {
321					this.connect();
322				}
323			} else if (content.socks5transport().hasChild("candidate-used")){
324				String cid = content.socks5transport().findChild("candidate-used").getAttribute("cid");
325				if (cid!=null) {
326					Log.d("xmppService","candidate used by counterpart:"+cid);
327					JingleCandidate candidate = getCandidate(cid);
328					candidate.flagAsUsedByCounterpart();
329					this.receivedCandidate = true;
330					if ((status == STATUS_ACCEPTED)&&(this.sentCandidate)) {
331						this.connect();
332					} else {
333						Log.d("xmppService","ignoring because file is already in transmission or we havent sent our candidate yet");
334					}
335				} else {
336					Log.d("xmppService","couldn't read used candidate");
337				}
338			} else {
339				Log.d("xmppService","empty transport");
340			}
341		}
342		
343		IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
344		account.getXmppConnection().sendIqPacket(response, null);
345	}
346
347	private void connect() {
348		final SocksConnection connection = chooseConnection();
349		this.transport = connection;
350		if (connection==null) {
351			Log.d("xmppService","could not find suitable candidate");
352			this.disconnect();
353			this.status = STATUS_FAILED;
354			this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_FAILED);
355		} else {
356			this.status = STATUS_TRANSMITTING;
357			if (connection.isProxy()) {
358				if (connection.getCandidate().isOurs()) {
359					Log.d("xmppService","candidate "+connection.getCandidate().getCid()+" was our proxy and needs activation");
360					IqPacket activation = new IqPacket(IqPacket.TYPE_SET);
361					activation.setTo(connection.getCandidate().getJid());
362					activation.query("http://jabber.org/protocol/bytestreams").setAttribute("sid", this.getSessionId());
363					activation.query().addChild("activate").setContent(this.getCounterPart());
364					this.account.getXmppConnection().sendIqPacket(activation, new OnIqPacketReceived() {
365						
366						@Override
367						public void onIqPacketReceived(Account account, IqPacket packet) {
368							if (packet.getType()==IqPacket.TYPE_ERROR) {
369								onProxyActivated.failed();
370							} else {
371								onProxyActivated.success();
372								sendProxyActivated(connection.getCandidate().getCid());
373							}
374						}
375					});
376				}
377			} else {
378				if (initiator.equals(account.getFullJid())) {
379					Log.d("xmppService","we were initiating. sending file");
380					connection.send(file,onFileTransmitted);
381				} else {
382					Log.d("xmppService","we were responding. receiving file");
383					connection.receive(file,onFileTransmitted);
384				}
385			}
386		}
387	}
388	
389	private SocksConnection chooseConnection() {
390		SocksConnection connection = null;
391		Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
392	    while (it.hasNext()) {
393	    	Entry<String, SocksConnection> pairs = it.next();
394	    	SocksConnection currentConnection = pairs.getValue();
395	    	//Log.d("xmppService","comparing candidate: "+currentConnection.getCandidate().toString());
396	        if (currentConnection.isEstablished()&&(currentConnection.getCandidate().isUsedByCounterpart()||(!currentConnection.getCandidate().isOurs()))) {
397	        	//Log.d("xmppService","is usable");
398	        	if (connection==null) {
399	        		connection = currentConnection;
400	        	} else {
401	        		if (connection.getCandidate().getPriority()<currentConnection.getCandidate().getPriority()) {
402	        			connection = currentConnection;
403	        		} else if (connection.getCandidate().getPriority()==currentConnection.getCandidate().getPriority()) {
404	        			//Log.d("xmppService","found two candidates with same priority");
405	        			if (initiator.equals(account.getFullJid())) {
406	        				if (currentConnection.getCandidate().isOurs()) {
407	        					connection = currentConnection;
408	        				}
409	        			} else {
410	        				if (!currentConnection.getCandidate().isOurs()) {
411	        					connection = currentConnection;
412	        				}
413	        			}
414	        		}
415	        	}
416	        }
417	        it.remove();
418	    }
419		return connection;
420	}
421
422	private void sendSuccess() {
423		JinglePacket packet = bootstrapPacket("session-terminate");
424		Reason reason = new Reason();
425		reason.addChild("success");
426		packet.setReason(reason);
427		this.sendJinglePacket(packet);
428		this.disconnect();
429		this.status = STATUS_FINISHED;
430		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_RECIEVED);
431	}
432	
433	private void finish() {
434		this.status = STATUS_FINISHED;
435		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND);
436		this.disconnect();
437	}
438	
439	public void cancel() {
440		this.disconnect();
441		this.status = STATUS_CANCELED;
442		this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_REJECTED);
443	}
444
445	private void connectNextCandidate() {
446		for(JingleCandidate candidate : this.candidates) {
447			if ((!connections.containsKey(candidate.getCid())&&(!candidate.isOurs()))) {
448				this.connectWithCandidate(candidate);
449				return;
450			}
451		}
452		this.sendCandidateError();
453	}
454	
455	private void connectWithCandidate(final JingleCandidate candidate) {
456		final SocksConnection socksConnection = new SocksConnection(this,candidate);
457		connections.put(candidate.getCid(), socksConnection);
458		socksConnection.connect(new OnSocksConnection() {
459			
460			@Override
461			public void failed() {
462				Log.d("xmppService", "connection failed with "+candidate.getHost()+":"+candidate.getPort());
463				connectNextCandidate();
464			}
465			
466			@Override
467			public void established() {
468				Log.d("xmppService", "established connection with "+candidate.getHost()+":"+candidate.getPort());
469				sendCandidateUsed(candidate.getCid());
470			}
471		});
472	}
473
474	private void disconnect() {
475		Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
476	    while (it.hasNext()) {
477	        Entry<String, SocksConnection> pairs = it.next();
478	        pairs.getValue().disconnect();
479	        it.remove();
480	    }
481	}
482	
483	private void sendProxyActivated(String cid) {
484		JinglePacket packet = bootstrapPacket("transport-info");
485		Content content = new Content("inititaor","a-file-offer");
486		content.setTransportId(this.transportId);
487		content.socks5transport().addChild("activated").setAttribute("cid", cid);
488		packet.setContent(content);
489		this.sendJinglePacket(packet);
490	}
491	
492	private void sendCandidateUsed(final String cid) {
493		JinglePacket packet = bootstrapPacket("transport-info");
494		Content content = new Content("initiator","a-file-offer");
495		content.setTransportId(this.transportId);
496		content.socks5transport().addChild("candidate-used").setAttribute("cid", cid);
497		packet.setContent(content);
498		this.sentCandidate = true;
499		if ((receivedCandidate)&&(status == STATUS_ACCEPTED)) {
500			connect();
501		}
502		this.sendJinglePacket(packet);
503	}
504	
505	private void sendCandidateError() {
506		JinglePacket packet = bootstrapPacket("transport-info");
507		Content content = new Content("initiator","a-file-offer");
508		content.setTransportId(this.transportId);
509		content.socks5transport().addChild("candidate-error");
510		packet.setContent(content);
511		this.sentCandidate = true;
512		if ((receivedCandidate)&&(status == STATUS_ACCEPTED)) {
513			connect();
514		}
515		this.sendJinglePacket(packet);
516	}
517
518	public String getInitiator() {
519		return this.initiator;
520	}
521	
522	public String getResponder() {
523		return this.responder;
524	}
525	
526	public int getStatus() {
527		return this.status;
528	}
529	
530	private boolean equalCandidateExists(JingleCandidate candidate) {
531		for(JingleCandidate c : this.candidates) {
532			if (c.equalValues(candidate)) {
533				return true;
534			}
535		}
536		return false;
537	}
538	
539	private void mergeCandidate(JingleCandidate candidate) {
540		for(JingleCandidate c : this.candidates) {
541			if (c.equals(candidate)) {
542				return;
543			}
544		}
545		this.candidates.add(candidate);
546	}
547	
548	private void mergeCandidates(List<JingleCandidate> candidates) {
549		for(JingleCandidate c : candidates) {
550			mergeCandidate(c);
551		}
552	}
553	
554	private JingleCandidate getCandidate(String cid) {
555		for(JingleCandidate c : this.candidates) {
556			if (c.getCid().equals(cid)) {
557				return c;
558			}
559		}
560		return null;
561	}
562	
563	interface OnProxyActivated {
564		public void success();
565		public void failed();
566	}
567}