index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/AbstractSoundManagerFactory.java
package net.sourceforge.peers.media; public interface AbstractSoundManagerFactory { AbstractSoundManager getSoundManager(); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/Capture.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2008, 2009, 2010, 2011 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.IOException; import java.io.InterruptedIOException; import java.io.PipedOutputStream; import java.util.concurrent.CountDownLatch; import net.sourceforge.peers.Logger; public class Capture implements Runnable { public static final int SAMPLE_SIZE = 16; public static final int BUFFER_SIZE = SAMPLE_SIZE * 20; private PipedOutputStream rawData; private boolean isStopped; private SoundSource soundSource; private Logger logger; private CountDownLatch latch; public Capture(PipedOutputStream rawData, SoundSource soundSource, Logger logger, CountDownLatch latch) { this.rawData = rawData; this.soundSource = soundSource; this.logger = logger; this.latch = latch; isStopped = false; } public void run() { byte[] buffer; try { while (!isStopped) { buffer = soundSource.readData(); if (buffer == null) { break; } int maxWaitForWriteMS = (buffer.length / RtpSender.CONSUMING_BYTES_PER_MS) + 1000; // plus 1 sec to be on the safe size long startWrite = System.currentTimeMillis(); // TODO solve problem about never being able to write the data provided by the SoundSource // if the provided byte-array is bigger than the max-capacity of rawData (CaptureRtpSender.PIPE_SIZE) while (true) { try { rawData.write(buffer); break; } catch (InterruptedIOException e) { // PipedOutputStream only has 1 sec (hardcoded) patience to be able to write, so if the byte-arrays // provided by soundSource is big enough we may get in trouble. Lets way at least for the time a well // running RtpSender could use consuming the bytes we want to write. Only after that, throw the exception if ((System.currentTimeMillis() - startWrite) > maxWaitForWriteMS) throw e; } } rawData.flush(); } } catch (IOException e) { logger.error("Error writing raw data", e); } finally { try { rawData.close(); } catch (IOException e) { logger.error("Error closing raw data output pipe", e); } latch.countDown(); if (latch.getCount() != 0) { try { latch.await(); } catch (InterruptedException e) { logger.error("interrupt exception", e); } } } } public synchronized void setStopped(boolean isStopped) { this.isStopped = isStopped; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/CaptureRtpSender.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.concurrent.CountDownLatch; import net.sourceforge.peers.Logger; import net.sourceforge.peers.rtp.RFC3551; import net.sourceforge.peers.rtp.RtpSession; import net.sourceforge.peers.sdp.Codec; public class CaptureRtpSender { public static final int PIPE_SIZE = 16384; private RtpSession rtpSession; private Capture capture; private Encoder encoder; private RtpSender rtpSender; public CaptureRtpSender(RtpSession rtpSession, SoundSource soundSource, boolean mediaDebug, Codec codec, Logger logger, String peersHome) throws IOException { super(); this.rtpSession = rtpSession; // the use of PipedInputStream and PipedOutputStream in Capture, // Encoder and RtpSender imposes a synchronization point at the // end of life of those threads to a void read end dead exceptions CountDownLatch latch = new CountDownLatch(3); PipedOutputStream rawDataOutput = new PipedOutputStream(); PipedInputStream rawDataInput; try { rawDataInput = new PipedInputStream(rawDataOutput, PIPE_SIZE); } catch (IOException e) { logger.error("input/output error", e); return; } PipedOutputStream encodedDataOutput = new PipedOutputStream(); PipedInputStream encodedDataInput; try { encodedDataInput = new PipedInputStream(encodedDataOutput, PIPE_SIZE); } catch (IOException e) { logger.error("input/output error"); rawDataInput.close(); return; } capture = new Capture(rawDataOutput, soundSource, logger, latch); String cannotProducePayloadReason = null; switch (codec.getPayloadType()) { case RFC3551.PAYLOAD_TYPE_PCMU: if (soundSource.dataProduced() == SoundSource.DataFormat.LINEAR_PCM_8KHZ_16BITS_SIGNED_MONO_LITTLE_ENDIAN) { encoder = new PcmuEncoder(rawDataInput, encodedDataOutput, mediaDebug, logger, peersHome, latch); } else { cannotProducePayloadReason = "Cannot convert " + soundSource.dataProduced().getDescription() + " to PCMU"; } break; case RFC3551.PAYLOAD_TYPE_PCMA: if (soundSource.dataProduced() == SoundSource.DataFormat.LINEAR_PCM_8KHZ_16BITS_SIGNED_MONO_LITTLE_ENDIAN) { encoder = new PcmaEncoder(rawDataInput, encodedDataOutput, mediaDebug, logger, peersHome, latch); } else if (soundSource.dataProduced() == SoundSource.DataFormat.ALAW_8KHZ_MONO_LITTLE_ENDIAN) { encoder = new NoEncodingEncoder(rawDataInput, encodedDataOutput, mediaDebug, logger, peersHome, latch); } else { cannotProducePayloadReason = "Cannot convert " + soundSource.dataProduced().getDescription() + " to PCMA"; } break; default: cannotProducePayloadReason = "unknown payload type"; } if (cannotProducePayloadReason != null) { encodedDataInput.close(); rawDataInput.close(); throw new RuntimeException(cannotProducePayloadReason); } rtpSender = new RtpSender(encodedDataInput, rtpSession, mediaDebug, codec, logger, peersHome, latch); } public void start() throws IOException { capture.setStopped(false); encoder.setStopped(false); rtpSender.setStopped(false); Thread captureThread = new Thread(capture, Capture.class.getSimpleName()); Thread encoderThread = new Thread(encoder, Encoder.class.getSimpleName()); Thread rtpSenderThread = new Thread(rtpSender, RtpSender.class.getSimpleName()); captureThread.start(); encoderThread.start(); rtpSenderThread.start(); } public void stop() { if (rtpSender != null) { rtpSender.setStopped(true); } if (encoder != null) { encoder.setStopped(true); } if (capture != null) { capture.setStopped(true); } } public synchronized RtpSession getRtpSession() { return rtpSession; } public RtpSender getRtpSender() { return rtpSender; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/ConfigAbstractSoundManagerFactory.java
package net.sourceforge.peers.media; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.javaxsound.JavaxSoundManager; public class ConfigAbstractSoundManagerFactory implements AbstractSoundManagerFactory { private Config config; private String peersHome; private Logger logger; public ConfigAbstractSoundManagerFactory(Config config, String peersHome, Logger logger) { this.config = config; this.peersHome = peersHome; this.logger = logger; } @Override public AbstractSoundManager getSoundManager() { switch (config.getMediaMode()) { case captureAndPlayback: return new JavaxSoundManager(config.isMediaDebug(), logger, peersHome); case echo: return null; case file: return new FilePlaybackSoundManager(config.getMediaFile(), config.getMediaFileDataFormat(), logger); case none: default: return null; } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/Decoder.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.media; public abstract class Decoder { public abstract byte[] process(byte[] media); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/DtmfDecoder.java
package net.sourceforge.peers.media; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.rtp.RtpPacket; public class DtmfDecoder { private DtmfEventHandler handler; private RFC4733.DTMFEvent lastDtmfEvent; private int lastDuration; private int lastVolume; public DtmfDecoder(DtmfEventHandler handler){ this.handler = handler; lastDuration = -1; } public void processPacket(RtpPacket packet) { if(packet.getPayloadType() != RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT) { throw new RuntimeException("Decoder only supports payloads of type " + RFC4733.TELEPHONE_EVENT); } if((packet.getData() == null) || (packet.getData().length != 4)) { throw new RuntimeException(("Only RFC4733 formatted DTMF supported (Unsupported datalength, " + packet.getData().length + " bytes)")); } if(((packet.getData()[1] >> 7) & 1) == 1) { //End bit is set int duration = (((packet.getData()[2] & 0xff) << 8) | (packet.getData()[1] & 0xff)); if(duration != 0) { //RFC4733 states that events with zero duration must be ignored RFC4733.DTMFEvent dtmfEvent = RFC4733.DTMFEvent.fromValue(packet.getData()[0]); int volume = (packet.getData()[1] & 0x3f); if((duration != lastDuration) || (dtmfEvent != lastDtmfEvent) || (lastVolume != volume)) { //The RFC states that the end packet SHOULD be sent a total of three times. //It does not say MUST, so to be flexible, the DTMF event is acknowledged on the first end event, //and further end events are ignored. lastDtmfEvent = dtmfEvent; lastDuration = duration; lastVolume = volume; handler.dtmfDetected(dtmfEvent, duration); } } } else { //Reset "same as last" detector lastDuration = -1; } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/DtmfEventHandler.java
package net.sourceforge.peers.media; import net.sourceforge.peers.rtp.RFC4733; public interface DtmfEventHandler { public void dtmfDetected(RFC4733.DTMFEvent dtmfEvent, int duration); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/DtmfFactory.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.media; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.rtp.RtpPacket; import java.util.ArrayList; import java.util.List; public class DtmfFactory { public List<RtpPacket> createDtmfPackets(char digit) { List<RtpPacket> packets = new ArrayList<RtpPacket>(); byte[] data = new byte[4]; // RFC4733 if (digit == '*') { data[0] = 10; } else if (digit == '#') { data[0] = 11; } else if (digit >= 'A' && digit <= 'D') { data[0] = (byte) (digit - 53); } else { data[0] = (byte) (digit - 48); } data[1] = 10; // volume 10 // Set Duration to 160 // duration 8 bits data[2] = 0; // duration 8 bits data[3] = -96; RtpPacket rtpPacket = new RtpPacket(); rtpPacket.setData(data); rtpPacket.setPayloadType(RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT); rtpPacket.setMarker(true); packets.add(rtpPacket); // two classical packets rtpPacket = new RtpPacket(); // set duration to 320 data = data.clone(); data[2] = 1; data[3] = 64; rtpPacket.setData(data); rtpPacket.setIncrementTimeStamp(false); rtpPacket.setMarker(false); rtpPacket.setPayloadType(RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT); packets.add(rtpPacket); rtpPacket = new RtpPacket(); // set duration to 320 data = data.clone(); data[2] = 1; data[3] = -32; rtpPacket.setData(data); rtpPacket.setIncrementTimeStamp(false); rtpPacket.setMarker(false); rtpPacket.setPayloadType(RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT); packets.add(rtpPacket); data = data.clone(); // create three end event packets data[1] = -0x76; // end event flag + volume set to 10 // set Duration to 640 data[2] = 2; // duration 8 bits data[3] = -128; // duration 8 bits for (int r = 0; r < 3; r++) { rtpPacket = new RtpPacket(); rtpPacket.setData(data); rtpPacket.setMarker(false); if(r > 0) { rtpPacket.setIncrementTimeStamp(false); } rtpPacket.setPayloadType(RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT); packets.add(rtpPacket); } return packets; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/Echo.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2009, 2010, 2012 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import net.sourceforge.peers.Logger; public class Echo implements Runnable { public static final int BUFFER_SIZE = 2048; private DatagramSocket datagramSocket; private InetAddress remoteAddress; private int remotePort; private boolean isRunning; private Logger logger; public Echo(DatagramSocket datagramSocket, String remoteAddress, int remotePort, Logger logger) throws UnknownHostException { this.datagramSocket = datagramSocket; this.remoteAddress = InetAddress.getByName(remoteAddress); this.remotePort = remotePort; this.logger = logger; isRunning = true; } @Override public void run() { try { while (isRunning) { byte[] buf = new byte[BUFFER_SIZE]; DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); try { datagramSocket.receive(datagramPacket); } catch (SocketTimeoutException e) { logger.debug("echo socket timeout"); continue; } datagramPacket = new DatagramPacket(buf, datagramPacket.getLength(), remoteAddress, remotePort); datagramSocket.send(datagramPacket); } } catch (IOException e) { logger.error("input/output error", e); } finally { datagramSocket.close(); } } public synchronized void stop() { isRunning = false; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/Encoder.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2008, 2009, 2010, 2011 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.CountDownLatch; import net.sourceforge.peers.Logger; public abstract class Encoder implements Runnable { private PipedInputStream rawData; private PipedOutputStream encodedData; private boolean isStopped; private FileOutputStream encoderOutput; private FileOutputStream encoderInput; private boolean mediaDebug; private Logger logger; private String peersHome; private CountDownLatch latch; public Encoder(PipedInputStream rawData, PipedOutputStream encodedData, boolean mediaDebug, Logger logger, String peersHome, CountDownLatch latch) { this.rawData = rawData; this.encodedData = encodedData; this.mediaDebug = mediaDebug; this.logger = logger; this.peersHome = peersHome; this.latch = latch; isStopped = false; } public void run() { try { int buf_size = Capture.BUFFER_SIZE; byte[] buffer = new byte[buf_size]; int numBytesRead; int tempBytesRead; if (mediaDebug) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String date = simpleDateFormat.format(new Date()); String dir = peersHome + File.separator + AbstractSoundManager.MEDIA_DIR + File.separator; String fileName = dir + date + "_g711_encoder.output"; try { encoderOutput = new FileOutputStream(fileName); fileName = dir + date + "_g711_encoder.input"; encoderInput = new FileOutputStream(fileName); } catch (FileNotFoundException e) { logger.error("cannot create file", e); return; } } //int ready; while (!isStopped || rawDataAvailable() > 0) { numBytesRead = 0; try { while (numBytesRead < buf_size) { // expect that the buffer is full tempBytesRead = rawData.read(buffer, numBytesRead, buf_size - numBytesRead); if (tempBytesRead < 0) { setStopped(true); break; } numBytesRead += tempBytesRead; } if (mediaDebug) { try { encoderInput.write(buffer, 0, numBytesRead); } catch (IOException e) { logger.error("cannot write to file", e); } } } catch (IOException e) { // Getting an IOException reading from rawData is expected after the encoder has been stopped if (!isStopped) logger.error("Error reading raw data", e); } byte[] encodedBuffer = process(buffer, numBytesRead); if (mediaDebug) { try { encoderOutput.write(encodedBuffer); } catch (IOException e) { logger.error("cannot write to file", e); } } try { encodedData.write(encodedBuffer); encodedData.flush(); } catch (IOException e) { logger.error("Error writing encoded data", e); } } } finally { if (mediaDebug) { try { encoderOutput.close(); encoderInput.close(); } catch (IOException e) { logger.error("cannot close file", e); } } try { rawData.close(); } catch (IOException e) { logger.error("Error closing raw data input pipe", e); } try { encodedData.close(); } catch (IOException e) { logger.error("Error closing encoded data output pipe", e); } latch.countDown(); if (latch.getCount() != 0) { try { latch.await(); } catch (InterruptedException e) { logger.error("interrupt exception", e); } } } } public synchronized void setStopped(boolean isStopped) { this.isStopped = isStopped; } public abstract byte[] process(byte[] media, int len); private int rawDataAvailable() { try { return rawData.available(); } catch (IOException e) { // PipedInputStream.available never throws IOException in practice logger.error("Error getting amount available raw data. Should never happen", e); return 0; } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/FilePlaybackSoundManager.java
package net.sourceforge.peers.media; import net.sourceforge.peers.Logger; public class FilePlaybackSoundManager extends AbstractSoundManager { private String fileName; private DataFormat fileDataFormat; private Logger logger; private FileReader fileReader; public FilePlaybackSoundManager(String fileName, DataFormat fileDataFormat, Logger logger) { this.fileName = fileName; this.fileDataFormat = fileDataFormat; this.logger = logger; } @Override public void init() { fileReader = new FileReader(fileName, fileDataFormat, logger); } @Override public void close() { if (fileReader != null) fileReader.close(); } @Override public int writeData(byte[] buffer, int offset, int length) { return 0; } @Override public DataFormat dataProduced() { return fileDataFormat; } @Override public byte[] readData() { return fileReader.readData(); } @Override public boolean finished() { return fileReader.finished(); } @Override public void waitFinished() throws InterruptedException { fileReader.waitFinished(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/FileReader.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2012 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import net.sourceforge.peers.Logger; // To create an audio file for peers, you can use audacity: // // Edit > Preferences // // - Peripherals // - Channels: 1 (Mono) // - Quality // - Sampling frequency of default: 8000 Hz // - Default Sample Format: 16 bits // // Validate // // Record audio // // File > Export // // - File type: AIFF (Apple) signed 16-bit PCM, File name: test.raw // - or, File type: Other uncompressed files, Header: RAW (header-less), Encoding: A-law, File name: test.alaw // // Validate public class FileReader implements SoundSource { public final static int BUFFER_SIZE = 256; private Object finishedSync = new Object(); private FileInputStream fileInputStream; private DataFormat fileDataFormat; private Logger logger; public FileReader(String fileName, DataFormat fileDataFormat, Logger logger) { this.logger = logger; try { fileInputStream = new FileInputStream(fileName); } catch (FileNotFoundException e) { logger.error("file not found: " + fileName, e); } this.fileDataFormat = fileDataFormat; } public synchronized void close() { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { logger.error("io exception", e); } fileInputStream = null; synchronized (finishedSync) { finishedSync.notifyAll(); } } } @Override public DataFormat dataProduced() { return (fileDataFormat != null)?fileDataFormat:DataFormat.DEFAULT; } @Override public synchronized byte[] readData() { if (fileInputStream == null) { return null; } byte buffer[] = new byte[BUFFER_SIZE]; try { int read; if ((read = fileInputStream.read(buffer)) >= 0) { // TODO There is a problem if not the entire buffer was filled. That is not communicated to the reader of the returned byte-array if (read < buffer.length) System.out.println("Buffer was not completely filled, but we are sending it all through anyway"); return buffer; } else { close(); } } catch (IOException e) { logger.error("io exception", e); } return null; } @Override public boolean finished() { return fileInputStream == null; } @Override public void waitFinished() throws InterruptedException { if (!finished()) { synchronized (finishedSync) { while (!finished()) { finishedSync.wait(); } } } return; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/IncomingRtpReader.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.IOException; import net.sourceforge.peers.Logger; import net.sourceforge.peers.rtp.*; import net.sourceforge.peers.sdp.Codec; public class IncomingRtpReader implements RtpListener { private RtpSession rtpSession; private AbstractSoundManager soundManager; private Decoder decoder; private DtmfDecoder dtmfDecoder; public IncomingRtpReader(RtpSession rtpSession, AbstractSoundManager soundManager, Codec codec, DtmfEventHandler dtmfHandler, Logger logger) throws IOException { logger.debug("playback codec:" + codec.toString().trim()); this.rtpSession = rtpSession; this.soundManager = soundManager; switch (codec.getPayloadType()) { case RFC3551.PAYLOAD_TYPE_PCMU: decoder = new PcmuDecoder(); break; case RFC3551.PAYLOAD_TYPE_PCMA: decoder = new PcmaDecoder(); break; default: throw new RuntimeException("unsupported payload type"); } dtmfDecoder = new DtmfDecoder(dtmfHandler); rtpSession.addRtpListener(this); } public void start() { rtpSession.start(); } @Override public void receivedRtpPacket(RtpPacket rtpPacket) { if(rtpPacket.getPayloadType() == RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT) { dtmfDecoder.processPacket(rtpPacket); } else { byte[] rawBuf = decoder.process(rtpPacket.getData()); if (soundManager != null) { soundManager.writeData(rawBuf, 0, rawBuf.length); } } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/MediaManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers.media; import net.sourceforge.peers.Logger; import net.sourceforge.peers.rtp.RtpPacket; import net.sourceforge.peers.rtp.RtpSession; import net.sourceforge.peers.sdp.Codec; import net.sourceforge.peers.sip.core.useragent.UserAgent; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; public class MediaManager { public static final int DEFAULT_CLOCK = 8000; // Hz private UserAgent userAgent; private Object connectedSync = new Object(); private CaptureRtpSender captureRtpSender; private IncomingRtpReader incomingRtpReader; private RtpSession rtpSession; private DtmfFactory dtmfFactory; private Logger logger; private DatagramSocket datagramSocket; private AbstractSoundManager soundManager; private DtmfEventHandler dtmfEventHandler; public MediaManager(UserAgent userAgent, DtmfEventHandler dtmfEventHandler, Logger logger) { this.userAgent = userAgent; this.dtmfEventHandler = dtmfEventHandler; this.logger = logger; dtmfFactory = new DtmfFactory(); } private void setCaptureRtpSender(CaptureRtpSender captureRtpSender) { this.captureRtpSender = captureRtpSender; synchronized (connectedSync) { connectedSync.notifyAll(); } } public CaptureRtpSender getCaptureRtpSender() { return captureRtpSender; } private void startRtpSessionOnSuccessResponse(String localAddress, String remoteAddress, int remotePort, Codec codec, SoundSource soundSource) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(localAddress); } catch (UnknownHostException e) { logger.error("unknown host: " + localAddress, e); return; } rtpSession = new RtpSession(inetAddress, datagramSocket, userAgent.isMediaDebug(), logger, userAgent.getPeersHome()); try { inetAddress = InetAddress.getByName(remoteAddress); rtpSession.setRemoteAddress(inetAddress); } catch (UnknownHostException e) { logger.error("unknown host: " + remoteAddress, e); } rtpSession.setRemotePort(remotePort); try { setCaptureRtpSender(new CaptureRtpSender(rtpSession, soundSource, userAgent.isMediaDebug(), codec, logger, userAgent.getPeersHome())); } catch (IOException e) { logger.error("input/output error", e); return; } try { captureRtpSender.start(); } catch (IOException e) { logger.error("input/output error", e); } } public void successResponseReceived(String localAddress, String remoteAddress, int remotePort, Codec codec) { switch (userAgent.getMediaMode()) { case captureAndPlayback: case file: if (soundManager != null) { soundManager.close(); } soundManager = userAgent.getAbstractSoundManagerFactory().getSoundManager(); soundManager.init(); startRtpSessionOnSuccessResponse(localAddress, remoteAddress, remotePort, codec, soundManager); try { incomingRtpReader = new IncomingRtpReader( captureRtpSender.getRtpSession(), soundManager, codec, dtmfEventHandler, logger); } catch (IOException e) { logger.error("input/output error", e); return; } incomingRtpReader.start(); break; case echo: Echo echo; try { echo = new Echo(datagramSocket, remoteAddress, remotePort, logger); } catch (UnknownHostException e) { logger.error("unknown host amongst " + localAddress + " or " + remoteAddress); return; } userAgent.setEcho(echo); Thread echoThread = new Thread(echo, Echo.class.getSimpleName()); echoThread.start(); break; case none: default: break; } } private void startRtpSession(String destAddress, int destPort, Codec codec, SoundSource soundSource) { rtpSession = new RtpSession(userAgent.getConfig() .getLocalInetAddress(), datagramSocket, userAgent.isMediaDebug(), logger, userAgent.getPeersHome()); try { InetAddress inetAddress = InetAddress.getByName(destAddress); rtpSession.setRemoteAddress(inetAddress); } catch (UnknownHostException e) { logger.error("unknown host: " + destAddress, e); } rtpSession.setRemotePort(destPort); try { setCaptureRtpSender(new CaptureRtpSender(rtpSession, soundSource, userAgent.isMediaDebug(), codec, logger, userAgent.getPeersHome())); } catch (IOException e) { logger.error("input/output error", e); return; } try { captureRtpSender.start(); } catch (IOException e) { logger.error("input/output error", e); } } public void handleAck(String destAddress, int destPort, Codec codec) { switch (userAgent.getMediaMode()) { case captureAndPlayback: case file: if (soundManager != null) { soundManager.close(); } soundManager = userAgent.getAbstractSoundManagerFactory().getSoundManager(); soundManager.init(); startRtpSession(destAddress, destPort, codec, soundManager); try { //FIXME RTP sessions can be different ! incomingRtpReader = new IncomingRtpReader(rtpSession, soundManager, codec, dtmfEventHandler, logger); } catch (IOException e) { logger.error("input/output error", e); return; } incomingRtpReader.start(); break; case echo: Echo echo; try { echo = new Echo(datagramSocket, destAddress, destPort, logger); } catch (UnknownHostException e) { logger.error("unknown host amongst " + userAgent.getConfig().getLocalInetAddress() .getHostAddress() + " or " + destAddress); return; } userAgent.setEcho(echo); Thread echoThread = new Thread(echo, Echo.class.getSimpleName()); echoThread.start(); break; case none: default: break; } } public void updateRemote(String destAddress, int destPort, Codec codec) { switch (userAgent.getMediaMode()) { case captureAndPlayback: case file: try { InetAddress inetAddress = InetAddress.getByName(destAddress); rtpSession.setRemoteAddress(inetAddress); } catch (UnknownHostException e) { logger.error("unknown host: " + destAddress, e); } rtpSession.setRemotePort(destPort); break; case echo: //TODO update echo socket break; default: break; } } public void sendDtmf(char digit) { if (connected()) { List<RtpPacket> rtpPackets = dtmfFactory.createDtmfPackets(digit); RtpSender rtpSender = captureRtpSender.getRtpSender(); rtpSender.pushPackets(rtpPackets); } } public void stopSession() { if (rtpSession != null) { rtpSession.stop(); while (!rtpSession.isSocketClosed()) { try { Thread.sleep(15); } catch (InterruptedException e) { logger.debug("sleep interrupted"); } } rtpSession = null; } if (incomingRtpReader != null) { incomingRtpReader = null; } if (captureRtpSender != null) { captureRtpSender.stop(); setCaptureRtpSender(null); } if (datagramSocket != null) { datagramSocket = null; } switch (userAgent.getMediaMode()) { case captureAndPlayback: case file: if (soundManager != null) { soundManager.close(); } break; case echo: Echo echo = userAgent.getEcho(); if (echo != null) { echo.stop(); userAgent.setEcho(null); } break; default: break; } } public void setDatagramSocket(DatagramSocket datagramSocket) { this.datagramSocket = datagramSocket; } public DatagramSocket getDatagramSocket() { return datagramSocket; } public SoundSource getSoundSource() { switch (userAgent.getMediaMode()) { case captureAndPlayback: case file: return soundManager; case echo: default: return null; } } public boolean connected() { return captureRtpSender != null; } public void waitConnected() throws InterruptedException { if (!connected()) { synchronized (connectedSync) { while (!connected()) { connectedSync.wait(); } } } return; } public void waitFinishedSending() throws IOException, InterruptedException { if (connected()) { captureRtpSender.getRtpSender().waitEmpty(); } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/MediaMode.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.media; public enum MediaMode { none, captureAndPlayback, echo, file }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/NoEncodingEncoder.java
package net.sourceforge.peers.media; import net.sourceforge.peers.Logger; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.concurrent.CountDownLatch; public class NoEncodingEncoder extends Encoder { public NoEncodingEncoder(PipedInputStream rawData, PipedOutputStream encodedData, boolean mediaDebug, Logger logger, String peersHome, CountDownLatch latch) { super(rawData, encodedData, mediaDebug, logger, peersHome, latch); } @Override public byte[] process(byte[] media, int len) { return media; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/PcmaDecoder.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Oleg Kulikov, Yohann Martineau */ package net.sourceforge.peers.media; public class PcmaDecoder extends Decoder { private static short aLawDecompressTable[] = new short[]{ -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016, -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88, -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344, 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848 }; @Override public byte[] process(byte[] media) { byte[] res = new byte[media.length * 2]; int j = 0; for (int i = 0; i < media.length; i++) { short s = aLawDecompressTable[media[i] & 0xff]; res[j++] = (byte) s; res[j++] = (byte) (s >> 8); } return res; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/PcmaEncoder.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010, 2011 Oleg Kulikov, Yohann Martineau */ package net.sourceforge.peers.media; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.concurrent.CountDownLatch; import net.sourceforge.peers.Logger; public class PcmaEncoder extends Encoder { private final static int cClip = 32635; private static byte aLawCompressTable[] = new byte[]{ 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; public PcmaEncoder(PipedInputStream rawData, PipedOutputStream encodedData, boolean mediaDebug, Logger logger, String peersHome, CountDownLatch latch) { super(rawData, encodedData, mediaDebug, logger, peersHome, latch); } @Override public byte[] process(byte[] media, int len) { byte[] compressed = new byte[len / 2]; int j = 0; for (int i = 0; i < compressed.length; i++) { short sample = (short) (((media[j++] & 0xff) | (media[j++]) << 8)); compressed[i] = linearToALawSample(sample); } return compressed; } /** * Compress 16bit value to 8bit value * * @param sample 16-bit sample * @return compressed 8-bit value. */ private byte linearToALawSample(short sample) { int sign; int exponent; int mantissa; int s; sign = ((~sample) >> 8) & 0x80; if (!(sign == 0x80)) { sample = (short) -sample; } if (sample > cClip) { sample = cClip; } if (sample >= 256) { exponent = (int) aLawCompressTable[(sample >> 8) & 0x7F]; mantissa = (sample >> (exponent + 3)) & 0x0F; s = (exponent << 4) | mantissa; } else { s = sample >> 4; } s ^= (sign ^ 0x55); return (byte) s; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/PcmuDecoder.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Oleg Kulikov, Yohann Martineau */ package net.sourceforge.peers.media; public class PcmuDecoder extends Decoder { // private final static int cBias = 0x84; // private int QUANT_MASK = 0xf; // private final static int SEG_SHIFT = 4; // private final static int SEG_MASK = 0x70; // private final static int SIGN_BIT = 0x80; private static short muLawDecompressTable[] = new short[]{ -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372, -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, 844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0 }; @Override public byte[] process(byte[] media) { byte[] res = new byte[media.length * 2]; int j = 0; for (int i = 0; i < media.length; i++) { short s = muLawDecompressTable[media[i] & 0xff]; res[j++] = (byte) s; res[j++] = (byte) (s >> 8); } return res; } //TODO compare what's the fastest: table lookup or real conversion /* * ulaw2linear() - Convert a u-law value to 16-bit linear PCM * * First, a biased linear code is derived from the code word. An unbiased * output can then be obtained by subtracting 33 from the biased code. * * Note that this function expects to be passed the complement of the * original code word. This is in keeping with ISDN conventions. */ // private short ulaw2linear(byte u_val) { // int t; // // /* Complement to obtain normal u-law value. */ // u_val = (byte) ~u_val; // // /* // * Extract and bias the quantization bits. Then // * shift up by the segment number and subtract out the bias. // */ // t = ((u_val & QUANT_MASK) << 3) + cBias; // t <<= (u_val & SEG_MASK) >> SEG_SHIFT; // // boolean s = (u_val & SIGN_BIT) == SIGN_BIT; // return (short) (s ? (cBias - t) : (t - cBias)); // } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/PcmuEncoder.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010, 2011 Oleg Kulikov, Yohann Martineau */ package net.sourceforge.peers.media; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.concurrent.CountDownLatch; import net.sourceforge.peers.Logger; public class PcmuEncoder extends Encoder { private final static int cBias = 0x84; private final static short seg_end[] = new short[]{0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF }; /* * linear2ulaw() - Convert a linear PCM value to u-law * * In order to simplify the encoding process, the original linear magnitude * is biased by adding 33 which shifts the encoding range from (0 - 8158) to * (33 - 8191). The result can be seen in the following encoding table: * * Biased Linear Input Code Compressed Code * ------------------------ --------------- * 00000001wxyza 000wxyz * 0000001wxyzab 001wxyz * 000001wxyzabc 010wxyz * 00001wxyzabcd 011wxyz * 0001wxyzabcde 100wxyz * 001wxyzabcdef 101wxyz * 01wxyzabcdefg 110wxyz * 1wxyzabcdefgh 111wxyz * * Each biased linear code has a leading 1 which identifies the segment * number. The value of the segment number is equal to 7 minus the number * of leading 0's. The quantization interval is directly available as the * four bits wxyz. * The trailing bits (a - h) are ignored. * * Ordinarily the complement of the resulting code word is used for * transmission, and so the code word is complemented before it is returned. * * For further information see John C. Bellamy's Digital Telephony, 1982, * John Wiley & Sons, pps 98-111 and 472-476. */ private static byte linear2ulaw(short pcm_val) { int mask; int seg; byte uval; /* Get the sign and the magnitude of the value. */ if (pcm_val < 0) { pcm_val = (short) (cBias - pcm_val); mask = 0x7F; } else { pcm_val += cBias; mask = 0xFF; } /* Convert the scaled magnitude to segment number. */ seg = search(pcm_val, seg_end, 8); /* * Combine the sign, segment, quantization bits; * and complement the code word. */ if (seg >= 8) /* out of range, return maximum value. */ { return (byte)(0x7F ^ mask); } else { uval = (byte)((seg << 4) | ((pcm_val >> (seg + 3)) & 0xF)); return (byte)(uval ^ mask); } } private static int search(int val, short[] table, int size) { int i; for (i = 0; i < size; i++) { if (val <= table[i]) { return (i); } } return (size); } public PcmuEncoder(PipedInputStream rawData, PipedOutputStream encodedData, boolean mediaDebug, Logger logger, String peersHome, CountDownLatch latch) { super(rawData, encodedData, mediaDebug, logger, peersHome, latch); } /** * Perform compression using U-law. Retrieved from Mobicents media server * code. * * @param media the input uncompressed media * @return the output compressed media. */ @Override public byte[] process(byte[] media, int len) { byte[] compressed = new byte[len / 2]; int j = 0; for (int i = 0; i < compressed.length; i++) { short sample = (short) ((media[j++] & 0xff) | ((media[j++]) << 8)); compressed[i] = linear2ulaw(sample); } return compressed; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/RtpSender.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2008, 2009, 2010, 2011 Yohann Martineau */ package net.sourceforge.peers.media; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.CountDownLatch; import net.sourceforge.peers.Logger; import net.sourceforge.peers.rtp.RFC3551; import net.sourceforge.peers.rtp.RtpPacket; import net.sourceforge.peers.rtp.RtpSession; import net.sourceforge.peers.sdp.Codec; public class RtpSender implements Runnable { private static int BUF_SIZE = Capture.BUFFER_SIZE / 2; public static int CONSUMING_BYTES_PER_MS = BUF_SIZE / 20; // Consuming BUF_SIZE bytes every 20 ms private PipedInputStream encodedData; private RtpSession rtpSession; private boolean isStopped; private Object pauseSync; private boolean isPaused; private FileOutputStream rtpSenderInput; private boolean mediaDebug; private Codec codec; private List<RtpPacket> pushedPackets; private Logger logger; private String peersHome; private CountDownLatch latch; public RtpSender(PipedInputStream encodedData, RtpSession rtpSession, boolean mediaDebug, Codec codec, Logger logger, String peersHome, CountDownLatch latch) { this.encodedData = encodedData; this.rtpSession = rtpSession; this.mediaDebug = mediaDebug; this.codec = codec; this.peersHome = peersHome; this.latch = latch; this.logger = logger; isStopped = false; pauseSync = new Object(); isPaused = false; pushedPackets = Collections.synchronizedList( new ArrayList<RtpPacket>()); } public void run() { try { if (mediaDebug) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String date = simpleDateFormat.format(new Date()); String fileName = peersHome + File.separator + AbstractSoundManager.MEDIA_DIR + File.separator + date + "_rtp_sender.input"; try { rtpSenderInput = new FileOutputStream(fileName); } catch (FileNotFoundException e) { logger.error("cannot create file", e); return; } } RtpPacket rtpPacket = new RtpPacket(); rtpPacket.setVersion(2); rtpPacket.setPadding(false); rtpPacket.setExtension(false); rtpPacket.setCsrcCount(0); rtpPacket.setMarker(false); rtpPacket.setPayloadType(codec.getPayloadType()); Random random = new Random(); int sequenceNumber = random.nextInt(); rtpPacket.setSequenceNumber(sequenceNumber); rtpPacket.setSsrc(random.nextInt()); byte[] buffer = new byte[BUF_SIZE]; byte[] pauseBuffer = new byte[BUF_SIZE]; Arrays.fill(pauseBuffer, silenceByte(codec)); int timestamp = 0; int numBytesRead = 0; boolean currentlyReading = false; int tempBytesRead; long sleepTime = 0; long lastSentTime = System.nanoTime(); // indicate if its the first time that we send a packet (dont wait) boolean firstTime = true; int sleeps = 0; long sumOversleep = 0; long avgOversleep = 0; while (!isStopped || encodedDataAvailable() > 0 || pushedPackets.size() > 0) { if (pushedPackets.size() > 0) { RtpPacket pushedPacket = pushedPackets.remove(0); rtpPacket.setMarker(pushedPacket.isMarker()); rtpPacket.setPayloadType(pushedPacket.getPayloadType()); rtpPacket.setIncrementTimeStamp(pushedPacket.isIncrementTimeStamp()); byte[] data = pushedPacket.getData(); rtpPacket.setData(data); } else { if (!currentlyReading) { numBytesRead = 0; } try { if (isPaused) { synchronized (pauseSync) { if (isPaused) { try { // When paused, send a small fragment of audio every 5th sec. Some components (SIP-servers, networks, // handsets, etc) hang up if no data is received for a while. You never know if such a component is involved // from here to the final client pauseSync.wait(5000); } catch (InterruptedException e) { logger.error("Interrupted pausing"); break; } } } } if (isPaused) { System.arraycopy(pauseBuffer, 0, buffer, 0, BUF_SIZE); numBytesRead = BUF_SIZE; } else { while ((numBytesRead < BUF_SIZE) && (encodedDataAvailable() > 0)) { tempBytesRead = encodedData.read(buffer, numBytesRead, BUF_SIZE - numBytesRead); if (tempBytesRead < 0) { setStopped(true); break; } numBytesRead += tempBytesRead; } // Make sure numBytesRead is not reset in next loop if available data is less than BUF_SIZE currentlyReading = ((numBytesRead > 0) && (numBytesRead < BUF_SIZE)); } } catch (IOException e) { // Getting an IOException reading from rawData is expected after the encoder has been stopped if (!isStopped) logger.error("Error reading encoded data", e); } //Only send full buffers if(currentlyReading) { continue; } byte[] trimmedBuffer; if (numBytesRead < buffer.length) { trimmedBuffer = new byte[numBytesRead]; System.arraycopy(buffer, 0, trimmedBuffer, 0, numBytesRead); } else { trimmedBuffer = buffer; } if (mediaDebug) { try { rtpSenderInput.write(trimmedBuffer); // TODO use classpath } catch (IOException e) { logger.error("cannot write to file", e); } } if (rtpPacket.getPayloadType() != codec.getPayloadType()) { rtpPacket.setPayloadType(codec.getPayloadType()); rtpPacket.setMarker(false); } rtpPacket.setData(trimmedBuffer); } rtpPacket.setSequenceNumber(sequenceNumber++); if (rtpPacket.isIncrementTimeStamp()) { timestamp += BUF_SIZE; } rtpPacket.setTimestamp(timestamp); if (firstTime) { lastSentTime = System.nanoTime(); rtpSession.send(rtpPacket); firstTime = false; continue; } long beforeSleep = System.nanoTime(); sleepTime = 20000000 - (beforeSleep - lastSentTime) - avgOversleep; if (sleepTime > 0) { try { Thread.sleep(sleepTime / 1000000, (int) sleepTime % 1000000); } catch (InterruptedException e) { logger.error("Thread interrupted", e); return; } lastSentTime = System.nanoTime(); long slept = (lastSentTime - beforeSleep); long oversleep = slept - sleepTime; sumOversleep += oversleep; if (sleeps++ == 10) { avgOversleep = (sumOversleep / sleeps); sleeps = 0; sumOversleep = 0; } rtpSession.send(rtpPacket); } else { lastSentTime = System.nanoTime(); rtpSession.send(rtpPacket); } } } finally { if (mediaDebug) { try { rtpSenderInput.close(); } catch (IOException e) { logger.error("cannot close file", e); return; } } try { encodedData.close(); } catch (IOException e) { logger.error("Error closing encoded data input pipe", e); } latch.countDown(); if (latch.getCount() != 0) { try { latch.await(); } catch (InterruptedException e) { logger.error("interrupt exception", e); } } } } public void setStopped(boolean isStopped) { this.isStopped = isStopped; resume(); } public void pause() { isPaused = true; } public synchronized void resume() { isPaused = false; synchronized (pauseSync) { pauseSync.notifyAll(); } } public void waitEmpty() throws IOException, InterruptedException { // FIXME This is the poor mans waiting. Really ought to be able to do it blocking. Besides that available() cannot really be trusted - it may // return 0 even though data is in the pipe arriving soon while (encodedData.available() > 0) { Thread.sleep(5); } } public void pushPackets(List<RtpPacket> rtpPackets) { this.pushedPackets.addAll(rtpPackets); } private int encodedDataAvailable() { try { return encodedData.available(); } catch (IOException e) { // PipedInputStream.available never throws IOException in practice logger.error("Error getting amount available encoded data. Should never happen", e); return 0; } } private byte silenceByte(Codec codec) { switch (codec.getPayloadType()) { case RFC3551.PAYLOAD_TYPE_PCMA: return RFC3551.PCMA_SILENCE; case RFC3551.PAYLOAD_TYPE_PCMU: return RFC3551.PCMU_SILENCE; default: return 0; } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/SoundSource.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2012 Yohann Martineau */ package net.sourceforge.peers.media; public interface SoundSource { enum DataFormat { LINEAR_PCM_8KHZ_16BITS_SIGNED_MONO_LITTLE_ENDIAN("pcm_8khz_16_bits_mono", "Linear PCM, 8kHz, 16-bites signed, mono-channel, little endian"), ALAW_8KHZ_MONO_LITTLE_ENDIAN("a_law", "A-law, 8kHz, mono-channel, little endian"); private String shortAlias; private String description; public static DataFormat DEFAULT = LINEAR_PCM_8KHZ_16BITS_SIGNED_MONO_LITTLE_ENDIAN; DataFormat(String shortAlias, String description) { this.shortAlias = shortAlias; this.description = description; } public String getDescription() { return description; } public String getShortAlias() { return shortAlias; } public static DataFormat fromShortAlias(String shortAlias) { for (DataFormat df : DataFormat.values()) { if (df.shortAlias.equals(shortAlias)) return df; } return null; } } default DataFormat dataProduced() { return DataFormat.DEFAULT; } /** * read raw data linear PCM 8kHz, 16 bits signed, mono-channel, little endian * @return */ byte[] readData(); default boolean finished() { return false; } default void waitFinished() throws InterruptedException { throw new RuntimeException("Waiting for finished not supported"); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/javaxsound/JavaxSoundManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010, 2011, 2012 Yohann Martineau */ package net.sourceforge.peers.media.javaxsound; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.SimpleDateFormat; import java.util.Date; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.AbstractSoundManager; import net.sourceforge.peers.sip.Utils; public class JavaxSoundManager extends AbstractSoundManager { private AudioFormat audioFormat; private TargetDataLine targetDataLine; private SourceDataLine sourceDataLine; private Object sourceDataLineMutex; private DataLine.Info targetInfo; private DataLine.Info sourceInfo; private FileOutputStream microphoneOutput; private FileOutputStream speakerInput; private boolean mediaDebug; private Logger logger; private String peersHome; public JavaxSoundManager(boolean mediaDebug, Logger logger, String peersHome) { this.mediaDebug = mediaDebug; this.logger = logger; this.peersHome = peersHome; if (peersHome == null) { this.peersHome = Utils.DEFAULT_PEERS_HOME; } // linear PCM 8kHz, 16 bits signed, mono-channel, little endian audioFormat = new AudioFormat(8000, 16, 1, true, false); targetInfo = new DataLine.Info(TargetDataLine.class, audioFormat); sourceInfo = new DataLine.Info(SourceDataLine.class, audioFormat); sourceDataLineMutex = new Object(); } @Override public void init() { logger.debug("openAndStartLines"); if (mediaDebug) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String date = simpleDateFormat.format(new Date()); StringBuffer buf = new StringBuffer(); buf.append(peersHome).append(File.separator); buf.append(MEDIA_DIR).append(File.separator); buf.append(date).append("_"); buf.append(audioFormat.getEncoding()).append("_"); buf.append(audioFormat.getSampleRate()).append("_"); buf.append(audioFormat.getSampleSizeInBits()).append("_"); buf.append(audioFormat.getChannels()).append("_"); buf.append(audioFormat.isBigEndian() ? "be" : "le"); try { microphoneOutput = new FileOutputStream(buf.toString() + "_microphone.output"); speakerInput = new FileOutputStream(buf.toString() + "_speaker.input"); } catch (FileNotFoundException e) { logger.error("cannot create file", e); return; } } // AccessController.doPrivileged added for plugin compatibility AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { try { targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo); targetDataLine.open(audioFormat); } catch (LineUnavailableException e) { logger.error("target line unavailable", e); return null; } catch (SecurityException e) { logger.error("security exception", e); return null; } catch (Throwable t) { logger.error("throwable " + t.getMessage()); return null; } targetDataLine.start(); synchronized (sourceDataLineMutex) { try { sourceDataLine = (SourceDataLine) AudioSystem.getLine(sourceInfo); sourceDataLine.open(audioFormat); } catch (LineUnavailableException e) { logger.error("source line unavailable", e); return null; } sourceDataLine.start(); } return null; } }); } @Override public synchronized void close() { logger.debug("closeLines"); if (microphoneOutput != null) { try { microphoneOutput.close(); } catch (IOException e) { logger.error("cannot close file", e); } microphoneOutput = null; } if (speakerInput != null) { try { speakerInput.close(); } catch (IOException e) { logger.error("cannot close file", e); } speakerInput = null; } // AccessController.doPrivileged added for plugin compatibility AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { if (targetDataLine != null) { targetDataLine.close(); targetDataLine = null; } synchronized (sourceDataLineMutex) { if (sourceDataLine != null) { sourceDataLine.drain(); sourceDataLine.stop(); sourceDataLine.close(); sourceDataLine = null; } } return null; } }); } @Override public synchronized byte[] readData() { if (targetDataLine == null) { return null; } int ready = targetDataLine.available(); while (ready == 0) { try { Thread.sleep(2); ready = targetDataLine.available(); } catch (InterruptedException e) { return null; } } if (ready <= 0) { return null; } byte[] buffer = new byte[ready]; targetDataLine.read(buffer, 0, buffer.length); if (mediaDebug) { try { microphoneOutput.write(buffer, 0, buffer.length); } catch (IOException e) { logger.error("cannot write to file", e); return null; } } return buffer; } @Override public int writeData(byte[] buffer, int offset, int length) { int numberOfBytesWritten; synchronized (sourceDataLineMutex) { if (sourceDataLine == null) { return 0; } numberOfBytesWritten = sourceDataLine.write(buffer, offset, length); } if (mediaDebug) { try { speakerInput.write(buffer, offset, numberOfBytesWritten); } catch (IOException e) { logger.error("cannot write to file", e); return -1; } } return numberOfBytesWritten; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/Client.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat; import java.io.IOException; import java.net.InetAddress; import org.w3c.dom.Document; public class Client { private Server server; //private String email; private PeerManager peerManager; public Client(String email, String localInetAddress, int localPort) { //this.email = email; // TODO automatic global access interface discovery try { InetAddress localAddress = InetAddress.getByName(localInetAddress); server = new Server(localAddress, localPort); peerManager = new PeerManager(localAddress, localPort); } catch (IOException e) { e.printStackTrace(); return; } server.update(email); Document document = server.getPeers(email); peerManager.setDocument(document); peerManager.start(); } /** * @param args */ public static void main(String[] args) { if (args.length != 3) { System.err.println("usage: java ... <email> <localAddress>" + " <localPort>"); System.exit(1); } new Client(args[0], args[1], Integer.parseInt(args[2])); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/PeerManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class PeerManager extends Thread { private InetAddress localAddress; private int localPort; private Document document; public PeerManager(InetAddress localAddress, int localPort) { this.localAddress = localAddress; this.localPort = localPort; } public void setDocument(Document document) { this.document = document; } public void run() { DatagramSocket datagramSocket; try { datagramSocket = new DatagramSocket(localPort, localAddress); } catch (SocketException e) { e.printStackTrace(); return; } // UDPReceiver udpReceiver = new UDPReceiver(datagramSocket); // udpReceiver.start(); while (true) { Element root = document.getDocumentElement(); NodeList peers = root.getChildNodes(); for (int i = 0; i < peers.getLength(); ++i) { Node node = peers.item(i); if (node.getNodeName().equals("peer")) { createConnection(node, datagramSocket); } } try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); return; } } } private void createConnection(Node peer, DatagramSocket datagramSocket) { NodeList childNodes = peer.getChildNodes(); String ipAddress = null; String port = null; for (int i = 0; i < childNodes.getLength(); ++i) { Node node = childNodes.item(i); String nodeName = node.getNodeName(); if (nodeName.equals("ipaddress")) { ipAddress = node.getTextContent(); } else if (nodeName.equals("port")) { port = node.getTextContent(); } } if (ipAddress == null || port == null) { return; } int remotePort = Integer.parseInt(port); try { InetAddress remoteAddress = InetAddress.getByName(ipAddress); // DatagramSocket datagramSocket = new DatagramSocket(localPort, localAddress); for (int i = 0; i < 5; ++i) { String message = "hello world " + System.currentTimeMillis(); byte[] buf = message.getBytes(); DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, remoteAddress, remotePort); datagramSocket.send(datagramPacket); System.out.println("> sent:\n" + message); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); return; } } //datagramSocket.close(); } catch (IOException e) { e.printStackTrace(); return; } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/Server.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class Server { public static final String SERVER_HOST = "peers.sourceforge.net"; public static final String PREFIX = "/peers"; //public static final int SOCKET_TIMEOUT = 30000;//millis //private InetAddress localAddress; //private int localPort; private InetAddress remoteAddress; private int remotePort; private Socket socket; //TODO constructor without parameters public Server(InetAddress localAddress, int localPort) throws IOException { super(); //this.localAddress = localAddress; //this.localPort = localPort; this.remoteAddress = InetAddress.getByName(SERVER_HOST); this.remotePort = 80; socket = new Socket(remoteAddress, remotePort, localAddress, localPort); //socket.setSoTimeout(SOCKET_TIMEOUT); } /** * This method will update public address on the web server. * @param email user identifier */ public void update(String email) { String encodedEmail; try { encodedEmail = URLEncoder.encode(email, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } StringBuffer urlEnd = new StringBuffer(); urlEnd.append("update2.php?email="); urlEnd.append(encodedEmail); get(urlEnd.toString()); close(); } public Document getPeers(String email) { String encodedEmail; try { encodedEmail = URLEncoder.encode(email, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } StringBuffer urlBuf = new StringBuffer(); urlBuf.append("http://"); urlBuf.append(SERVER_HOST); urlBuf.append(PREFIX); urlBuf.append("/getassocasxml.php?email="); urlBuf.append(encodedEmail); URL url; try { url = new URL(urlBuf.toString()); } catch (MalformedURLException e) { e.printStackTrace(); return null; } System.out.println("retrieved peers"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } try { URLConnection urlConnection = url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); return documentBuilder.parse(inputStream); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; } private String get(String urlEnd) { StringBuffer get = new StringBuffer(); get.append("GET "); get.append(PREFIX); get.append('/'); get.append(urlEnd); get.append(" HTTP/1.1\r\n"); get.append("Host: "); get.append(SERVER_HOST); get.append("\r\n"); get.append("\r\n"); try { socket.getOutputStream().write(get.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); return null; } System.out.println("> sent:\n" + get.toString()); StringBuffer result = new StringBuffer(); try { byte[] buf = new byte[256]; int read = 0; while ((read = socket.getInputStream().read(buf)) > -1) { byte[] exactBuf = new byte[read]; System.arraycopy(buf, 0, exactBuf, 0, read); result.append(new String(exactBuf)); } } catch (SocketTimeoutException e) { System.out.println("socket timeout"); return null; } catch (IOException e) { e.printStackTrace(); return null; } System.out.println("< received:\n" + result.toString()); return result.toString(); } public void close() { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/UDPReceiver.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPReceiver extends Thread { private DatagramSocket datagramSocket; public UDPReceiver(DatagramSocket datagramSocket) { super(); this.datagramSocket = datagramSocket; } @Override public void run() { try { while (true) { byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); datagramSocket.receive(packet); System.out.println("< received:\n" + new String(packet.getData())); } } catch (IOException e) { e.printStackTrace(); } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/api/DataReceiver.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat.api; public interface DataReceiver { public void dataReceived(byte[] data, String peerId); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/api/PeersClient.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat.api; public abstract class PeersClient { /** * creates a new peers client * @param myId the string identifier corresponding * to the computer or to a person (email). * @param dataReceiver object that will receive incoming traffic. */ public PeersClient(String myId, DataReceiver dataReceiver) { } /** * creates a UDP connection to a peer. * @param peerId unique peer identifier (email for example). * @return an object that allows to send data to the peer. */ public abstract UDPTransport createUDPTransport(String peerId); /** * creates a TCP connection to a peer. * @param peerId unique peer identifier (email for example). * @return an object that allows to send data to the peer. */ public abstract TCPTransport createTCPTransport(String peerId); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/api/TCPTransport.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat.api; public interface TCPTransport extends Transport { }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/api/Transport.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat.api; public interface Transport { public void sendData(byte[] data); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/nat/api/UDPTransport.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.nat.api; public interface UDPTransport extends Transport { }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/rtp/RFC3551.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.rtp; public class RFC3551 { // payload types public static final int PAYLOAD_TYPE_PCMU = 0; public static final int PAYLOAD_TYPE_PCMA = 8; // encoding names public static final String PCMU = "PCMU"; public static final String PCMA = "PCMA"; // silence public static final byte PCMU_SILENCE = (byte)0xFF; public static final byte PCMA_SILENCE = (byte)0xD5; }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/rtp/RFC4733.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.rtp; public class RFC4733 { // payload types public static final int PAYLOAD_TYPE_TELEPHONE_EVENT = 101; // encoding names public static final String TELEPHONE_EVENT = "telephone-event"; // DTMF values public static enum DTMFEvent { DTMF_DIGIT_0 (0), DTMF_DIGIT_1 (1), DTMF_DIGIT_2 (2), DTMF_DIGIT_3 (3), DTMF_DIGIT_4 (4), DTMF_DIGIT_5 (5), DTMF_DIGIT_6 (6), DTMF_DIGIT_7 (7), DTMF_DIGIT_8 (8), DTMF_DIGIT_9 (9), DTMF_DIGIT_STAR (10), DTMF_DIGIT_HASH (11), DTMF_DIGIT_A (12), DTMF_DIGIT_B (13), DTMF_DIGIT_C (14), DTMF_DIGIT_D (15), DTMF_DIGIT_FLASH (16); private int value; DTMFEvent(int value) { this.value = value; } public int getValue() { return value; } public static DTMFEvent fromValue(int value) { for (DTMFEvent type : DTMFEvent.values()) { if (type.getValue() == value) { return type; } } return null; } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/rtp/RtpListener.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.rtp; public interface RtpListener { public void receivedRtpPacket(RtpPacket rtpPacket); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/rtp/RtpPacket.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.rtp; public class RtpPacket { private int version; private boolean padding; private boolean extension; private int csrcCount; private boolean marker; private int payloadType; private int sequenceNumber; private long timestamp; private long ssrc; private long[] csrcList; private byte[] data; private boolean incrementTimeStamp = true; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isPadding() { return padding; } public void setPadding(boolean padding) { this.padding = padding; } public boolean isExtension() { return extension; } public void setExtension(boolean extension) { this.extension = extension; } public int getCsrcCount() { return csrcCount; } public void setCsrcCount(int csrcCount) { this.csrcCount = csrcCount; } public boolean isMarker() { return marker; } public void setMarker(boolean marker) { this.marker = marker; } public int getPayloadType() { return payloadType; } public void setPayloadType(int payloadType) { this.payloadType = payloadType; } public int getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(int sequenceNumber) { this.sequenceNumber = sequenceNumber; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public long getSsrc() { return ssrc; } public void setSsrc(long ssrc) { this.ssrc = ssrc; } public long[] getCsrcList() { return csrcList; } public void setCsrcList(long[] csrcList) { this.csrcList = csrcList; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public boolean isIncrementTimeStamp() { return incrementTimeStamp; } public void setIncrementTimeStamp(boolean incrementTimeStamp) { this.incrementTimeStamp = incrementTimeStamp; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/rtp/RtpParser.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.rtp; import net.sourceforge.peers.Logger; // RFC 3550 public class RtpParser { private Logger logger; public RtpParser(Logger logger) { this.logger = logger; } public RtpPacket decode(byte[] packet) { if (packet.length < 12) { logger.error("RTP packet too short"); return null; } RtpPacket rtpPacket = new RtpPacket(); int b = (int)(packet[0] & 0xff); rtpPacket.setVersion((b & 0xc0) >> 6); rtpPacket.setPadding((b & 0x20) != 0); rtpPacket.setExtension((b & 0x10) != 0); rtpPacket.setCsrcCount(b & 0x0f); b = (int)(packet[1] & 0xff); rtpPacket.setMarker((b & 0x80) != 0); rtpPacket.setPayloadType(b & 0x7f); b = (int)(packet[2] & 0xff); rtpPacket.setSequenceNumber(b * 256 + (int)(packet[3] & 0xff)); b = (int)(packet[4] & 0xff); rtpPacket.setTimestamp(b * 256 * 256 * 256 + (int)(packet[5] & 0xff) * 256 * 256 + (int)(packet[6] & 0xff) * 256 + (int)(packet[7] & 0xff)); b = (int)(packet[8] & 0xff); rtpPacket.setSsrc(b * 256 * 256 * 256 + (int)(packet[9] & 0xff) * 256 * 256 + (int)(packet[10] & 0xff) * 256 + (int)(packet[11] & 0xff)); long[] csrcList = new long[rtpPacket.getCsrcCount()]; for (int i = 0; i < csrcList.length; ++i) csrcList[i] = (int)(packet[12 + i] & 0xff) << 24 + (int)(packet[12 + i + 1] & 0xff) << 16 + (int)(packet[12 + i + 2] & 0xff) << 8 + (int)(packet[12 + i + 3] & 0xff); rtpPacket.setCsrcList(csrcList); int dataOffset = 12 + csrcList.length * 4; int dataLength = packet.length - dataOffset; byte[] data = new byte[dataLength]; System.arraycopy(packet, dataOffset, data, 0, dataLength); rtpPacket.setData(data); return rtpPacket; } public byte[] encode(RtpPacket rtpPacket) { byte[] data = rtpPacket.getData(); int packetLength = 12 + rtpPacket.getCsrcCount() * 4 + data.length; byte[] packet = new byte[packetLength]; int b = (rtpPacket.getVersion() << 6) + ((rtpPacket.isPadding() ? 1 : 0) << 5) + ((rtpPacket.isExtension() ? 1 : 0) << 4) + (rtpPacket.getCsrcCount()); packet[0] = new Integer(b).byteValue(); b = ((rtpPacket.isMarker() ? 1 : 0) << 7) + rtpPacket.getPayloadType(); packet[1] = new Integer(b).byteValue(); b = rtpPacket.getSequenceNumber() >> 8; packet[2] = new Integer(b).byteValue(); b = rtpPacket.getSequenceNumber() & 0xff; packet[3] = new Integer(b).byteValue(); b = (int)(rtpPacket.getTimestamp() >> 24); packet[4] = new Integer(b).byteValue(); b = (int)(rtpPacket.getTimestamp() >> 16); packet[5] = new Integer(b).byteValue(); b = (int)(rtpPacket.getTimestamp() >> 8); packet[6] = new Integer(b).byteValue(); b = (int)(rtpPacket.getTimestamp() & 0xff); packet[7] = new Integer(b).byteValue(); b = (int)(rtpPacket.getSsrc() >> 24); packet[8] = new Integer(b).byteValue(); b = (int)(rtpPacket.getSsrc() >> 16); packet[9] = new Integer(b).byteValue(); b = (int)(rtpPacket.getSsrc() >> 8); packet[10] = new Integer(b).byteValue(); b = (int)(rtpPacket.getSsrc() & 0xff); packet[11] = new Integer(b).byteValue(); for (int i = 0; i < rtpPacket.getCsrcCount(); ++i) { b = (int)(rtpPacket.getCsrcList()[i] >> 24); packet[12 + i * 4] = new Integer(b).byteValue(); b = (int)(rtpPacket.getCsrcList()[i] >> 16); packet[12 + i * 4 + 1] = new Integer(b).byteValue(); b = (int)(rtpPacket.getCsrcList()[i] >> 8); packet[12 + i * 4 + 2] = new Integer(b).byteValue(); b = (int)(rtpPacket.getCsrcList()[i] & 0xff); packet[12 + i * 4 + 3] = new Integer(b).byteValue(); } System.arraycopy(data, 0, packet, 12 + rtpPacket.getCsrcCount() * 4, data.length); return packet; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/rtp/RtpSession.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers.rtp; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.AbstractSoundManager; /** * can be instantiated on UAC INVITE sending or on UAS 200 OK sending */ public class RtpSession { private InetAddress remoteAddress; private int remotePort; private DatagramSocket datagramSocket; private int executorServiceThreadNo = 0; private ExecutorService executorService; private List<RtpListener> rtpListeners; private RtpParser rtpParser; private FileOutputStream rtpSessionOutput; private FileOutputStream rtpSessionInput; private boolean mediaDebug; private Logger logger; private String peersHome; public RtpSession(InetAddress localAddress, DatagramSocket datagramSocket, boolean mediaDebug, Logger logger, String peersHome) { this.mediaDebug = mediaDebug; this.logger = logger; this.peersHome = peersHome; this.datagramSocket = datagramSocket; rtpListeners = new ArrayList<RtpListener>(); rtpParser = new RtpParser(logger); executorService = Executors.newSingleThreadExecutor((runnable) -> new Thread(runnable, RtpSession.class.getSimpleName() + "-" + ++executorServiceThreadNo)); } public synchronized void start() { if (mediaDebug) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String date = simpleDateFormat.format(new Date()); String dir = peersHome + File.separator + AbstractSoundManager.MEDIA_DIR + File.separator; String fileName = dir + date + "_rtp_session.output"; try { rtpSessionOutput = new FileOutputStream(fileName); fileName = dir + date + "_rtp_session.input"; rtpSessionInput = new FileOutputStream(fileName); } catch (FileNotFoundException e) { logger.error("cannot create file", e); return; } } executorService.submit(new Receiver()); } public void stop() { // AccessController.doPrivileged added for plugin compatibility AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { executorService.shutdown(); return null; } } ); } public void addRtpListener(RtpListener rtpListener) { rtpListeners.add(rtpListener); } public synchronized void send(RtpPacket rtpPacket) { if (datagramSocket == null) { return; } byte[] buf = rtpParser.encode(rtpPacket); final DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, remoteAddress, remotePort); if (!datagramSocket.isClosed()) { // AccessController.doPrivileged added for plugin compatibility AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { try { datagramSocket.send(datagramPacket); } catch (IOException e) { logger.error("cannot send rtp packet", e); } catch (SecurityException e) { logger.error("security exception", e); } return null; } } ); if (mediaDebug) { try { rtpSessionOutput.write(buf); } catch (IOException e) { logger.error("cannot write to file", e); } } } } public void setRemoteAddress(InetAddress remoteAddress) { this.remoteAddress = remoteAddress; } public void setRemotePort(int remotePort) { this.remotePort = remotePort; } private void closeFileAndDatagramSocket() { if (mediaDebug) { try { rtpSessionOutput.close(); rtpSessionInput.close(); } catch (IOException e) { logger.error("cannot close file", e); } } // AccessController.doPrivileged added for plugin compatibility AccessController.doPrivileged( new PrivilegedAction<Void>() { @Override public Void run() { datagramSocket.close(); return null; } } ); } class Receiver implements Runnable { @Override public void run() { int receiveBufferSize; try { receiveBufferSize = datagramSocket.getReceiveBufferSize(); } catch (SocketException e) { logger.error("cannot get datagram socket receive buffer size", e); return; } byte[] buf = new byte[receiveBufferSize]; final DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); final int noException = 0; final int socketTimeoutException = 1; final int ioException = 2; int result = AccessController.doPrivileged( new PrivilegedAction<Integer>() { public Integer run() { try { datagramSocket.receive(datagramPacket); } catch (SocketTimeoutException e) { return socketTimeoutException; } catch (IOException e) { logger.error("cannot receive packet", e); return ioException; } return noException; } }); switch (result) { case socketTimeoutException: try { executorService.execute(this); } catch (RejectedExecutionException rej) { closeFileAndDatagramSocket(); } return; case ioException: return; case noException: break; default: break; } InetAddress remoteAddress = datagramPacket.getAddress(); if (remoteAddress != null && !remoteAddress.equals(RtpSession.this.remoteAddress)) { RtpSession.this.remoteAddress = remoteAddress; } int remotePort = datagramPacket.getPort(); if (remotePort != RtpSession.this.remotePort) { RtpSession.this.remotePort = remotePort; } byte[] data = datagramPacket.getData(); int offset = datagramPacket.getOffset(); int length = datagramPacket.getLength(); byte[] trimmedData = new byte[length]; System.arraycopy(data, offset, trimmedData, 0, length); if (mediaDebug) { try { rtpSessionInput.write(trimmedData); } catch (IOException e) { logger.error("cannot write to file", e); return; } } RtpPacket rtpPacket = rtpParser.decode(trimmedData); for (RtpListener rtpListener: rtpListeners) { rtpListener.receivedRtpPacket(rtpPacket); } try { executorService.execute(this); } catch (RejectedExecutionException rej) { closeFileAndDatagramSocket(); } } } public boolean isSocketClosed() { if (datagramSocket == null) { return true; } return datagramSocket.isClosed(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/Codec.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; import net.sourceforge.peers.media.MediaManager; public class Codec { private int payloadType; private String name; public int getPayloadType() { return payloadType; } public void setPayloadType(int payloadType) { this.payloadType = payloadType; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (!(obj instanceof Codec)) { return false; } Codec codec = (Codec)obj; if (codec.getName() == null) { return name == null; } return codec.getName().equalsIgnoreCase(name); } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append(RFC4566.TYPE_ATTRIBUTE).append(RFC4566.SEPARATOR); buf.append(RFC4566.ATTR_RTPMAP).append(RFC4566.ATTR_SEPARATOR); buf.append(payloadType).append(" ").append(name).append("/"); buf.append(MediaManager.DEFAULT_CLOCK).append("\r\n"); return buf.toString(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/MediaDescription.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.util.Hashtable; import java.util.List; public class MediaDescription { private String type; private InetAddress ipAddress; // attributes not codec-related private Hashtable<String, String> attributes; private int port; private List<Codec> codecs; public String getType() { return type; } public void setType(String type) { this.type = type; } public Hashtable<String, String> getAttributes() { return attributes; } public void setAttributes(Hashtable<String, String> attributes) { this.attributes = attributes; } public InetAddress getIpAddress() { return ipAddress; } public void setIpAddress(InetAddress ipAddress) { this.ipAddress = ipAddress; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public List<Codec> getCodecs() { return codecs; } public void setCodecs(List<Codec> codecs) { this.codecs = codecs; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append(RFC4566.TYPE_MEDIA).append(RFC4566.SEPARATOR); buf.append(type).append(" ").append(port); buf.append(" RTP/AVP"); for (Codec codec: codecs) { buf.append(" "); buf.append(codec.getPayloadType()); } buf.append("\r\n"); if (ipAddress != null) { int ipVersion; if (ipAddress instanceof Inet4Address) { ipVersion = 4; } else if (ipAddress instanceof Inet6Address) { ipVersion = 6; } else { throw new RuntimeException("unknown ip version: " + ipAddress); } buf.append(RFC4566.TYPE_CONNECTION).append(RFC4566.SEPARATOR); buf.append("IN IP").append(ipVersion).append(" "); buf.append(ipAddress.getHostAddress()).append("\r\n"); } for (Codec codec: codecs) { buf.append(codec.toString()); } if (attributes != null) { for (String attributeName: attributes.keySet()) { buf.append(RFC4566.TYPE_ATTRIBUTE).append(RFC4566.SEPARATOR); buf.append(attributeName); String attributeValue = attributes.get(attributeName); if (attributeValue != null && !"".equals(attributeValue.trim())) { buf.append(":").append(attributeValue); } buf.append("\r\n"); } } return buf.toString(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/MediaDestination.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; public class MediaDestination { private String destination; private int port; private Codec codec; public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public Codec getCodec() { return codec; } public void setCodec(Codec codec) { this.codec = codec; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/NoCodecException.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; public class NoCodecException extends Exception { private static final long serialVersionUID = 1L; }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/RFC4566.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; public class RFC4566 { public static final char VERSION = '0'; public static final char TYPE_VERSION = 'v'; public static final char TYPE_ORIGIN = 'o'; public static final char TYPE_SUBJECT = 's'; public static final char TYPE_INFO = 'i'; public static final char TYPE_URI = 'u'; public static final char TYPE_EMAIL = 'e'; public static final char TYPE_PHONE = 'p'; public static final char TYPE_CONNECTION = 'c'; public static final char TYPE_BANDWITH = 'b'; public static final char TYPE_TIME = 't'; public static final char TYPE_REPEAT = 'r'; public static final char TYPE_ZONE = 'z'; public static final char TYPE_KEY = 'k'; public static final char TYPE_ATTRIBUTE = 'a'; public static final char TYPE_MEDIA = 'm'; public static final char SEPARATOR = '='; public static final char ATTR_SEPARATOR = ':'; public static final String MEDIA_AUDIO = "audio"; public static final String ATTR_RTPMAP = "rtpmap"; public static final String ATTR_SENDRECV = "sendrecv"; }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/SDPManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010, 2012 Yohann Martineau */ package net.sourceforge.peers.sdp; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Random; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.rtp.RFC3551; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sip.core.useragent.UserAgent; public class SDPManager { private SdpParser sdpParser; private UserAgent userAgent; private List<Codec> supportedCodecs; private Random random; private Logger logger; public SDPManager(UserAgent userAgent, Logger logger) { this.userAgent = userAgent; this.logger = logger; sdpParser = new SdpParser(); supportedCodecs = userAgent.getConfig().getSupportedCodecs(); random = new Random(); } public SessionDescription parse(byte[] sdp) { try { return sdpParser.parse(sdp); } catch (IOException e) { logger.error(e.getMessage(), e); } return null; } public MediaDestination getMediaDestination( SessionDescription sessionDescription) throws NoCodecException { InetAddress destAddress = sessionDescription.getIpAddress(); List<MediaDescription> mediaDescriptions = sessionDescription.getMediaDescriptions(); for (MediaDescription mediaDescription: mediaDescriptions) { if (RFC4566.MEDIA_AUDIO.equals(mediaDescription.getType())) { for (Codec offerCodec: mediaDescription.getCodecs()) { if (supportedCodecs.contains(offerCodec)) { String offerCodecName = offerCodec.getName(); if (offerCodecName.equalsIgnoreCase(RFC3551.PCMU) || offerCodecName.equalsIgnoreCase(RFC3551.PCMA)) { int destPort = mediaDescription.getPort(); if (mediaDescription.getIpAddress() != null) { destAddress = mediaDescription.getIpAddress(); } MediaDestination mediaDestination = new MediaDestination(); mediaDestination.setDestination( destAddress.getHostAddress()); mediaDestination.setPort(destPort); mediaDestination.setCodec(offerCodec); return mediaDestination; } } } } } throw new NoCodecException(); } public SessionDescription createSessionDescription(SessionDescription offer, int localRtpPort) throws IOException { SessionDescription sessionDescription = new SessionDescription(); sessionDescription.setUsername("user1"); sessionDescription.setId(random.nextInt(Integer.MAX_VALUE)); sessionDescription.setVersion(random.nextInt(Integer.MAX_VALUE)); Config config = userAgent.getConfig(); InetAddress inetAddress = config.getPublicInetAddress(); if (inetAddress == null) { inetAddress = config.getLocalInetAddress(); } sessionDescription.setIpAddress(inetAddress); sessionDescription.setName("-"); sessionDescription.setAttributes(new Hashtable<String, String>()); List<Codec> codecs; if (offer == null) { codecs = supportedCodecs; } else { codecs = new ArrayList<Codec>(); for (MediaDescription mediaDescription: offer.getMediaDescriptions()) { if (RFC4566.MEDIA_AUDIO.equals(mediaDescription.getType())) { for (Codec codec: mediaDescription.getCodecs()) { if (supportedCodecs.contains(codec)) { codecs.add(codec); } } } } } MediaDescription mediaDescription = new MediaDescription(); Hashtable<String, String> attributes = new Hashtable<String, String>(); attributes.put(RFC4566.ATTR_SENDRECV, ""); mediaDescription.setAttributes(attributes); mediaDescription.setType(RFC4566.MEDIA_AUDIO); mediaDescription.setPort(localRtpPort); mediaDescription.setCodecs(codecs); List<MediaDescription> mediaDescriptions = new ArrayList<MediaDescription>(); mediaDescriptions.add(mediaDescription); sessionDescription.setMediaDescriptions(mediaDescriptions); return sessionDescription; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/SDPMessage.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; public class SDPMessage { }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/SdpLine.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; public class SdpLine { private char type; private String value; public char getType() { return type; } public void setType(char type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/SdpParser.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import net.sourceforge.peers.rtp.RFC3551; public class SdpParser { public SessionDescription parse(byte[] body) throws IOException { if (body == null || body.length == 0) { return null; } ByteArrayInputStream in = new ByteArrayInputStream(body); InputStreamReader inputStreamReader = new InputStreamReader(in); BufferedReader reader = new BufferedReader(inputStreamReader); SessionDescription sessionDescription = new SessionDescription(); //version String line = reader.readLine(); if (line.length() < 3) { return null; } if (line.charAt(0) != RFC4566.TYPE_VERSION || line.charAt(1) != RFC4566.SEPARATOR || line.charAt(2) != RFC4566.VERSION) { return null; } //origin line = reader.readLine(); if (line.length() < 3) { return null; } if (line.charAt(0) != RFC4566.TYPE_ORIGIN || line.charAt(1) != RFC4566.SEPARATOR) { return null; } line = line.substring(2); String[] originArr = line.split(" "); if (originArr == null || originArr.length != 6) { return null; } sessionDescription.setUsername(originArr[0]); sessionDescription.setId(Long.parseLong(originArr[1])); sessionDescription.setVersion(Long.parseLong(originArr[2])); sessionDescription.setIpAddress(InetAddress.getByName(originArr[5])); //name line = reader.readLine(); if (line.length() < 3) { return null; } if (line.charAt(0) != RFC4566.TYPE_SUBJECT || line.charAt(1) != RFC4566.SEPARATOR) { return null; } sessionDescription.setName(line.substring(2)); //session connection and attributes Hashtable<String, String> sessionAttributes = new Hashtable<String, String>(); sessionDescription.setAttributes(sessionAttributes); while ((line = reader.readLine()) != null && line.charAt(0) != RFC4566.TYPE_MEDIA) { if (line.length() > 3 && line.charAt(0) == RFC4566.TYPE_CONNECTION && line.charAt(1) == RFC4566.SEPARATOR) { String connection = parseConnection(line.substring(2)); if (connection == null) { continue; } sessionDescription.setIpAddress(InetAddress.getByName(connection)); } else if (line.length() > 3 && line.charAt(0) == RFC4566.TYPE_ATTRIBUTE && line.charAt(1) == RFC4566.SEPARATOR) { String value = line.substring(2); int pos = value.indexOf(RFC4566.ATTR_SEPARATOR); if (pos > -1) { sessionAttributes.put(value.substring(0, pos), value.substring(pos + 1)); } else { sessionAttributes.put(value, ""); } } } if (line == null) { return null; } //we are at the first media line ArrayList<SdpLine> mediaLines = new ArrayList<SdpLine>(); do { if (line.length() < 3) { return null; } if (line.charAt(1) != RFC4566.SEPARATOR) { return null; } SdpLine mediaLine = new SdpLine(); mediaLine.setType(line.charAt(0)); mediaLine.setValue(line.substring(2)); mediaLines.add(mediaLine); } while ((line = reader.readLine()) != null); ArrayList<MediaDescription> mediaDescriptions = new ArrayList<MediaDescription>(); sessionDescription.setMediaDescriptions(mediaDescriptions); for (SdpLine sdpLine : mediaLines) { MediaDescription mediaDescription; if (sdpLine.getType() == RFC4566.TYPE_MEDIA) { String[] mediaArr = sdpLine.getValue().split(" "); if (mediaArr == null || mediaArr.length < 4) { return null; } mediaDescription = new MediaDescription(); mediaDescription.setType(mediaArr[0]); //TODO manage port range mediaDescription.setPort(Integer.parseInt(mediaArr[1])); mediaDescription.setAttributes(new Hashtable<String, String>()); List<Codec> codecs = new ArrayList<Codec>(); for (int i = 3; i < mediaArr.length; ++i) { int payloadType = Integer.parseInt(mediaArr[i]); Codec codec = new Codec(); codec.setPayloadType(payloadType); String name; switch (payloadType) { case RFC3551.PAYLOAD_TYPE_PCMU: name = RFC3551.PCMU; break; case RFC3551.PAYLOAD_TYPE_PCMA: name = RFC3551.PCMA; break; default: name = "unsupported"; break; } codec.setName(name); codecs.add(codec); //TODO check that sdp offer without rtpmap works } mediaDescription.setCodecs(codecs); mediaDescriptions.add(mediaDescription); } else { mediaDescription = mediaDescriptions.get(mediaDescriptions.size() - 1); String sdpLineValue = sdpLine.getValue(); if (sdpLine.getType() == RFC4566.TYPE_CONNECTION) { String ipAddress = parseConnection(sdpLineValue); mediaDescription.setIpAddress(InetAddress.getByName(ipAddress)); } else if (sdpLine.getType() == RFC4566.TYPE_ATTRIBUTE) { Hashtable<String, String> attributes = mediaDescription.getAttributes(); int pos = sdpLineValue.indexOf(RFC4566.ATTR_SEPARATOR); if (pos > -1) { String name = sdpLineValue.substring(0, pos); String value = sdpLineValue.substring(pos + 1); pos = value.indexOf(" "); if (pos > -1) { int payloadType; try { payloadType = Integer.parseInt(value.substring(0, pos)); List<Codec> codecs = mediaDescription.getCodecs(); for (Codec codec: codecs) { if (codec.getPayloadType() == payloadType) { value = value.substring(pos + 1); pos = value.indexOf("/"); if (pos > -1) { value = value.substring(0, pos); codec.setName(value); } break; } } } catch (NumberFormatException e) { attributes.put(name, value); } } else { attributes.put(name, value); } } else { attributes.put(sdpLineValue, ""); } } } } sessionDescription.setMediaDescriptions(mediaDescriptions); for (MediaDescription description : mediaDescriptions) { if (description.getIpAddress() == null) { InetAddress sessionAddress = sessionDescription.getIpAddress(); if (sessionAddress == null) { return null; } description.setIpAddress(sessionAddress); } } return sessionDescription; } private String parseConnection(String line) { String[] connectionArr = line.split(" "); if (connectionArr == null || connectionArr.length != 3) { return null; } return connectionArr[2]; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sdp/SessionDescription.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sdp; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.util.Hashtable; import java.util.List; public class SessionDescription { private long id; private long version; private String name; private String username; private InetAddress ipAddress; private List<MediaDescription> mediaDescriptions; private Hashtable<String, String> attributes; public long getId() { return id; } public void setId(long id) { this.id = id; } public InetAddress getIpAddress() { return ipAddress; } public void setIpAddress(InetAddress ipAddress) { this.ipAddress = ipAddress; } public List<MediaDescription> getMediaDescriptions() { return mediaDescriptions; } public void setMediaDescriptions(List<MediaDescription> mediaDescriptions) { this.mediaDescriptions = mediaDescriptions; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public Hashtable<String, String> getAttributes() { return attributes; } public void setAttributes(Hashtable<String, String> attributes) { this.attributes = attributes; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("v=0\r\n"); buf.append("o=").append(username).append(" ").append(id); buf.append(" ").append(version); int ipVersion; if (ipAddress instanceof Inet4Address) { ipVersion = 4; } else if (ipAddress instanceof Inet6Address) { ipVersion = 6; } else { throw new RuntimeException("unknown ip version: " + ipAddress); } buf.append(" IN IP").append(ipVersion).append(" "); String hostAddress = ipAddress.getHostAddress(); buf.append(hostAddress).append("\r\n"); buf.append("s=").append(name).append("\r\n"); buf.append("c=IN IP").append(ipVersion).append(" "); buf.append(hostAddress).append("\r\n"); buf.append("t=0 0\r\n"); for (String attributeName: attributes.keySet()) { String attributeValue = attributes.get(attributeName); buf.append("a=").append(attributeName); if (attributeValue != null && !"".equals(attributeValue.trim())) { buf.append(":"); buf.append(attributeValue); buf.append("\r\n"); } } for (MediaDescription mediaDescription: mediaDescriptions) { buf.append(mediaDescription.toString()); } return buf.toString(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/AbstractState.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip; import net.sourceforge.peers.Logger; public abstract class AbstractState { protected String id; protected Logger logger; public AbstractState(String id, Logger logger) { this.id = id; this.logger = logger; } public void log(AbstractState state) { StringBuffer buf = new StringBuffer(); buf.append("SM ").append(id).append(" ["); buf.append(JavaUtils.getShortClassName(this.getClass())).append(" -> "); buf.append(JavaUtils.getShortClassName(state.getClass())).append("] "); buf.append(new Exception().getStackTrace()[1].getMethodName()); logger.debug(buf.toString()); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/JavaUtils.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip; public class JavaUtils { public static String getShortClassName(Class<?> c) { String name = c.getName(); return name.substring(name.lastIndexOf('.') + 1); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/RFC2617.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2008, 2009, 2010, 2011 Yohann Martineau */ package net.sourceforge.peers.sip; public class RFC2617 { // SCHEMES public static final String SCHEME_DIGEST = "Digest"; // PARAMETERS public static final String PARAM_NONCE = "nonce"; public static final String PARAM_OPAQUE = "opaque"; public static final String PARAM_REALM = "realm"; public static final String PARAM_RESPONSE = "response"; public static final String PARAM_URI = "uri"; public static final String PARAM_USERNAME = "username"; public static final String PARAM_QOP = "qop"; public static final String PARAM_CNONCE = "cnonce"; public static final String PARAM_NC = "nc"; public static final String PARAM_ALGORITHM= "algorithm"; // MISCELLANEOUS public static final char PARAM_SEPARATOR = ','; public static final char PARAM_VALUE_SEPARATOR = '='; public static final char PARAM_VALUE_DELIMITER = '"'; public static final char DIGEST_SEPARATOR = ':'; }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/RFC3261.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip; public final class RFC3261 { //SYNTAX ENCODING //HEADERS //Methods public static final String METHOD_INVITE = "INVITE"; public static final String METHOD_ACK = "ACK"; public static final String METHOD_REGISTER = "REGISTER"; public static final String METHOD_BYE = "BYE"; public static final String METHOD_OPTIONS = "OPTIONS"; public static final String METHOD_CANCEL = "CANCEL"; //Classical form public static final String HDR_ALLOW = "Allow"; public static final String HDR_AUTHORIZATION = "Authorization"; public static final String HDR_CALLID = "Call-ID"; public static final String HDR_CONTACT = "Contact"; public static final String HDR_CONTENT_ENCODING = "Content-Encoding"; public static final String HDR_CONTENT_LENGTH = "Content-Length"; public static final String HDR_CONTENT_TYPE = "Content-Type"; public static final String HDR_CSEQ = "CSeq"; public static final String HDR_EXPIRES = "Expires"; public static final String HDR_FROM = "From"; public static final String HDR_MAX_FORWARDS = "Max-Forwards"; public static final String HDR_RECORD_ROUTE = "Record-Route"; public static final String HDR_PROXY_AUTHENTICATE = "Proxy-Authenticate"; public static final String HDR_PROXY_AUTHORIZATION = "Proxy-Authorization"; public static final String HDR_ROUTE = "Route"; public static final String HDR_SUBJECT = "Subject"; public static final String HDR_SUPPORTED = "Supported"; public static final String HDR_TO = "To"; public static final String HDR_VIA = "Via"; public static final String HDR_WWW_AUTHENTICATE = "WWW-Authenticate"; //Compact form public static final char COMPACT_HDR_CALLID = 'i'; public static final char COMPACT_HDR_CONTACT = 'm'; public static final char COMPACT_HDR_CONTENT_ENCODING = 'e'; public static final char COMPACT_HDR_CONTENT_LENGTH = 'l'; public static final char COMPACT_HDR_CONTENT_TYPE = 'c'; public static final char COMPACT_HDR_FROM = 'f'; public static final char COMPACT_HDR_SUBJECT = 's'; public static final char COMPACT_HDR_SUPPORTED = 'k'; public static final char COMPACT_HDR_TO = 't'; public static final char COMPACT_HDR_VIA = 'v'; //Parameters public static final String PARAM_BRANCH = "branch"; public static final String PARAM_EXPIRES = "expires"; public static final String PARAM_MADDR = "maddr"; public static final String PARAM_RECEIVED = "received"; public static final String PARAM_RPORT = "rport"; public static final String PARAM_SENTBY = "sent-by"; public static final String PARAM_TAG = "tag"; public static final String PARAM_TRANSPORT = "transport"; public static final String PARAM_TTL = "ttl"; public static final String PARAM_SEPARATOR = ";"; public static final String PARAM_ASSIGNMENT = "="; //Miscellaneous public static final char FIELD_NAME_SEPARATOR = ':'; public static final String DEFAULT_SIP_VERSION = "SIP/2.0"; public static final String CRLF = "\r\n"; public static final String IPV4_TTL = "1"; public static final char AT = '@'; public static final String LOOSE_ROUTING = "lr"; public static final char LEFT_ANGLE_BRACKET = '<'; public static final char RIGHT_ANGLE_BRACKET = '>'; public static final String HEADER_SEPARATOR = ","; //STATUS CODES public static final int CODE_MIN_PROV = 100; public static final int CODE_MIN_SUCCESS = 200; public static final int CODE_MIN_REDIR = 300; public static final int CODE_MAX = 699; public static final int CODE_100_TRYING = 100; public static final int CODE_180_RINGING = 180; public static final int CODE_200_OK = 200; public static final int CODE_401_UNAUTHORIZED = 401; public static final int CODE_405_METHOD_NOT_ALLOWED = 405; public static final int CODE_407_PROXY_AUTHENTICATION_REQUIRED = 407; public static final int CODE_481_CALL_TRANSACTION_DOES_NOT_EXIST = 481; public static final int CODE_486_BUSYHERE = 486; public static final int CODE_487_REQUEST_TERMINATED = 487; public static final int CODE_500_SERVER_INTERNAL_ERROR = 500; //REASON PHRASES public static final String REASON_180_RINGING = "Ringing"; public static final String REASON_200_OK = "OK"; public static final String REASON_405_METHOD_NOT_ALLOWED = "Method Not Allowed"; public static final String REASON_481_CALL_TRANSACTION_DOES_NOT_EXIST = "Call/Transaction Does Not Exist"; public static final String REASON_486_BUSYHERE = "Busy Here"; public static final String REASON_487_REQUEST_TERMINATED = "Request Terminated"; public static final String REASON_500_SERVER_INTERNAL_ERROR = "Server Internal Error"; //TRANSPORT public static final String TRANSPORT_UDP = "UDP"; public static final String TRANSPORT_TCP = "TCP"; public static final String TRANSPORT_SCTP = "SCTP"; public static final String TRANSPORT_TLS = "TLS"; public static final int TRANSPORT_UDP_USUAL_MAX_SIZE = 1300; public static final int TRANSPORT_UDP_MAX_SIZE = 65535; public static final char TRANSPORT_VIA_SEP = '/'; public static final char TRANSPORT_VIA_SEP2 = ' '; public static final int TRANSPORT_DEFAULT_PORT = 5060; public static final int TRANSPORT_TLS_PORT = 5061; public static final char TRANSPORT_PORT_SEP = ':'; //TRANSACTION //TRANSACTION USER public static final int DEFAULT_MAXFORWARDS = 70; public static final String BRANCHID_MAGIC_COOKIE = "z9hG4bK"; public static final String SIP_SCHEME = "sip"; public static final char SCHEME_SEPARATOR = ':'; //TIMERS (in milliseconds) public static final int TIMER_T1 = 500; public static final int TIMER_T2 = 4000; public static final int TIMER_T4 = 5000; public static final int TIMER_INVITE_CLIENT_TRANSACTION = 32000; //TRANSACTION USER //CORE public static final String CONTENT_TYPE_SDP = "application/sdp"; public static final int DEFAULT_EXPIRES = 3600; }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/Utils.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip; import java.net.InetAddress; import net.sourceforge.peers.sip.core.useragent.UAS; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldMultiValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transport.SipMessage; public class Utils { public static final String PEERSHOME_SYSTEM_PROPERTY = "peers.home"; public static final String DEFAULT_PEERS_HOME = "."; public final static SipHeaderFieldValue getTopVia(SipMessage sipMessage) { SipHeaders sipHeaders = sipMessage.getSipHeaders(); SipHeaderFieldName viaName = new SipHeaderFieldName(RFC3261.HDR_VIA); SipHeaderFieldValue via = sipHeaders.get(viaName); if (via instanceof SipHeaderFieldMultiValue) { via = ((SipHeaderFieldMultiValue)via).getValues().get(0); } return via; } public final static String generateTag() { return randomString(8); } public final static String generateCallID(InetAddress inetAddress) { //TODO make a hash using current time millis, public ip @, private @, and a random string StringBuffer buf = new StringBuffer(); buf.append(randomString(8)); buf.append('-'); buf.append(String.valueOf(System.currentTimeMillis())); buf.append('@'); buf.append(inetAddress.getHostName()); return buf.toString(); } public final static String generateBranchId() { StringBuffer buf = new StringBuffer(); buf.append(RFC3261.BRANCHID_MAGIC_COOKIE); //TODO must be unique across space and time... buf.append(randomString(9)); return buf.toString(); } public final static String getMessageCallId(SipMessage sipMessage) { if (sipMessage == null || sipMessage.getSipHeaders() == null) return null; SipHeaderFieldValue callId = sipMessage.getSipHeaders().get( new SipHeaderFieldName(RFC3261.HDR_CALLID)); if (callId == null) return null; return callId.getValue(); } public final static String randomString(int length) { String chars = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIFKLMNOPRSTUVWXYZ" + "0123456789"; StringBuffer buf = new StringBuffer(length); for (int i = 0; i < length; ++i) { int pos = (int)Math.round(Math.random() * (chars.length() - 1)); buf.append(chars.charAt(pos)); } return buf.toString(); } public final static void copyHeader(SipMessage src, SipMessage dst, String name) { SipHeaderFieldName sipHeaderFieldName = new SipHeaderFieldName(name); SipHeaderFieldValue sipHeaderFieldValue = src.getSipHeaders().get(sipHeaderFieldName); if (sipHeaderFieldValue != null) { dst.getSipHeaders().add(sipHeaderFieldName, sipHeaderFieldValue); } } public final static String getUserPart(String sipUri) { int start = sipUri.indexOf(RFC3261.SCHEME_SEPARATOR); int end = sipUri.indexOf(RFC3261.AT); return sipUri.substring(start + 1, end); } /** * adds Max-Forwards Supported and Require headers * @param headers */ public final static void addCommonHeaders(SipHeaders headers) { //Max-Forwards headers.add(new SipHeaderFieldName(RFC3261.HDR_MAX_FORWARDS), new SipHeaderFieldValue( String.valueOf(RFC3261.DEFAULT_MAXFORWARDS))); //TODO Supported and Require } public final static String generateAllowHeader() { StringBuffer buf = new StringBuffer(); for (String supportedMethod: UAS.SUPPORTED_METHODS) { buf.append(supportedMethod); buf.append(", "); } int bufLength = buf.length(); buf.delete(bufLength - 2, bufLength); return buf.toString(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/ChallengeManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2008-2013 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC2617; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public class ChallengeManager implements MessageInterceptor { public static final String ALGORITHM_MD5 = "MD5"; private String username; private String password; private String realm; private String nonce; private String opaque; private String requestUri; private String digest; private String profileUri; private String qop; private String cnonce; private String authorizationUsername; private static volatile int nonceCount = 1; private String nonceCountHex; private Config config; private Logger logger; // FIXME what happens if a challenge is received for a register-refresh // and another challenge is received in the mean time for an invite? private int statusCode; private SipHeaderFieldValue contact; private InitialRequestManager initialRequestManager; private MidDialogRequestManager midDialogRequestManager; private DialogManager dialogManager; public ChallengeManager(Config config, InitialRequestManager initialRequestManager, MidDialogRequestManager midDialogRequestManager, DialogManager dialogManager, Logger logger) { this.config = config; this.initialRequestManager = initialRequestManager; this.midDialogRequestManager = midDialogRequestManager; this.dialogManager = dialogManager; this.logger = logger; init(); } private void init() { username = config.getUserPart(); authorizationUsername = config.getAuthorizationUsername(); if (authorizationUsername == null || authorizationUsername.isEmpty()) { authorizationUsername = username; } password = config.getPassword(); profileUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + username + RFC3261.AT + config.getDomain(); } private String md5hash(String message) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(ALGORITHM_MD5); } catch (NoSuchAlgorithmException e) { logger.error("no such algorithm " + ALGORITHM_MD5, e); return null; } byte[] messageBytes = message.getBytes(); byte[] messageMd5 = messageDigest.digest(messageBytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(out); for (byte b : messageMd5) { int u_b = (b < 0) ? 256 + b : b; printStream.printf("%02x", u_b); } return out.toString(); } public void handleChallenge(SipRequest sipRequest, SipResponse sipResponse) { init(); statusCode = sipResponse.getStatusCode(); SipHeaders responseHeaders = sipResponse.getSipHeaders(); SipHeaders requestHeaders = sipRequest.getSipHeaders(); contact = requestHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CONTACT)); SipHeaderFieldValue authenticate; SipHeaderFieldName authenticateHeaderName; if (statusCode == RFC3261.CODE_401_UNAUTHORIZED) { authenticateHeaderName = new SipHeaderFieldName( RFC3261.HDR_WWW_AUTHENTICATE); } else if (statusCode == RFC3261.CODE_407_PROXY_AUTHENTICATION_REQUIRED) { authenticateHeaderName = new SipHeaderFieldName( RFC3261.HDR_PROXY_AUTHENTICATE); } else { return; } authenticate = responseHeaders.get(authenticateHeaderName); if (authenticate == null) { return; } if (!authenticate.getValue().startsWith(RFC2617.SCHEME_DIGEST)) { logger.info("unsupported challenge scheme in header: " + authenticate); return; } String headerValue = authenticate.getValue(); realm = getParameter(RFC2617.PARAM_REALM, headerValue); nonce = getParameter(RFC2617.PARAM_NONCE, headerValue); opaque = getParameter(RFC2617.PARAM_OPAQUE, headerValue); qop = getParameter(RFC2617.PARAM_QOP, headerValue); if( "auth".equals(qop)) { nonceCountHex = String.format("%08X", nonceCount++); } String method = sipRequest.getMethod(); requestUri = sipRequest.getRequestUri().toString(); cnonce = UUID.randomUUID().toString(); digest = getRequestDigest(method); // FIXME message should be copied "as is" not created anew from scratch // and this technique is not clean String callId = responseHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CALLID)).getValue(); Dialog dialog = dialogManager.getDialog(callId); if (dialog != null) { midDialogRequestManager.generateMidDialogRequest( dialog, RFC3261.METHOD_BYE, this); } else { SipHeaderFieldValue from = requestHeaders.get( new SipHeaderFieldName(RFC3261.HDR_FROM)); String fromTag = from.getParam(new SipHeaderParamName( RFC3261.PARAM_TAG)); try { initialRequestManager.createInitialRequest( requestUri, method, profileUri, callId, fromTag, this); } catch (SipUriSyntaxException e) { logger.error("syntax error", e); } } } private String getRequestDigest(String method) { StringBuffer buf = new StringBuffer(); buf.append(authorizationUsername); buf.append(RFC2617.DIGEST_SEPARATOR); buf.append(realm); buf.append(RFC2617.DIGEST_SEPARATOR); buf.append(password); String ha1 = md5hash(buf.toString()); buf = new StringBuffer(); buf.append(method); buf.append(RFC2617.DIGEST_SEPARATOR); buf.append(requestUri); String ha2 = md5hash(buf.toString()); buf = new StringBuffer(); buf.append(ha1); buf.append(RFC2617.DIGEST_SEPARATOR); buf.append(nonce); buf.append(RFC2617.DIGEST_SEPARATOR); if("auth".equals(qop)) { buf.append(nonceCountHex); buf.append(RFC2617.DIGEST_SEPARATOR); buf.append(cnonce); buf.append(RFC2617.DIGEST_SEPARATOR); buf.append(qop); buf.append(RFC2617.DIGEST_SEPARATOR); } buf.append(ha2); return md5hash(buf.toString()); } private String getParameter(String paramName, String header) { int paramPos = header.indexOf(paramName); if (paramPos < 0) { return null; } int paramNameLength = paramName.length(); if (paramPos + paramNameLength + 3 > header.length()) { logger.info("Malformed " + RFC3261.HDR_WWW_AUTHENTICATE + " header"); return null; } if (header.charAt(paramPos + paramNameLength) != RFC2617.PARAM_VALUE_SEPARATOR) { logger.info("Malformed " + RFC3261.HDR_WWW_AUTHENTICATE + " header"); return null; } if (header.charAt(paramPos + paramNameLength + 1) != RFC2617.PARAM_VALUE_DELIMITER) { logger.info("Malformed " + RFC3261.HDR_WWW_AUTHENTICATE + " header"); return null; } header = header.substring(paramPos + paramNameLength + 2); int endDelimiter = header.indexOf(RFC2617.PARAM_VALUE_DELIMITER); if (endDelimiter < 0) { logger.info("Malformed " + RFC3261.HDR_WWW_AUTHENTICATE + " header"); return null; } return header.substring(0, endDelimiter); } /** add xxxAuthorization header */ public void postProcess(SipMessage sipMessage) { if (realm == null || nonce == null || digest == null) { return; } SipHeaders sipHeaders = sipMessage.getSipHeaders(); String cseq = sipHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CSEQ)).getValue(); String method = cseq.substring(cseq.trim().lastIndexOf(' ') + 1); digest = getRequestDigest(method); StringBuffer buf = new StringBuffer(); buf.append(RFC2617.SCHEME_DIGEST).append(" "); appendParameter(buf, RFC2617.PARAM_USERNAME, authorizationUsername); buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_REALM, realm); buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_NONCE, nonce); buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_URI, requestUri); buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_RESPONSE, digest); if("auth".equals(qop)) { buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_NC, nonceCountHex); buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_CNONCE, cnonce); buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_QOP, qop); } if (opaque != null) { buf.append(RFC2617.PARAM_SEPARATOR).append(" "); appendParameter(buf, RFC2617.PARAM_OPAQUE, opaque); } SipHeaderFieldName authorizationName; if (statusCode == RFC3261.CODE_401_UNAUTHORIZED) { authorizationName = new SipHeaderFieldName( RFC3261.HDR_AUTHORIZATION); } else if (statusCode == RFC3261.CODE_407_PROXY_AUTHENTICATION_REQUIRED) { authorizationName = new SipHeaderFieldName( RFC3261.HDR_PROXY_AUTHORIZATION); } else { return; } sipHeaders.add(authorizationName, new SipHeaderFieldValue(buf.toString())); // manage authentication on unregister challenge... if (contact != null) { SipHeaderParamName expiresName = new SipHeaderParamName(RFC3261.PARAM_EXPIRES); String expiresString = contact.getParam(expiresName); if (expiresString != null && Integer.parseInt(expiresString) == 0) { SipHeaderFieldValue requestContact = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CONTACT)); requestContact.addParam(expiresName, expiresString); } } } private void appendParameter(StringBuffer buf, String name, String value) { buf.append(name); buf.append(RFC2617.PARAM_VALUE_SEPARATOR); buf.append(RFC2617.PARAM_VALUE_DELIMITER); buf.append(value); buf.append(RFC2617.PARAM_VALUE_DELIMITER); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/InitialRequestManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010, 2011 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.handlers.ByeHandler; import net.sourceforge.peers.sip.core.useragent.handlers.CancelHandler; import net.sourceforge.peers.sip.core.useragent.handlers.InviteHandler; import net.sourceforge.peers.sip.core.useragent.handlers.OptionsHandler; import net.sourceforge.peers.sip.core.useragent.handlers.RegisterHandler; import net.sourceforge.peers.sip.syntaxencoding.NameAddress; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransactionUser; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class InitialRequestManager extends RequestManager implements ServerTransactionUser { public InitialRequestManager(UserAgent userAgent, InviteHandler inviteHandler, CancelHandler cancelHandler, ByeHandler byeHandler, OptionsHandler optionsHandler, RegisterHandler registerHandler, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, inviteHandler, cancelHandler, byeHandler, optionsHandler, registerHandler, dialogManager, transactionManager, transportManager, logger); registerHandler.setInitialRequestManager(this); } /** * gives a new request outside of a dialog * * @param requestUri * @param method * @return * @throws SipUriSyntaxException */ public SipRequest getGenericRequest(String requestUri, String method, String profileUri, String callId, String fromTag) throws SipUriSyntaxException { //8.1.1 SipRequest request = new SipRequest(method, new SipURI(requestUri)); SipHeaders headers = request.getSipHeaders(); //String hostAddress = utils.getMyAddress().getHostAddress(); //Via //TODO no Via should be added directly by UAC, Via is normally added by Transaction layer // StringBuffer viaBuf = new StringBuffer(); // viaBuf.append(RFC3261.DEFAULT_SIP_VERSION); // // TODO choose real transport // viaBuf.append("/UDP "); // viaBuf.append(hostAddress); // SipHeaderFieldValue via = new SipHeaderFieldValue(viaBuf.toString()); // via.addParam(new SipHeaderParamName(RFC3261.PARAM_BRANCHID), // utils.generateBranchId()); // headers.add(new SipHeaderFieldName(RFC3261.HDR_VIA), via); Utils.addCommonHeaders(headers); //To NameAddress to = new NameAddress(requestUri); headers.add(new SipHeaderFieldName(RFC3261.HDR_TO), new SipHeaderFieldValue(to.toString())); //From NameAddress fromNA = new NameAddress(profileUri); SipHeaderFieldValue from = new SipHeaderFieldValue(fromNA.toString()); String localFromTag; if (fromTag != null) { localFromTag = fromTag; } else { localFromTag = Utils.generateTag(); } from.addParam(new SipHeaderParamName(RFC3261.PARAM_TAG), localFromTag); headers.add(new SipHeaderFieldName(RFC3261.HDR_FROM), from); //Call-ID SipHeaderFieldName callIdName = new SipHeaderFieldName(RFC3261.HDR_CALLID); String localCallId; if (callId != null) { localCallId = callId; } else { localCallId = Utils.generateCallID( userAgent.getConfig().getLocalInetAddress()); } headers.add(callIdName, new SipHeaderFieldValue(localCallId)); //CSeq headers.add(new SipHeaderFieldName(RFC3261.HDR_CSEQ), new SipHeaderFieldValue(userAgent.generateCSeq(method))); return request; } public SipRequest createInitialRequest(String requestUri, String method, String profileUri) throws SipUriSyntaxException { return createInitialRequest(requestUri, method, profileUri, null); } public SipRequest createInitialRequest(String requestUri, String method, String profileUri, String callId) throws SipUriSyntaxException { return createInitialRequest(requestUri, method, profileUri, callId, null, null); } public SipRequest createInitialRequest(String requestUri, String method, String profileUri, String callId, String fromTag, MessageInterceptor messageInterceptor) throws SipUriSyntaxException { SipRequest sipRequest = getGenericRequest(requestUri, method, profileUri, callId, fromTag); // TODO add route header for outbound proxy give it to xxxHandler to create // clientTransaction SipURI outboundProxy = userAgent.getOutboundProxy(); if (outboundProxy != null) { NameAddress outboundProxyNameAddress = new NameAddress(outboundProxy.toString()); sipRequest.getSipHeaders().add(new SipHeaderFieldName(RFC3261.HDR_ROUTE), new SipHeaderFieldValue(outboundProxyNameAddress.toString()), 0); } ClientTransaction clientTransaction = null; if (RFC3261.METHOD_INVITE.equals(method)) { clientTransaction = inviteHandler.preProcessInvite(sipRequest); } else if (RFC3261.METHOD_REGISTER.equals(method)) { clientTransaction = registerHandler.preProcessRegister(sipRequest); } createInitialRequestEnd(sipRequest, clientTransaction, profileUri, messageInterceptor, true); return sipRequest; } private void createInitialRequestEnd(SipRequest sipRequest, ClientTransaction clientTransaction, String profileUri, MessageInterceptor messageInterceptor, boolean addContact) { if (clientTransaction == null) { logger.error("method not supported"); return; } if (addContact) { addContact(sipRequest, clientTransaction.getContact(), profileUri); } if (messageInterceptor != null) { messageInterceptor.postProcess(sipRequest); } // TODO create message receiver on client transport port clientTransaction.start(); } public void createCancel(SipRequest inviteRequest, MidDialogRequestManager midDialogRequestManager, String profileUri) { SipHeaders inviteHeaders = inviteRequest.getSipHeaders(); SipHeaderFieldValue callId = inviteHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CALLID)); SipRequest sipRequest; try { sipRequest = getGenericRequest( inviteRequest.getRequestUri().toString(), RFC3261.METHOD_CANCEL, profileUri, callId.getValue(), null); } catch (SipUriSyntaxException e) { logger.error("syntax error", e); return; } ClientTransaction clientTransaction = null; clientTransaction = cancelHandler.preProcessCancel(sipRequest, inviteRequest, midDialogRequestManager); if (clientTransaction != null) { createInitialRequestEnd(sipRequest, clientTransaction, profileUri, null, false); } } public void manageInitialRequest(SipRequest sipRequest) { SipHeaders headers = sipRequest.getSipHeaders(); // TODO authentication //method inspection SipResponse sipResponse = null; if (!UAS.SUPPORTED_METHODS.contains(sipRequest.getMethod())) { //TODO generate 405 (using 8.2.6 &) with Allow header //(20.5) and send it sipResponse = generateResponse(sipRequest, null, RFC3261.CODE_405_METHOD_NOT_ALLOWED, RFC3261.REASON_405_METHOD_NOT_ALLOWED); SipHeaders sipHeaders = sipResponse.getSipHeaders(); sipHeaders.add(new SipHeaderFieldName(RFC3261.HDR_ALLOW), new SipHeaderFieldValue(Utils.generateAllowHeader())); } SipHeaderFieldValue contentType = headers.get(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE)); if (contentType != null) { if (!RFC3261.CONTENT_TYPE_SDP.equals(contentType.getValue())) { //TODO generate 415 with a Accept header listing supported content types //8.2.3 } } //etc. if (sipResponse != null) { ServerTransaction serverTransaction = transactionManager.createServerTransaction( sipResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); serverTransaction.start(); serverTransaction.receivedRequest(sipRequest); serverTransaction.sendReponse(sipResponse); } //TODO create server transaction String method = sipRequest.getMethod(); if (RFC3261.METHOD_INVITE.equals(method)) { inviteHandler.handleInitialInvite(sipRequest); } else if (RFC3261.METHOD_CANCEL.equals(method)) { cancelHandler.handleCancel(sipRequest); } else if (RFC3261.METHOD_OPTIONS.equals(method)) { optionsHandler.handleOptions(sipRequest); } } public void addContact(SipRequest sipRequest, String contactEnd, String profileUri) { SipHeaders sipHeaders = sipRequest.getSipHeaders(); //Contact StringBuffer contactBuf = new StringBuffer(); contactBuf.append(RFC3261.SIP_SCHEME); contactBuf.append(RFC3261.SCHEME_SEPARATOR); String userPart = Utils.getUserPart(profileUri); contactBuf.append(userPart); contactBuf.append(RFC3261.AT); contactBuf.append(contactEnd); NameAddress contactNA = new NameAddress(contactBuf.toString()); SipHeaderFieldValue contact = new SipHeaderFieldValue(contactNA.toString()); sipHeaders.add(new SipHeaderFieldName(RFC3261.HDR_CONTACT), new SipHeaderFieldValue(contact.toString())); } /////////////////////////////////////////////////////////// // ServerTransactionUser methods /////////////////////////////////////////////////////////// @Override public void transactionFailure() { // TODO Auto-generated method stub } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/MessageInterceptor.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import net.sourceforge.peers.sip.transport.SipMessage; public interface MessageInterceptor { public void postProcess(SipMessage sipMessage); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/MidDialogRequestManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Hashtable; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.core.useragent.handlers.ByeHandler; import net.sourceforge.peers.sip.core.useragent.handlers.CancelHandler; import net.sourceforge.peers.sip.core.useragent.handlers.InviteHandler; import net.sourceforge.peers.sip.core.useragent.handlers.OptionsHandler; import net.sourceforge.peers.sip.core.useragent.handlers.RegisterHandler; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.ClientTransactionUser; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransactionUser; import net.sourceforge.peers.sip.transaction.Transaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class MidDialogRequestManager extends RequestManager implements ClientTransactionUser, ServerTransactionUser { public MidDialogRequestManager(UserAgent userAgent, InviteHandler inviteHandler, CancelHandler cancelHandler, ByeHandler byeHandler, OptionsHandler optionsHandler, RegisterHandler registerHandler, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, inviteHandler, cancelHandler, byeHandler, optionsHandler, registerHandler, dialogManager, transactionManager, transportManager, logger); } //////////////////////////////////////////////// // methods for UAC //////////////////////////////////////////////// public void generateMidDialogRequest(Dialog dialog, String method, MessageInterceptor messageInterceptor) { SipRequest sipRequest = dialog.buildSubsequentRequest(RFC3261.METHOD_BYE); if (RFC3261.METHOD_BYE.equals(method)) { byeHandler.preprocessBye(sipRequest, dialog); } //TODO check that subsequent request is supported before client //transaction creation if (!RFC3261.METHOD_INVITE.equals(method)) { ClientTransaction clientTransaction = createNonInviteClientTransaction( sipRequest, null, byeHandler); if (messageInterceptor != null) { messageInterceptor.postProcess(sipRequest); } if (clientTransaction != null) { clientTransaction.start(); } } else { //TODO client transaction user is managed by invite handler directly } } public ClientTransaction createNonInviteClientTransaction( SipRequest sipRequest, String branchId, ClientTransactionUser clientTransactionUser) { //8.1.2 SipURI destinationUri = RequestManager.getDestinationUri(sipRequest, logger); //TODO if header route is present, addrspec = toproute.nameaddress.addrspec String transport = RFC3261.TRANSPORT_UDP; Hashtable<String, String> params = destinationUri.getUriParameters(); if (params != null) { String reqUriTransport = params.get(RFC3261.PARAM_TRANSPORT); if (reqUriTransport != null) { transport = reqUriTransport; } } int port = destinationUri.getPort(); if (port == SipURI.DEFAULT_PORT) { port = RFC3261.TRANSPORT_DEFAULT_PORT; } SipURI sipUri = userAgent.getConfig().getOutboundProxy(); if (sipUri == null) { sipUri = destinationUri; } InetAddress inetAddress; try { inetAddress = InetAddress.getByName(sipUri.getHost()); } catch (UnknownHostException e) { logger.error("unknown host: " + sipUri.getHost(), e); return null; } ClientTransaction clientTransaction = transactionManager .createClientTransaction(sipRequest, inetAddress, port, transport, branchId, clientTransactionUser); return clientTransaction; } //////////////////////////////////////////////// // methods for UAS //////////////////////////////////////////////// public void manageMidDialogRequest(SipRequest sipRequest, Dialog dialog) { SipHeaders sipHeaders = sipRequest.getSipHeaders(); SipHeaderFieldValue cseq = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CSEQ)); String cseqStr = cseq.getValue(); int pos = cseqStr.indexOf(' '); if (pos < 0) { pos = cseqStr.indexOf('\t'); } int newCseq = Integer.parseInt(cseqStr.substring(0, pos)); int oldCseq = dialog.getRemoteCSeq(); if (oldCseq == Dialog.EMPTY_CSEQ) { dialog.setRemoteCSeq(newCseq); } else if (newCseq < oldCseq) { // out of order // RFC3261 12.2.2 p77 // TODO test out of order in-dialog-requests SipResponse sipResponse = generateResponse(sipRequest, dialog, RFC3261.CODE_500_SERVER_INTERNAL_ERROR, RFC3261.REASON_500_SERVER_INTERNAL_ERROR); ServerTransaction serverTransaction = transactionManager.createServerTransaction( sipResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); serverTransaction.start(); serverTransaction.receivedRequest(sipRequest); serverTransaction.sendReponse(sipResponse); } else { dialog.setRemoteCSeq(newCseq); } String method = sipRequest.getMethod(); if (RFC3261.METHOD_BYE.equals(method)) { byeHandler.handleBye(sipRequest, dialog); } else if (RFC3261.METHOD_INVITE.equals(method)) { inviteHandler.handleReInvite(sipRequest, dialog); } else if (RFC3261.METHOD_ACK.equals(method)) { inviteHandler.handleAck(sipRequest, dialog); } else if (RFC3261.METHOD_OPTIONS.equals(method)) { optionsHandler.handleOptions(sipRequest); } } /////////////////////////////////////// // ServerTransactionUser methods /////////////////////////////////////// @Override public void transactionFailure() { // TODO Auto-generated method stub } /////////////////////////////////////// // ClientTransactionUser methods /////////////////////////////////////// // callbacks employed for cancel responses (ignored) @Override public void transactionTimeout(ClientTransaction clientTransaction) { // TODO Auto-generated method stub } @Override public void provResponseReceived(SipResponse sipResponse, Transaction transaction) { // TODO Auto-generated method stub } @Override public void errResponseReceived(SipResponse sipResponse) { // TODO Auto-generated method stub } @Override public void successResponseReceived(SipResponse sipResponse, Transaction transaction) { // TODO Auto-generated method stub } @Override public void transactionTransportError() { // TODO Auto-generated method stub } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/RequestManager.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.core.useragent.handlers.ByeHandler; import net.sourceforge.peers.sip.core.useragent.handlers.CancelHandler; import net.sourceforge.peers.sip.core.useragent.handlers.InviteHandler; import net.sourceforge.peers.sip.core.useragent.handlers.OptionsHandler; import net.sourceforge.peers.sip.core.useragent.handlers.RegisterHandler; import net.sourceforge.peers.sip.syntaxencoding.NameAddress; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public abstract class RequestManager { public static SipURI getDestinationUri(SipRequest sipRequest, Logger logger) { SipHeaders requestHeaders = sipRequest.getSipHeaders(); SipURI destinationUri = null; SipHeaderFieldValue route = requestHeaders.get( new SipHeaderFieldName(RFC3261.HDR_ROUTE)); if (route != null) { try { destinationUri = new SipURI( NameAddress.nameAddressToUri(route.toString())); } catch (SipUriSyntaxException e) { logger.error("syntax error", e); } } if (destinationUri == null) { destinationUri = sipRequest.getRequestUri(); } return destinationUri; } public static SipResponse generateResponse(SipRequest sipRequest, Dialog dialog, int statusCode, String reasonPhrase) { //8.2.6.2 SipResponse sipResponse = new SipResponse(statusCode, reasonPhrase); SipHeaders requestHeaders = sipRequest.getSipHeaders(); SipHeaders responseHeaders = sipResponse.getSipHeaders(); SipHeaderFieldName fromName = new SipHeaderFieldName(RFC3261.HDR_FROM); responseHeaders.add(fromName, requestHeaders.get(fromName)); SipHeaderFieldName callIdName = new SipHeaderFieldName(RFC3261.HDR_CALLID); responseHeaders.add(callIdName, requestHeaders.get(callIdName)); SipHeaderFieldName cseqName = new SipHeaderFieldName(RFC3261.HDR_CSEQ); responseHeaders.add(cseqName, requestHeaders.get(cseqName)); SipHeaderFieldName viaName = new SipHeaderFieldName(RFC3261.HDR_VIA); responseHeaders.add(viaName, requestHeaders.get(viaName));//TODO check ordering SipHeaderFieldName toName = new SipHeaderFieldName(RFC3261.HDR_TO); SipHeaderFieldValue toValue = requestHeaders.get(toName); SipHeaderParamName toTagParamName = new SipHeaderParamName(RFC3261.PARAM_TAG); String toTag = toValue.getParam(toTagParamName); if (toTag == null) { if (dialog != null) { toTag = dialog.getLocalTag(); toValue.addParam(toTagParamName, toTag); } } responseHeaders.add(toName, toValue); return sipResponse; } protected InviteHandler inviteHandler; protected CancelHandler cancelHandler; protected ByeHandler byeHandler; protected OptionsHandler optionsHandler; protected RegisterHandler registerHandler; protected UserAgent userAgent; protected TransactionManager transactionManager; protected TransportManager transportManager; protected Logger logger; public RequestManager(UserAgent userAgent, InviteHandler inviteHandler, CancelHandler cancelHandler, ByeHandler byeHandler, OptionsHandler optionsHandler, RegisterHandler registerHandler, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { this.userAgent = userAgent; this.inviteHandler = inviteHandler; this.cancelHandler = cancelHandler; this.byeHandler = byeHandler; this.optionsHandler = optionsHandler; this.registerHandler = registerHandler; this.transactionManager = transactionManager; this.transportManager = transportManager; this.logger = logger; } public InviteHandler getInviteHandler() { return inviteHandler; } public ByeHandler getByeHandler() { return byeHandler; } public RegisterHandler getRegisterHandler() { return registerHandler; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/SipEvent.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010, 2011 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import net.sourceforge.peers.sip.transport.SipMessage; public class SipEvent { public enum EventType { ERROR, RINGING, INCOMING_CALL, CALLEE_PICKUP; } private EventType eventType; private SipMessage sipMessage; public SipEvent(EventType type, SipMessage sipMessage) { this.eventType = type; this.sipMessage = sipMessage; } public SipMessage getSipMessage() { return sipMessage; } public EventType getEventType() { return eventType; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/SipListener.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public interface SipListener { void registering(SipRequest sipRequest); void registerSuccessful(SipResponse sipResponse); void registerFailed(SipResponse sipResponse); void incomingCall(SipRequest sipRequest, SipResponse provResponse); void remoteHangup(SipRequest sipRequest); void ringing(SipResponse sipResponse); void calleePickup(SipResponse sipResponse); void error(SipResponse sipResponse); void dtmfEvent(RFC4733.DTMFEvent dtmfEvent, int duration); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/UAC.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.InviteClientTransaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transactionuser.DialogState; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class UAC { private InitialRequestManager initialRequestManager; private MidDialogRequestManager midDialogRequestManager; private String registerCallID; private String profileUri; //FIXME private UserAgent userAgent; private TransactionManager transactionManager; private DialogManager dialogManager; private List<String> guiClosedCallIds; private Logger logger; /** * should be instanciated only once, it was a singleton. */ public UAC(UserAgent userAgent, InitialRequestManager initialRequestManager, MidDialogRequestManager midDialogRequestManager, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { this.userAgent = userAgent; this.initialRequestManager = initialRequestManager; this.midDialogRequestManager = midDialogRequestManager; this.dialogManager = dialogManager; this.transactionManager = transactionManager; this.logger = logger; guiClosedCallIds = Collections.synchronizedList(new ArrayList<String>()); profileUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + userAgent.getUserpart() + RFC3261.AT + userAgent.getDomain(); } /** * For the moment we consider that only one profile uri is used at a time. * @throws SipUriSyntaxException */ SipRequest register() throws SipUriSyntaxException { String domain = userAgent.getDomain(); String requestUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + domain; SipListener sipListener = userAgent.getSipListener(); profileUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + userAgent.getUserpart() + RFC3261.AT + domain; registerCallID = Utils.generateCallID( userAgent.getConfig().getLocalInetAddress()); SipRequest sipRequest = initialRequestManager.createInitialRequest( requestUri, RFC3261.METHOD_REGISTER, profileUri, registerCallID); if (sipListener != null) { sipListener.registering(sipRequest); } return sipRequest; } void unregister() throws SipUriSyntaxException { if (getInitialRequestManager().getRegisterHandler().isRegistered()) { String requestUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + userAgent.getDomain(); MessageInterceptor messageInterceptor = new MessageInterceptor() { @Override public void postProcess(SipMessage sipMessage) { initialRequestManager.registerHandler.unregister(); SipHeaders sipHeaders = sipMessage.getSipHeaders(); SipHeaderFieldValue contact = sipHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CONTACT)); contact.addParam(new SipHeaderParamName(RFC3261.PARAM_EXPIRES), "0"); } }; // for any reason, asterisk requires a new Call-ID to unregister registerCallID = Utils.generateCallID( userAgent.getConfig().getLocalInetAddress()); initialRequestManager.createInitialRequest(requestUri, RFC3261.METHOD_REGISTER, profileUri, registerCallID, null, messageInterceptor); } } SipRequest invite(String requestUri, String callId) throws SipUriSyntaxException { return initialRequestManager.createInitialRequest(requestUri, RFC3261.METHOD_INVITE, profileUri, callId); } private SipRequest getInviteWithAuth(String callId) { List<ClientTransaction> clientTransactions = transactionManager.getClientTransactionsFromCallId(callId, RFC3261.METHOD_INVITE); SipRequest sipRequestNoAuth = null; for (ClientTransaction clientTransaction: clientTransactions) { InviteClientTransaction inviteClientTransaction = (InviteClientTransaction)clientTransaction; SipRequest sipRequest = inviteClientTransaction.getRequest(); SipHeaders sipHeaders = sipRequest.getSipHeaders(); SipHeaderFieldName authorization = new SipHeaderFieldName( RFC3261.HDR_AUTHORIZATION); SipHeaderFieldValue value = sipHeaders.get(authorization); if (value == null) { SipHeaderFieldName proxyAuthorization = new SipHeaderFieldName( RFC3261.HDR_PROXY_AUTHORIZATION); value = sipHeaders.get(proxyAuthorization); } if (value != null) { return sipRequest; } sipRequestNoAuth = sipRequest; } return sipRequestNoAuth; } void terminate(SipRequest sipRequest) { String callId = Utils.getMessageCallId(sipRequest); if (callId != null && !guiClosedCallIds.contains(callId)) { guiClosedCallIds.add(callId); } Dialog dialog = dialogManager.getDialog(callId); SipRequest inviteWithAuth = getInviteWithAuth(callId); SipRequest originatingRequest; if (inviteWithAuth != null) { originatingRequest = inviteWithAuth; } else { originatingRequest = sipRequest; } if (dialog != null) { ClientTransaction clientTransaction = (originatingRequest != null)?transactionManager.getClientTransaction(originatingRequest):null; if (clientTransaction != null) { synchronized (clientTransaction) { DialogState dialogState = dialog.getState(); if (dialog.EARLY.equals(dialogState)) { initialRequestManager.createCancel(originatingRequest, midDialogRequestManager, profileUri); } else if (dialog.CONFIRMED.equals(dialogState)) { // clientTransaction not yet removed midDialogRequestManager.generateMidDialogRequest( dialog, RFC3261.METHOD_BYE, null); guiClosedCallIds.remove(callId); } } } else { // clientTransaction Terminated and removed logger.debug("clientTransaction null"); midDialogRequestManager.generateMidDialogRequest( dialog, RFC3261.METHOD_BYE, null); guiClosedCallIds.remove(callId); } } else { InviteClientTransaction inviteClientTransaction = (originatingRequest != null)?(InviteClientTransaction)transactionManager.getClientTransaction(originatingRequest):null; if (inviteClientTransaction == null) { logger.error("cannot find invite client transaction" + " for call " + callId); } else { SipResponse sipResponse = inviteClientTransaction.getLastResponse(); if (sipResponse != null) { int statusCode = sipResponse.getStatusCode(); if (statusCode < RFC3261.CODE_200_OK) { initialRequestManager.createCancel(originatingRequest, midDialogRequestManager, profileUri); } } } } userAgent.getMediaManager().stopSession(); } public InitialRequestManager getInitialRequestManager() { return initialRequestManager; } public List<String> getGuiClosedCallIds() { return guiClosedCallIds; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/UAS.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import java.net.SocketException; import java.util.ArrayList; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.SipServerTransportUser; import net.sourceforge.peers.sip.transport.TransportManager; public class UAS implements SipServerTransportUser { public final static ArrayList<String> SUPPORTED_METHODS; static { SUPPORTED_METHODS = new ArrayList<String>(); SUPPORTED_METHODS.add(RFC3261.METHOD_INVITE); SUPPORTED_METHODS.add(RFC3261.METHOD_ACK); SUPPORTED_METHODS.add(RFC3261.METHOD_CANCEL); SUPPORTED_METHODS.add(RFC3261.METHOD_OPTIONS); SUPPORTED_METHODS.add(RFC3261.METHOD_BYE); }; private InitialRequestManager initialRequestManager; private MidDialogRequestManager midDialogRequestManager; private DialogManager dialogManager; /** * should be instanciated only once, it was a singleton. */ public UAS(UserAgent userAgent, InitialRequestManager initialRequestManager, MidDialogRequestManager midDialogRequestManager, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager) throws SocketException { this.initialRequestManager = initialRequestManager; this.midDialogRequestManager = midDialogRequestManager; this.dialogManager = dialogManager; transportManager.setSipServerTransportUser(this); transportManager.createServerTransport( RFC3261.TRANSPORT_UDP, userAgent.getConfig().getSipPort()); } public void messageReceived(SipMessage sipMessage) { if (sipMessage instanceof SipRequest) { requestReceived((SipRequest) sipMessage); } else if (sipMessage instanceof SipResponse) { responseReceived((SipResponse) sipMessage); } else { throw new RuntimeException("unknown message type"); } } private void responseReceived(SipResponse sipResponse) { } private void requestReceived(SipRequest sipRequest) { //TODO 8.2 //TODO JTA to make request processing atomic SipHeaders headers = sipRequest.getSipHeaders(); //TODO find whether the request is within an existing dialog or not SipHeaderFieldValue to = headers.get(new SipHeaderFieldName(RFC3261.HDR_TO)); String toTag = to.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG)); if (toTag != null) { Dialog dialog = dialogManager.getDialog(sipRequest); if (dialog != null) { //this is a mid-dialog request midDialogRequestManager.manageMidDialogRequest(sipRequest, dialog); //TODO continue processing } else { //TODO reject the request with a 481 Call/Transaction Does Not Exist } } else { initialRequestManager.manageInitialRequest(sipRequest); } } void acceptCall(SipRequest sipRequest, Dialog dialog) { initialRequestManager.getInviteHandler().acceptCall(sipRequest, dialog); } void rejectCall(SipRequest sipRequest) { initialRequestManager.getInviteHandler().rejectCall(sipRequest); } public InitialRequestManager getInitialRequestManager() { return initialRequestManager; } public MidDialogRequestManager getMidDialogRequestManager() { return midDialogRequestManager; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/UserAgent.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent; import net.sourceforge.peers.Config; import net.sourceforge.peers.FileLogger; import net.sourceforge.peers.Logger; import net.sourceforge.peers.XmlConfig; import net.sourceforge.peers.media.*; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sdp.SDPManager; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.handlers.ByeHandler; import net.sourceforge.peers.sip.core.useragent.handlers.CancelHandler; import net.sourceforge.peers.sip.core.useragent.handlers.InviteHandler; import net.sourceforge.peers.sip.core.useragent.handlers.OptionsHandler; import net.sourceforge.peers.sip.core.useragent.handlers.RegisterHandler; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transaction.Transaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; import java.io.File; import java.net.SocketException; import java.util.ArrayList; import java.util.List; public class UserAgent implements DtmfEventHandler { public final static String CONFIG_FILE = "conf" + File.separator + "peers.xml"; public final static int RTP_DEFAULT_PORT = 8000; private String peersHome; private Logger logger; private Config config; private List<String> peers; //private List<Dialog> dialogs; //TODO factorize echo and captureRtpSender private Echo echo; private UAC uac; private UAS uas; private ChallengeManager challengeManager; private DialogManager dialogManager; private TransactionManager transactionManager; private TransportManager transportManager; private InviteHandler inviteHandler; private int cseqCounter; private AbstractSoundManagerFactory abstractSoundManagerFactory; private SipListener sipListener; private SDPManager sdpManager; private MediaManager mediaManager; public UserAgent(SipListener sipListener, String peersHome, Logger logger) throws SocketException { this(sipListener, null, peersHome, logger); } public UserAgent(SipListener sipListener, Config config, Logger logger) throws SocketException { this(sipListener, config, null, logger); } private UserAgent(SipListener sipListener, Config config, String peersHome, Logger logger) throws SocketException { this(sipListener, null, config, peersHome, logger); } public UserAgent(SipListener sipListener, AbstractSoundManagerFactory abstractSoundManagerFactory, Config config, String peersHome, Logger logger) throws SocketException { this.sipListener = sipListener; this.abstractSoundManagerFactory = abstractSoundManagerFactory; if (peersHome == null) { peersHome = Utils.DEFAULT_PEERS_HOME; } this.peersHome = peersHome; if (logger == null) { logger = new FileLogger(this.peersHome); } this.logger = logger; if (config == null) { config = new XmlConfig(this.peersHome + File.separator + CONFIG_FILE, this.logger); } this.config = config; if (abstractSoundManagerFactory == null) { abstractSoundManagerFactory = new ConfigAbstractSoundManagerFactory(this.config, this.peersHome, this.logger); } this.abstractSoundManagerFactory = abstractSoundManagerFactory; cseqCounter = 1; StringBuffer buf = new StringBuffer(); buf.append("starting user agent ["); buf.append("myAddress: "); buf.append(config.getLocalInetAddress().getHostAddress()).append(", "); buf.append("sipPort: "); buf.append(config.getSipPort()).append(", "); buf.append("userpart: "); buf.append(config.getUserPart()).append(", "); buf.append("domain: "); buf.append(config.getDomain()).append("]"); logger.info(buf.toString()); //transaction user dialogManager = new DialogManager(logger); //transaction transactionManager = new TransactionManager(logger); //transport transportManager = new TransportManager(transactionManager, config, logger); transactionManager.setTransportManager(transportManager); //core inviteHandler = new InviteHandler(this, dialogManager, transactionManager, transportManager, logger); CancelHandler cancelHandler = new CancelHandler(this, dialogManager, transactionManager, transportManager, logger); ByeHandler byeHandler = new ByeHandler(this, dialogManager, transactionManager, transportManager, logger); OptionsHandler optionsHandler = new OptionsHandler(this, transactionManager, transportManager, logger); RegisterHandler registerHandler = new RegisterHandler(this, transactionManager, transportManager, logger); InitialRequestManager initialRequestManager = new InitialRequestManager( this, inviteHandler, cancelHandler, byeHandler, optionsHandler, registerHandler, dialogManager, transactionManager, transportManager, logger); MidDialogRequestManager midDialogRequestManager = new MidDialogRequestManager( this, inviteHandler, cancelHandler, byeHandler, optionsHandler, registerHandler, dialogManager, transactionManager, transportManager, logger); uas = new UAS(this, initialRequestManager, midDialogRequestManager, dialogManager, transactionManager, transportManager); uac = new UAC(this, initialRequestManager, midDialogRequestManager, dialogManager, transactionManager, transportManager, logger); challengeManager = new ChallengeManager(config, initialRequestManager, midDialogRequestManager, dialogManager, logger); registerHandler.setChallengeManager(challengeManager); inviteHandler.setChallengeManager(challengeManager); byeHandler.setChallengeManager(challengeManager); peers = new ArrayList<String>(); //dialogs = new ArrayList<Dialog>(); sdpManager = new SDPManager(this, logger); inviteHandler.setSdpManager(sdpManager); optionsHandler.setSdpManager(sdpManager); mediaManager = new MediaManager(this, this, logger); } // client methods public void close() { transportManager.closeTransports(); transactionManager.closeTimers(); inviteHandler.closeTimers(); mediaManager.stopSession(); config.setPublicInetAddress(null); } public SipRequest register() throws SipUriSyntaxException { return uac.register(); } public void unregister() throws SipUriSyntaxException { uac.unregister(); } public SipRequest invite(String requestUri, String callId) throws SipUriSyntaxException { return uac.invite(requestUri, callId); } public void terminate(SipRequest sipRequest) { uac.terminate(sipRequest); } public void acceptCall(SipRequest sipRequest, Dialog dialog) { uas.acceptCall(sipRequest, dialog); } public void rejectCall(SipRequest sipRequest) { uas.rejectCall(sipRequest); } /** * Gives the sipMessage if sipMessage is a SipRequest or * the SipRequest corresponding to the SipResponse * if sipMessage is a SipResponse * @param sipMessage * @return null if sipMessage is neither a SipRequest neither a SipResponse */ public SipRequest getSipRequest(SipMessage sipMessage) { if (sipMessage instanceof SipRequest) { return (SipRequest) sipMessage; } else if (sipMessage instanceof SipResponse) { SipResponse sipResponse = (SipResponse) sipMessage; Transaction transaction = (Transaction)transactionManager .getClientTransaction(sipResponse); if (transaction == null) { transaction = (Transaction)transactionManager .getServerTransaction(sipResponse); } if (transaction == null) { return null; } return transaction.getRequest(); } else { return null; } } // public List<Dialog> getDialogs() { // return dialogs; // } public List<String> getPeers() { return peers; } // public Dialog getDialog(String peer) { // for (Dialog dialog : dialogs) { // String remoteUri = dialog.getRemoteUri(); // if (remoteUri != null) { // if (remoteUri.contains(peer)) { // return dialog; // } // } // } // return null; // } public String generateCSeq(String method) { StringBuffer buf = new StringBuffer(); buf.append(cseqCounter++); buf.append(' '); buf.append(method); return buf.toString(); } public boolean isRegistered() { return uac.getInitialRequestManager().getRegisterHandler() .isRegistered(); } public UAS getUas() { return uas; } public UAC getUac() { return uac; } public DialogManager getDialogManager() { return dialogManager; } public int getSipPort() { return transportManager.getSipPort(); } public int getRtpPort() { return config.getRtpPort(); } public String getDomain() { return config.getDomain(); } public String getUserpart() { return config.getUserPart(); } public MediaMode getMediaMode() { return config.getMediaMode(); } public boolean isMediaDebug() { return config.isMediaDebug(); } public SipURI getOutboundProxy() { return config.getOutboundProxy(); } public Echo getEcho() { return echo; } public void setEcho(Echo echo) { this.echo = echo; } public AbstractSoundManagerFactory getAbstractSoundManagerFactory() { return abstractSoundManagerFactory; } public SipListener getSipListener() { return sipListener; } public MediaManager getMediaManager() { return mediaManager; } public Config getConfig() { return config; } public String getPeersHome() { return peersHome; } public TransportManager getTransportManager() { return transportManager; } @Override public void dtmfDetected(RFC4733.DTMFEvent dtmfEvent, int duration) { sipListener.dtmfEvent(dtmfEvent, duration); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/ByeHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.core.useragent.RequestManager; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.ClientTransactionUser; import net.sourceforge.peers.sip.transaction.NonInviteClientTransaction; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransactionUser; import net.sourceforge.peers.sip.transaction.Transaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class ByeHandler extends DialogMethodHandler implements ServerTransactionUser, ClientTransactionUser { public ByeHandler(UserAgent userAgent, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, dialogManager, transactionManager, transportManager, logger); } //////////////////////////////////////////////// // methods for UAC //////////////////////////////////////////////// public void preprocessBye(SipRequest sipRequest, Dialog dialog) { // 15.1.1 String addrSpec = sipRequest.getRequestUri().toString(); userAgent.getPeers().remove(addrSpec); challengeManager.postProcess(sipRequest); } //////////////////////////////////////////////// // methods for UAS //////////////////////////////////////////////// public void handleBye(SipRequest sipRequest, Dialog dialog) { dialog.receivedOrSentBye(); //String remoteUri = dialog.getRemoteUri(); String addrSpec = sipRequest.getRequestUri().toString(); userAgent.getPeers().remove(addrSpec); dialogManager.removeDialog(dialog.getId()); logger.debug("removed dialog " + dialog.getId()); userAgent.getMediaManager().stopSession(); SipResponse sipResponse = RequestManager.generateResponse( sipRequest, dialog, RFC3261.CODE_200_OK, RFC3261.REASON_200_OK); // TODO determine port and transport for server transaction>transport // from initial invite // FIXME determine port and transport for server transaction>transport ServerTransaction serverTransaction = transactionManager .createServerTransaction( sipResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); serverTransaction.start(); serverTransaction.receivedRequest(sipRequest); serverTransaction.sendReponse(sipResponse); dialogManager.removeDialog(dialog.getId()); SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.remoteHangup(sipRequest); } // setChanged(); // notifyObservers(sipRequest); } /////////////////////////////////////// //ServerTransactionUser methods /////////////////////////////////////// public void transactionFailure() { // TODO Auto-generated method stub } /////////////////////////////////////// //ClientTransactionUser methods /////////////////////////////////////// @Override public void transactionTimeout(ClientTransaction clientTransaction) { // TODO Auto-generated method stub } @Override public void provResponseReceived(SipResponse sipResponse, Transaction transaction) { // TODO Auto-generated method stub } @Override public void errResponseReceived(SipResponse sipResponse) { int statusCode = sipResponse.getStatusCode(); if (statusCode == RFC3261.CODE_401_UNAUTHORIZED || statusCode == RFC3261.CODE_407_PROXY_AUTHENTICATION_REQUIRED && !challenged) { NonInviteClientTransaction nonInviteClientTransaction = (NonInviteClientTransaction) transactionManager.getClientTransaction(sipResponse); SipRequest sipRequest = nonInviteClientTransaction.getRequest(); String password = userAgent.getConfig().getPassword(); if (password != null && !"".equals(password.trim())) { challengeManager.handleChallenge(sipRequest, sipResponse); } challenged = true; } else { challenged = false; } } @Override public void successResponseReceived(SipResponse sipResponse, Transaction transaction) { Dialog dialog = dialogManager.getDialog(sipResponse); if (dialog == null) { return; } dialog.receivedOrSentBye(); dialogManager.removeDialog(dialog.getId()); logger.debug("removed dialog " + dialog.getId()); } @Override public void transactionTransportError() { // TODO Auto-generated method stub } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/CancelHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.MidDialogRequestManager; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.InviteClientTransaction; import net.sourceforge.peers.sip.transaction.InviteServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransactionUser; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class CancelHandler extends DialogMethodHandler implements ServerTransactionUser { public CancelHandler(UserAgent userAgent, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, dialogManager, transactionManager, transportManager, logger); } ////////////////////////////////////////////////////////// // UAS methods ////////////////////////////////////////////////////////// public void handleCancel(SipRequest sipRequest) { SipHeaderFieldValue topVia = Utils.getTopVia(sipRequest); String branchId = topVia.getParam(new SipHeaderParamName( RFC3261.PARAM_BRANCH)); InviteServerTransaction inviteServerTransaction = (InviteServerTransaction)transactionManager .getServerTransaction(branchId,RFC3261.METHOD_INVITE); SipResponse cancelResponse; if (inviteServerTransaction == null) { //TODO generate CANCEL 481 Call Leg/Transaction Does Not Exist cancelResponse = buildGenericResponse(sipRequest, RFC3261.CODE_481_CALL_TRANSACTION_DOES_NOT_EXIST, RFC3261.REASON_481_CALL_TRANSACTION_DOES_NOT_EXIST); } else { cancelResponse = buildGenericResponse(sipRequest, RFC3261.CODE_200_OK, RFC3261.REASON_200_OK); } ServerTransaction cancelServerTransaction = transactionManager .createServerTransaction(cancelResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); cancelServerTransaction.start(); cancelServerTransaction.receivedRequest(sipRequest); cancelServerTransaction.sendReponse(cancelResponse); if (cancelResponse.getStatusCode() != RFC3261.CODE_200_OK) { return; } SipResponse lastResponse = inviteServerTransaction.getLastResponse(); if (lastResponse != null && lastResponse.getStatusCode() >= RFC3261.CODE_200_OK) { return; } SipResponse inviteResponse = buildGenericResponse( inviteServerTransaction.getRequest(), RFC3261.CODE_487_REQUEST_TERMINATED, RFC3261.REASON_487_REQUEST_TERMINATED); inviteServerTransaction.sendReponse(inviteResponse); Dialog dialog = dialogManager.getDialog(lastResponse); dialog.receivedOrSent300To699(); SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.remoteHangup(sipRequest); } } ////////////////////////////////////////////////////////// // UAC methods ////////////////////////////////////////////////////////// public ClientTransaction preProcessCancel(SipRequest cancelGenericRequest, SipRequest inviteRequest, MidDialogRequestManager midDialogRequestManager) { //TODO //p. 54 §9.1 SipHeaders cancelHeaders = cancelGenericRequest.getSipHeaders(); SipHeaders inviteHeaders = inviteRequest.getSipHeaders(); //cseq SipHeaderFieldName cseqName = new SipHeaderFieldName(RFC3261.HDR_CSEQ); SipHeaderFieldValue cancelCseq = cancelHeaders.get(cseqName); SipHeaderFieldValue inviteCseq = inviteHeaders.get(cseqName); cancelCseq.setValue(inviteCseq.getValue().replace(RFC3261.METHOD_INVITE, RFC3261.METHOD_CANCEL)); //from SipHeaderFieldName fromName = new SipHeaderFieldName(RFC3261.HDR_FROM); SipHeaderFieldValue cancelFrom = cancelHeaders.get(fromName); SipHeaderFieldValue inviteFrom = inviteHeaders.get(fromName); cancelFrom.setValue(inviteFrom.getValue()); SipHeaderParamName tagParam = new SipHeaderParamName(RFC3261.PARAM_TAG); cancelFrom.removeParam(tagParam); cancelFrom.addParam(tagParam, inviteFrom.getParam(tagParam)); //top-via // cancelHeaders.add(new SipHeaderFieldName(RFC3261.HDR_VIA), // Utils.getInstance().getTopVia(inviteRequest)); SipHeaderFieldValue topVia = Utils.getTopVia(inviteRequest); String branchId = topVia.getParam(new SipHeaderParamName(RFC3261.PARAM_BRANCH)); //route SipHeaderFieldName routeName = new SipHeaderFieldName(RFC3261.HDR_ROUTE); SipHeaderFieldValue inviteRoute = inviteHeaders.get(routeName); if (inviteRoute != null) { cancelHeaders.add(routeName, inviteRoute); } InviteClientTransaction inviteClientTransaction = (InviteClientTransaction)transactionManager.getClientTransaction( inviteRequest); if (inviteClientTransaction != null) { SipResponse lastResponse = inviteClientTransaction.getLastResponse(); if (lastResponse != null && lastResponse.getStatusCode() >= RFC3261.CODE_200_OK) { return null; } } else { logger.error("cannot retrieve invite client transaction for" + " request " + inviteRequest); } return midDialogRequestManager.createNonInviteClientTransaction( cancelGenericRequest, branchId, midDialogRequestManager); } public void transactionFailure() { // TODO Auto-generated method stub } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/DialogMethodHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.TimerTask; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.NameAddress; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldMultiValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transaction.Transaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public abstract class DialogMethodHandler extends MethodHandler { protected DialogManager dialogManager; public DialogMethodHandler(UserAgent userAgent, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, transactionManager, transportManager, logger); this.dialogManager = dialogManager; } protected Dialog buildDialogForUas(SipResponse sipResponse, SipRequest sipRequest) { //12.1.1 //prepare response SipHeaders reqHeaders = sipRequest.getSipHeaders(); SipHeaders respHeaders = sipResponse.getSipHeaders(); //copy record-route SipHeaderFieldName recordRouteName = new SipHeaderFieldName(RFC3261.HDR_RECORD_ROUTE); SipHeaderFieldValue reqRecRoute = reqHeaders.get(recordRouteName); if (reqRecRoute != null) { respHeaders.add(recordRouteName, reqRecRoute); } //FIXME Contact header should probably added in response here. SipHeaderFieldName contactName = new SipHeaderFieldName(RFC3261.HDR_CONTACT); Dialog dialog = dialogManager.createDialog(sipResponse); //build dialog state //route set SipHeaderFieldValue recordRoute = respHeaders.get(new SipHeaderFieldName(RFC3261.HDR_RECORD_ROUTE)); ArrayList<String> routeSet = new ArrayList<String>(); if (recordRoute != null) { if (recordRoute instanceof SipHeaderFieldMultiValue) { SipHeaderFieldMultiValue multiRecordRoute = (SipHeaderFieldMultiValue) recordRoute; for (SipHeaderFieldValue routeValue : multiRecordRoute.getValues()) { routeSet.add(routeValue.getValue()); } } else { routeSet.add(recordRoute.getValue()); } } dialog.setRouteSet(routeSet); //remote target SipHeaderFieldValue reqContact = reqHeaders.get(contactName); String remoteTarget = reqContact.getValue(); if (remoteTarget.indexOf(RFC3261.LEFT_ANGLE_BRACKET) > -1) { remoteTarget = NameAddress.nameAddressToUri(remoteTarget); } dialog.setRemoteTarget(remoteTarget); //remote cseq SipHeaderFieldName cseqName = new SipHeaderFieldName(RFC3261.HDR_CSEQ); SipHeaderFieldValue cseq = reqHeaders.get(cseqName); String remoteCseq = cseq.getValue().substring(0, cseq.getValue().indexOf(' ')); dialog.setRemoteCSeq(Integer.parseInt(remoteCseq)); //callid SipHeaderFieldName callidName = new SipHeaderFieldName(RFC3261.HDR_CALLID); SipHeaderFieldValue callid = reqHeaders.get(callidName); dialog.setCallId(callid.getValue()); //local tag SipHeaderFieldName toName = new SipHeaderFieldName(RFC3261.HDR_TO); SipHeaderFieldValue to = respHeaders.get(toName); SipHeaderParamName tagName = new SipHeaderParamName(RFC3261.PARAM_TAG); String toTag = to.getParam(tagName); dialog.setLocalTag(toTag); //remote tag SipHeaderFieldName fromName = new SipHeaderFieldName(RFC3261.HDR_FROM); SipHeaderFieldValue from = reqHeaders.get(fromName); String fromTag = from.getParam(tagName); dialog.setRemoteTag(fromTag); //remote uri String remoteUri = from.getValue(); if (remoteUri.indexOf(RFC3261.LEFT_ANGLE_BRACKET) > -1) { remoteUri = NameAddress.nameAddressToUri(remoteUri); } dialog.setRemoteUri(remoteUri); //local uri String localUri = to.getValue(); if (localUri.indexOf(RFC3261.LEFT_ANGLE_BRACKET) > -1) { localUri = NameAddress.nameAddressToUri(localUri); } dialog.setLocalUri(localUri); return dialog; } //TODO throw an exception if dialog elements are lacking when dialog is built from 200 protected Dialog buildOrUpdateDialogForUac(SipResponse sipResponse, Transaction transaction) { SipHeaders headers = sipResponse.getSipHeaders(); Dialog dialog = dialogManager.getDialog(sipResponse); if (dialog == null) { dialog = dialogManager.createDialog(sipResponse); } //12.1.2 //TODO if request uri contains sips scheme or if sent over tls => dialog.setSecure(true) //route set ArrayList<String> routeSet = computeRouteSet(headers); if (routeSet != null) { dialog.setRouteSet(routeSet); } //remote target SipHeaderFieldValue contact = headers.get(new SipHeaderFieldName(RFC3261.HDR_CONTACT)); logger.debug("Contact: " + contact); if (contact != null) { String remoteTarget = NameAddress.nameAddressToUri(contact.toString()); dialog.setRemoteTarget(remoteTarget); } SipHeaders requestSipHeaders = transaction.getRequest().getSipHeaders(); //local cseq String requestCSeq = requestSipHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CSEQ)).toString(); requestCSeq = requestCSeq.substring(0, requestCSeq.indexOf(' ')); dialog.setLocalCSeq(Integer.parseInt(requestCSeq)); //callID //already done in createDialog() // String requestCallID = requestSipHeaders.get( // new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString(); // dialog.setCallId(requestCallID); //local tag //already done in createDialog() // SipHeaderFieldValue requestFrom = requestSipHeaders.get( // new SipHeaderFieldName(RFC3261.HDR_FROM)); // String requestFromTag = // requestFrom.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG)); // dialog.setLocalTag(requestFromTag); //remote tag //already done in createDialog() // dialog.setRemoteTag(toTag); //remote uri SipHeaderFieldValue to = headers.get(new SipHeaderFieldName(RFC3261.HDR_TO)); if (to != null) { String remoteUri = to.getValue(); if (remoteUri.indexOf(RFC3261.LEFT_ANGLE_BRACKET) > -1) { remoteUri = NameAddress.nameAddressToUri(remoteUri); } dialog.setRemoteUri(remoteUri); } //local uri SipHeaderFieldValue requestFrom = requestSipHeaders.get( new SipHeaderFieldName(RFC3261.HDR_FROM)); String localUri = requestFrom.getValue(); if (localUri.indexOf(RFC3261.LEFT_ANGLE_BRACKET) > -1) { localUri = NameAddress.nameAddressToUri(localUri); } dialog.setLocalUri(localUri); return dialog; } protected ArrayList<String> computeRouteSet(SipHeaders headers) { SipHeaderFieldValue recordRoute = headers.get(new SipHeaderFieldName(RFC3261.HDR_RECORD_ROUTE)); ArrayList<String> routeSet = new ArrayList<String>(); if (recordRoute != null) { if (recordRoute instanceof SipHeaderFieldMultiValue) { List<SipHeaderFieldValue> values = ((SipHeaderFieldMultiValue)recordRoute).getValues(); for (SipHeaderFieldValue value : values) { //reverse order routeSet.add(0, value.toString()); } } else { routeSet.add(recordRoute.toString()); } } return routeSet; } //TODO see if AckHandler is usable class AckTimerTask extends TimerTask { private String toUri; public AckTimerTask(String toUri) { super(); this.toUri = toUri; } @Override public void run() { ArrayList<Dialog> purgedDialogs = new ArrayList<Dialog>(); Collection<Dialog> dialogs = dialogManager.getDialogCollection(); for (Dialog dialog : dialogs) { String remoteUri = dialog.getRemoteUri(); if (remoteUri.equals(toUri) && !dialog.CONFIRMED.equals(dialog.getState())) { dialog.receivedOrSentBye(); purgedDialogs.add(dialog); } } for (Dialog dialog : purgedDialogs) { dialogs.remove(dialog); } } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/InviteHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import net.sourceforge.peers.Timer; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.MediaManager; import net.sourceforge.peers.sdp.Codec; import net.sourceforge.peers.sdp.MediaDestination; import net.sourceforge.peers.sdp.NoCodecException; import net.sourceforge.peers.sdp.SessionDescription; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.RequestManager; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.NameAddress; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.ClientTransactionUser; import net.sourceforge.peers.sip.transaction.InviteClientTransaction; import net.sourceforge.peers.sip.transaction.InviteServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransactionUser; import net.sourceforge.peers.sip.transaction.Transaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.MessageSender; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class InviteHandler extends DialogMethodHandler implements ServerTransactionUser, ClientTransactionUser { public static final int TIMEOUT = 100; private MediaDestination mediaDestination; private Timer ackTimer; private boolean initialIncomingInvite; public InviteHandler(UserAgent userAgent, DialogManager dialogManager, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, dialogManager, transactionManager, transportManager, logger); ackTimer = new Timer(getClass().getSimpleName() + " Ack " + Timer.class.getSimpleName()); } ////////////////////////////////////////////////////////// // UAS methods ////////////////////////////////////////////////////////// public void handleInitialInvite(SipRequest sipRequest) { initialIncomingInvite = true; //generate 180 Ringing SipResponse sipResponse = buildGenericResponse(sipRequest, RFC3261.CODE_180_RINGING, RFC3261.REASON_180_RINGING); Dialog dialog = buildDialogForUas(sipResponse, sipRequest); //here dialog is already stored in dialogs in DialogManager InviteServerTransaction inviteServerTransaction = (InviteServerTransaction) transactionManager.createServerTransaction(sipResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); inviteServerTransaction.start(); inviteServerTransaction.receivedRequest(sipRequest); //TODO send 180 more than once inviteServerTransaction.sendReponse(sipResponse); dialog.receivedOrSent1xx(); SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.incomingCall(sipRequest, sipResponse); } List<String> peers = userAgent.getPeers(); String responseTo = sipRequest.getSipHeaders().get( new SipHeaderFieldName(RFC3261.HDR_FROM)).getValue(); if (!peers.contains(responseTo)) { peers.add(responseTo); } } public void handleReInvite(SipRequest sipRequest, Dialog dialog) { logger.debug("handleReInvite"); initialIncomingInvite = false; SipHeaders sipHeaders = sipRequest.getSipHeaders(); // 12.2.2 update dialog SipHeaderFieldValue contact = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CONTACT)); if (contact != null) { String contactStr = contact.getValue(); if (contactStr.indexOf(RFC3261.LEFT_ANGLE_BRACKET) > -1) { contactStr = NameAddress.nameAddressToUri(contactStr); } dialog.setRemoteTarget(contactStr); } // update session sendSuccessfulResponse(sipRequest, dialog); } private DatagramSocket getDatagramSocket() { DatagramSocket datagramSocket = userAgent.getMediaManager() .getDatagramSocket(); if (datagramSocket == null) { // initial invite success response // AccessController.doPrivileged added for plugin compatibility datagramSocket = AccessController.doPrivileged( new PrivilegedAction<DatagramSocket>() { @Override public DatagramSocket run() { DatagramSocket datagramSocket = null; int rtpPort = userAgent.getConfig().getRtpPort(); try { if (rtpPort == 0) { int localPort = -1; while (localPort % 2 != 0) { datagramSocket = new DatagramSocket(); localPort = datagramSocket.getLocalPort(); if (localPort % 2 != 0) { datagramSocket.close(); } } } else { datagramSocket = new DatagramSocket(rtpPort); } } catch (SocketException e) { logger.error("cannot create datagram socket ", e); } return datagramSocket; } } ); logger.debug("new rtp DatagramSocket " + datagramSocket.hashCode()); try { datagramSocket.setSoTimeout(TIMEOUT); } catch (SocketException e) { logger.error("cannot set timeout on datagram socket ", e); } userAgent.getMediaManager().setDatagramSocket(datagramSocket); } return datagramSocket; } private synchronized void sendSuccessfulResponse(SipRequest sipRequest, Dialog dialog) { SipHeaders reqHeaders = sipRequest.getSipHeaders(); SipHeaderFieldValue contentType = reqHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE)); if (RFC3261.CONTENT_TYPE_SDP.equals(contentType)) { //TODO // String sdpResponse; // try { // sdpResponse = sdpManager.handleOffer( // new String(sipRequest.getBody())); // } catch (NoCodecException e) { // sdpResponse = sdpManager.generateErrorResponse(); // } } else { // TODO manage empty bodies and non-application/sdp content type } //TODO if mode autoanswer just send 200 without asking any question SipResponse sipResponse = RequestManager.generateResponse( sipRequest, dialog, RFC3261.CODE_200_OK, RFC3261.REASON_200_OK); // TODO 13.3 dialog invite-specific processing // TODO timer if there is an Expires header in INVITE // TODO 3xx // TODO 486 or 600 byte[] offerBytes = sipRequest.getBody(); SessionDescription answer; try { DatagramSocket datagramSocket = getDatagramSocket(); if (offerBytes != null && contentType != null && RFC3261.CONTENT_TYPE_SDP.equals(contentType.getValue())) { // create response in 200 try { SessionDescription offer = sdpManager.parse(offerBytes); answer = sdpManager.createSessionDescription(offer, datagramSocket.getLocalPort()); mediaDestination = sdpManager.getMediaDestination(offer); } catch (NoCodecException e) { answer = sdpManager.createSessionDescription(null, datagramSocket.getLocalPort()); } } else { // create offer in 200 (never tested...) answer = sdpManager.createSessionDescription(null, datagramSocket.getLocalPort()); } sipResponse.setBody(answer.toString().getBytes()); } catch (IOException e) { logger.error(e.getMessage(), e); } SipHeaders respHeaders = sipResponse.getSipHeaders(); respHeaders.add(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE), new SipHeaderFieldValue(RFC3261.CONTENT_TYPE_SDP)); ArrayList<String> routeSet = dialog.getRouteSet(); if (routeSet != null) { SipHeaderFieldName recordRoute = new SipHeaderFieldName(RFC3261.HDR_RECORD_ROUTE); for (String route : routeSet) { respHeaders.add(recordRoute, new SipHeaderFieldValue(route)); } } // TODO determine port and transport for server transaction>transport // from initial invite // FIXME determine port and transport for server transaction>transport ServerTransaction serverTransaction = transactionManager .getServerTransaction(sipRequest); if (serverTransaction == null) { // in re-INVITE case, no serverTransaction has been created serverTransaction = (InviteServerTransaction) transactionManager.createServerTransaction(sipResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); } serverTransaction.start(); serverTransaction.receivedRequest(sipRequest); serverTransaction.sendReponse(sipResponse); // TODO manage retransmission of the response (send to the transport) // until ACK arrives, if no ACK is received within 64*T1, confirm dialog // and terminate it with a BYE // logger.getInstance().debug("before dialog.receivedOrSent2xx();"); // logger.getInstance().debug("dialog state: " + dialog.getState()); } public void acceptCall(SipRequest sipRequest, Dialog dialog) { sendSuccessfulResponse(sipRequest, dialog); dialog.receivedOrSent2xx(); // logger.getInstance().debug("dialog state: " + dialog.getState()); // logger.getInstance().debug("after dialog.receivedOrSent2xx();"); // setChanged(); // notifyObservers(sipRequest); } public void rejectCall(SipRequest sipRequest) { //TODO generate 486, etc. SipHeaders reqHeaders = sipRequest.getSipHeaders(); SipHeaderFieldValue callId = reqHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CALLID)); Dialog dialog = dialogManager.getDialog(callId.getValue()); //TODO manage auto reject Do not disturb (DND) SipResponse sipResponse = RequestManager.generateResponse( sipRequest, dialog, RFC3261.CODE_486_BUSYHERE, RFC3261.REASON_486_BUSYHERE); // TODO determine port and transport for server transaction>transport // from initial invite // FIXME determine port and transport for server transaction>transport ServerTransaction serverTransaction = transactionManager .getServerTransaction(sipRequest); serverTransaction.start(); serverTransaction.receivedRequest(sipRequest); serverTransaction.sendReponse(sipResponse); dialog.receivedOrSent300To699(); userAgent.getMediaManager().setDatagramSocket(null); // setChanged(); // notifyObservers(sipRequest); } ////////////////////////////////////////////////////////// // UAC methods ////////////////////////////////////////////////////////// public void closeTimers() { ackTimer.cancel(); } public ClientTransaction preProcessInvite(SipRequest sipRequest) throws SipUriSyntaxException { //8.1.2 SipHeaders requestHeaders = sipRequest.getSipHeaders(); SipURI destinationUri = RequestManager.getDestinationUri(sipRequest, logger); //TODO if header route is present, addrspec = toproute.nameaddress.addrspec String transport = RFC3261.TRANSPORT_UDP; Hashtable<String, String> params = destinationUri.getUriParameters(); if (params != null) { String reqUriTransport = params.get(RFC3261.PARAM_TRANSPORT); if (reqUriTransport != null) { transport = reqUriTransport; } } int port = destinationUri.getPort(); if (port == SipURI.DEFAULT_PORT) { port = RFC3261.TRANSPORT_DEFAULT_PORT; } SipURI sipUri = userAgent.getConfig().getOutboundProxy(); if (sipUri == null) { sipUri = destinationUri; } InetAddress inetAddress; try { inetAddress = InetAddress.getByName(sipUri.getHost()); } catch (UnknownHostException e) { throw new SipUriSyntaxException("unknown host: " + sipUri.getHost(), e); } ClientTransaction clientTransaction = transactionManager .createClientTransaction(sipRequest, inetAddress, port, transport, null, this); DatagramSocket datagramSocket; synchronized (this) { datagramSocket = getDatagramSocket(); } try { SessionDescription sessionDescription = sdpManager.createSessionDescription(null, datagramSocket.getLocalPort()); sipRequest.setBody(sessionDescription.toString().getBytes()); } catch (IOException e) { logger.error(e.getMessage(), e); } requestHeaders.add(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE), new SipHeaderFieldValue(RFC3261.CONTENT_TYPE_SDP)); return clientTransaction; } public void preProcessReInvite(SipRequest sipRequest) { //TODO } ////////////////////////////////////////////////////////// // ClientTransactionUser methods ////////////////////////////////////////////////////////// public void errResponseReceived(final SipResponse sipResponse) { Dialog dialog = dialogManager.getDialog(sipResponse); if (dialog != null) { dialog.receivedOrSent300To699(); dialogManager.removeDialog(dialog.getId()); } int statusCode = sipResponse.getStatusCode(); if (statusCode == RFC3261.CODE_401_UNAUTHORIZED || statusCode == RFC3261.CODE_407_PROXY_AUTHENTICATION_REQUIRED && !challenged) { InviteClientTransaction inviteClientTransaction = (InviteClientTransaction) transactionManager.getClientTransaction(sipResponse); SipRequest sipRequest = inviteClientTransaction.getRequest(); String password = userAgent.getConfig().getPassword(); if (password != null && !"".equals(password.trim())) { challengeManager.handleChallenge(sipRequest, sipResponse); } challenged = true; return; } else { challenged = false; } SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.error(sipResponse); } List<String> guiClosedCallIds = userAgent.getUac().getGuiClosedCallIds(); String callId = Utils.getMessageCallId(sipResponse); if (guiClosedCallIds.contains(callId)) { guiClosedCallIds.remove(callId); } userAgent.getMediaManager().setDatagramSocket(null); } public void provResponseReceived(SipResponse sipResponse, Transaction transaction) { // dialog may have already been created if a previous 1xx has // already been received Dialog dialog = dialogManager.getDialog(sipResponse); boolean isFirstProvRespWithToTag = false; if (dialog == null) { SipHeaderFieldValue to = sipResponse.getSipHeaders().get( new SipHeaderFieldName(RFC3261.HDR_TO)); String toTag = to.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG)); if (toTag != null) { dialog = dialogManager.createDialog(sipResponse); isFirstProvRespWithToTag = true; } else { //TODO maybe stop retransmissions } } if (dialog != null) { buildOrUpdateDialogForUac(sipResponse, transaction); } // // if (dialog == null && sipResponse.getStatusCode() != RFC3261.CODE_100_TRYING) { // logger.debug("dialog not found for prov response"); // isFirstProvRespWithToTag = true; // SipHeaderFieldValue to = sipResponse.getSipHeaders() // .get(new SipHeaderFieldName(RFC3261.HDR_TO)); // String toTag = to.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG)); // if (toTag != null) { // dialog = buildOrUpdateDialogForUac(sipResponse, transaction); // } // } //TODO this notification is probably useless because dialog state modification // thereafter always notify dialog observers if (isFirstProvRespWithToTag) { SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.ringing(sipResponse); } dialog.receivedOrSent1xx(); } List<String> guiClosedCallIds = userAgent.getUac().getGuiClosedCallIds(); String callId = Utils.getMessageCallId(sipResponse); if (guiClosedCallIds.contains(callId)) { SipRequest sipRequest = transaction.getRequest(); logger.debug("cancel after prov response: sipRequest " + sipRequest + ", sipResponse " + sipResponse); userAgent.terminate(sipRequest); } } public void successResponseReceived(SipResponse sipResponse, Transaction transaction) { SipHeaders responseHeaders = sipResponse.getSipHeaders(); String cseq = responseHeaders.get( new SipHeaderFieldName(RFC3261.HDR_CSEQ)).getValue(); String method = cseq.substring(cseq.trim().lastIndexOf(' ') + 1); if (!RFC3261.METHOD_INVITE.equals(method)) { return; } challenged = false; //13.2.2.4 List<String> peers = userAgent.getPeers(); String responseTo = responseHeaders.get( new SipHeaderFieldName(RFC3261.HDR_TO)).getValue(); if (!peers.contains(responseTo)) { peers.add(responseTo); //timer used to purge dialogs which are not confirmed //after a given time ackTimer.schedule(new AckTimerTask(responseTo), 64 * RFC3261.TIMER_T1); } Dialog dialog = dialogManager.getDialog(sipResponse); if (dialog != null) { //dialog already created with a 180 for example dialog.setRouteSet(computeRouteSet(sipResponse.getSipHeaders())); } dialog = buildOrUpdateDialogForUac(sipResponse, transaction); SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.calleePickup(sipResponse); } //added for media SessionDescription sessionDescription = sdpManager.parse(sipResponse.getBody()); try { mediaDestination = sdpManager.getMediaDestination(sessionDescription); } catch (NoCodecException e) { logger.error(e.getMessage(), e); } String remoteAddress = mediaDestination.getDestination(); int remotePort = mediaDestination.getPort(); Codec codec = mediaDestination.getCodec(); String localAddress = userAgent.getConfig() .getLocalInetAddress().getHostAddress(); userAgent.getMediaManager().successResponseReceived(localAddress, remoteAddress, remotePort, codec); //switch to confirmed state dialog.receivedOrSent2xx(); //generate ack //p. 82 §3 SipRequest ack = dialog.buildSubsequentRequest(RFC3261.METHOD_ACK); //update CSeq SipHeaders ackHeaders = ack.getSipHeaders(); SipHeaderFieldName cseqName = new SipHeaderFieldName(RFC3261.HDR_CSEQ); SipHeaderFieldValue ackCseq = ackHeaders.get(cseqName); SipRequest request = transaction.getRequest(); SipHeaders requestHeaders = request.getSipHeaders(); SipHeaderFieldValue requestCseq = requestHeaders.get(cseqName); ackCseq.setValue(requestCseq.toString().replace(RFC3261.METHOD_INVITE, RFC3261.METHOD_ACK)); //add Via with only the branchid parameter SipHeaderFieldValue via = new SipHeaderFieldValue(""); SipHeaderParamName branchIdName = new SipHeaderParamName(RFC3261.PARAM_BRANCH); via.addParam(branchIdName, Utils.generateBranchId()); ackHeaders.add(new SipHeaderFieldName(RFC3261.HDR_VIA), via, 0); //TODO authentication headers if (request.getBody() == null && sipResponse.getBody() != null) { //TODO add a real SDP answer ack.setBody(sipResponse.getBody()); } //TODO check if sdp is acceptable SipURI destinationUri = RequestManager.getDestinationUri(ack, logger); challengeManager.postProcess(ack); //TODO if header route is present, addrspec = toproute.nameaddress.addrspec String transport = RFC3261.TRANSPORT_UDP; Hashtable<String, String> params = destinationUri.getUriParameters(); if (params != null) { String reqUriTransport = params.get(RFC3261.PARAM_TRANSPORT); if (reqUriTransport != null) { transport = reqUriTransport; } } int port = destinationUri.getPort(); if (port == SipURI.DEFAULT_PORT) { port = RFC3261.TRANSPORT_DEFAULT_PORT; } SipURI sipUri = userAgent.getConfig().getOutboundProxy(); if (sipUri == null) { sipUri = destinationUri; } InetAddress inetAddress; try { inetAddress = InetAddress.getByName(sipUri.getHost()); } catch (UnknownHostException e) { logger.error("unknown host: " + sipUri.getHost(), e); return; } try { MessageSender sender = transportManager.createClientTransport( ack, inetAddress, port, transport); sender.sendMessage(ack); } catch (IOException e) { logger.error("input/output error", e); } List<String> guiClosedCallIds = userAgent.getUac().getGuiClosedCallIds(); String callId = Utils.getMessageCallId(sipResponse); if (guiClosedCallIds.contains(callId)) { userAgent.terminate(request); } } public void handleAck(SipRequest ack, Dialog dialog) { // TODO determine if ACK is ACK of an initial INVITE or a re-INVITE // in first case, captureRtpSender and incomingRtpReader must be // created, in the second case, they must be updated. logger.debug("handleAck"); if (mediaDestination == null) { SipHeaders reqHeaders = ack.getSipHeaders(); SipHeaderFieldValue contentType = reqHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE)); byte[] offerBytes = ack.getBody(); if (offerBytes != null && contentType != null && RFC3261.CONTENT_TYPE_SDP.equals(contentType.getValue())) { // create response in 200 try { SessionDescription answer = sdpManager.parse(offerBytes); mediaDestination = sdpManager.getMediaDestination(answer); } catch (NoCodecException e) { logger.error(e.getMessage(), e); return; } } } String destAddress = mediaDestination.getDestination(); int destPort = mediaDestination.getPort(); Codec codec = mediaDestination.getCodec(); MediaManager mediaManager = userAgent.getMediaManager(); if (initialIncomingInvite) { mediaManager.handleAck(destAddress, destPort, codec); } else { mediaManager.updateRemote(destAddress, destPort, codec); } } public void transactionTimeout(ClientTransaction clientTransaction) { // TODO Auto-generated method stub } public void transactionTransportError() { // TODO Auto-generated method stub } ////////////////////////////////////////////////////////// // ServerTransactionUser methods ////////////////////////////////////////////////////////// public void transactionFailure() { // TODO manage transaction failure (ACK was not received) } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/MethodHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sdp.SDPManager; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.ChallengeManager; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public abstract class MethodHandler { protected UserAgent userAgent; protected TransactionManager transactionManager; protected TransportManager transportManager; protected ChallengeManager challengeManager; protected SDPManager sdpManager; protected boolean challenged; protected Logger logger; public MethodHandler(UserAgent userAgent, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { this.userAgent = userAgent; this.transactionManager = transactionManager; this.transportManager = transportManager; this.logger = logger; challenged = false; } protected SipResponse buildGenericResponse(SipRequest sipRequest, int statusCode, String reasonPhrase) { //8.2.6 SipResponse sipResponse = new SipResponse(statusCode, reasonPhrase); SipHeaders respHeaders = sipResponse.getSipHeaders(); SipHeaders reqHeaders = sipRequest.getSipHeaders(); SipHeaderFieldName fromName = new SipHeaderFieldName(RFC3261.HDR_FROM); respHeaders.add(fromName, reqHeaders.get(fromName)); SipHeaderFieldName callIdName = new SipHeaderFieldName(RFC3261.HDR_CALLID); respHeaders.add(callIdName, reqHeaders.get(callIdName)); SipHeaderFieldName cseqName = new SipHeaderFieldName(RFC3261.HDR_CSEQ); respHeaders.add(cseqName, reqHeaders.get(cseqName)); SipHeaderFieldName viaName = new SipHeaderFieldName(RFC3261.HDR_VIA); respHeaders.add(viaName, reqHeaders.get(viaName)); SipHeaderFieldName toName = new SipHeaderFieldName(RFC3261.HDR_TO); String to = reqHeaders.get(toName).getValue(); SipHeaderFieldValue toValue = new SipHeaderFieldValue(to); toValue.addParam(new SipHeaderParamName(RFC3261.PARAM_TAG), Utils.randomString(10));// TODO 19.3 respHeaders.add(toName, toValue); return sipResponse; } public void setChallengeManager(ChallengeManager challengeManager) { this.challengeManager = challengeManager; } public void setSdpManager(SDPManager sdpManager) { this.sdpManager = sdpManager; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/OptionsHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010, 2012 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import java.io.IOException; import java.util.Random; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sdp.SessionDescription; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.ServerTransactionUser; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class OptionsHandler extends MethodHandler implements ServerTransactionUser { public static final int MAX_PORTS = 65536; public OptionsHandler(UserAgent userAgent, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, transactionManager, transportManager, logger); } public void handleOptions(SipRequest sipRequest) { SipResponse sipResponse = buildGenericResponse(sipRequest, RFC3261.CODE_200_OK, RFC3261.REASON_200_OK); int localPort = new Random().nextInt(MAX_PORTS); try { SessionDescription sessionDescription = sdpManager.createSessionDescription(null, localPort); sipResponse.setBody(sessionDescription.toString().getBytes()); } catch (IOException e) { logger.error(e.getMessage(), e); } SipHeaders sipHeaders = sipResponse.getSipHeaders(); sipHeaders.add(new SipHeaderFieldName(RFC3261.HDR_CONTENT_TYPE), new SipHeaderFieldValue(RFC3261.CONTENT_TYPE_SDP)); sipHeaders.add(new SipHeaderFieldName(RFC3261.HDR_ALLOW), new SipHeaderFieldValue(Utils.generateAllowHeader())); ServerTransaction serverTransaction = transactionManager.createServerTransaction( sipResponse, userAgent.getSipPort(), RFC3261.TRANSPORT_UDP, this, sipRequest); serverTransaction.start(); serverTransaction.receivedRequest(sipRequest); serverTransaction.sendReponse(sipResponse); } @Override public void transactionFailure() { // TODO Auto-generated method stub } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/core/useragent/handlers/RegisterHandler.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers.sip.core.useragent.handlers; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Hashtable; import java.util.TimerTask; import net.sourceforge.peers.Timer; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.core.useragent.InitialRequestManager; import net.sourceforge.peers.sip.core.useragent.RequestManager; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.NameAddress; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.ClientTransactionUser; import net.sourceforge.peers.sip.transaction.NonInviteClientTransaction; import net.sourceforge.peers.sip.transaction.Transaction; import net.sourceforge.peers.sip.transaction.TransactionManager; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class RegisterHandler extends MethodHandler implements ClientTransactionUser { public static final int REFRESH_MARGIN = 10; // seconds private InitialRequestManager initialRequestManager; private Timer timer; private String requestUriStr; private String profileUriStr; private String callIDStr; //FIXME should be on a profile based context private boolean unregisterInvoked; private boolean registered; public RegisterHandler(UserAgent userAgent, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(userAgent, transactionManager, transportManager, logger); } //TODO factorize common code here and in invitehandler public synchronized ClientTransaction preProcessRegister(SipRequest sipRequest) throws SipUriSyntaxException { registered = false; unregisterInvoked = false; SipHeaders sipHeaders = sipRequest.getSipHeaders(); SipURI destinationUri = RequestManager.getDestinationUri(sipRequest, logger); int port = destinationUri.getPort(); if (port == SipURI.DEFAULT_PORT) { port = RFC3261.TRANSPORT_DEFAULT_PORT; } //TODO if header route is present, addrspec = toproute.nameaddress.addrspec String transport = RFC3261.TRANSPORT_UDP; Hashtable<String, String> params = destinationUri.getUriParameters(); if (params != null) { String reqUriTransport = params.get(RFC3261.PARAM_TRANSPORT); if (reqUriTransport != null) { transport = reqUriTransport; } } SipURI sipUri = userAgent.getConfig().getOutboundProxy(); if (sipUri == null) { sipUri = destinationUri; } InetAddress inetAddress; try { inetAddress = InetAddress.getByName(sipUri.getHost()); } catch (UnknownHostException e) { throw new SipUriSyntaxException("unknown host: " + sipUri.getHost(), e); } ClientTransaction clientTransaction = transactionManager .createClientTransaction(sipRequest, inetAddress, port, transport, null, this); //TODO 10.2 SipHeaderFieldValue to = sipHeaders.get( new SipHeaderFieldName(RFC3261.HDR_TO)); SipHeaderFieldValue from = sipHeaders.get( new SipHeaderFieldName(RFC3261.HDR_FROM)); String fromValue = from.getValue(); to.setValue(fromValue); requestUriStr = destinationUri.toString(); profileUriStr = NameAddress.nameAddressToUri(fromValue); callIDStr = sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CALLID)) .toString(); // added for buggy servers like cirpack which doesn't answer with a // default expires value if it doesn't find any expires in request sipHeaders.add(new SipHeaderFieldName(RFC3261.HDR_EXPIRES), new SipHeaderFieldValue(String.valueOf( RFC3261.DEFAULT_EXPIRES))); return clientTransaction; } public void unregister() { timer.cancel(); unregisterInvoked = true; challenged = false; } ////////////////////////////////////////////////////////// // ClientTransactionUser methods ////////////////////////////////////////////////////////// public void errResponseReceived(SipResponse sipResponse) { String password = userAgent.getConfig().getPassword(); if (password != null && !"".equals(password.trim())) { int statusCode = sipResponse.getStatusCode(); if (statusCode == RFC3261.CODE_401_UNAUTHORIZED || statusCode == RFC3261.CODE_407_PROXY_AUTHENTICATION_REQUIRED) { if (challenged) { notifyListener(sipResponse); } else { challenged = true; NonInviteClientTransaction nonInviteClientTransaction = (NonInviteClientTransaction) transactionManager.getClientTransaction(sipResponse); SipRequest sipRequest = nonInviteClientTransaction.getRequest(); challengeManager.handleChallenge(sipRequest, sipResponse); } } else { // not 401 nor 407 SipHeaders sipHeaders = sipResponse.getSipHeaders(); SipHeaderFieldName viaName = new SipHeaderFieldName( RFC3261.HDR_VIA); SipHeaderFieldValue via = sipHeaders.get(viaName); SipHeaderParamName receivedName = new SipHeaderParamName( RFC3261.PARAM_RECEIVED); String viaValue = via.getValue(); int pos = viaValue.indexOf(" "); if (pos > -1) { viaValue = viaValue.substring(pos + 1); pos = viaValue.indexOf(RFC3261.TRANSPORT_PORT_SEP); if (pos > -1) { viaValue = viaValue.substring(0, pos); } else { pos = viaValue.indexOf(RFC3261.PARAM_SEPARATOR); if (pos > -1) { viaValue = viaValue.substring(0, pos); } } } String received = via.getParam(receivedName); if (received != null && !"".equals(received.trim())) { if (viaValue.equals(received)) { notifyListener(sipResponse); } else { // received != via ip address try { InetAddress receivedInetAddress = InetAddress.getByName(received); Config config = userAgent.getConfig(); config.setPublicInetAddress(receivedInetAddress); userAgent.register(); } catch (UnknownHostException e) { notifyListener(sipResponse); logger.error(e.getMessage(), e); } catch (SipUriSyntaxException e) { notifyListener(sipResponse); logger.error(e.getMessage(), e); } } } else { // received not provided notifyListener(sipResponse); } } } else { // no password configured notifyListener(sipResponse); } } private void notifyListener(SipResponse sipResponse) { SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.registerFailed(sipResponse); } challenged = false; } public void provResponseReceived(SipResponse sipResponse, Transaction transaction) { //meaningless } public synchronized void successResponseReceived(SipResponse sipResponse, Transaction transaction) { // 1. retrieve request corresponding to response // 2. if request was not an unregister, extract contact and expires, // and start register refresh timer // 3. notify sip listener of register success event. SipRequest sipRequest = transaction.getRequest(); SipHeaderFieldName contactName = new SipHeaderFieldName( RFC3261.HDR_CONTACT); SipHeaderFieldValue requestContact = sipRequest.getSipHeaders() .get(contactName); SipHeaderParamName expiresParam = new SipHeaderParamName( RFC3261.PARAM_EXPIRES); String expires = requestContact.getParam(expiresParam); challenged = false; if (!"0".equals(expires)) { // each contact contains an expires parameter giving the expiration // in seconds. Thus the binding must be refreshed before it expires. SipHeaders sipHeaders = sipResponse.getSipHeaders(); SipHeaderFieldValue responseContact = sipHeaders.get(contactName); if (responseContact == null) { return; } expires = responseContact.getParam(expiresParam); // patch mobicents simple application registered = true; int delay = -1; if (expires == null || "".equals(expires.trim())) { delay = 3600; } if (!unregisterInvoked) { if (delay == -1) { delay = Integer.parseInt(expires) - REFRESH_MARGIN; } if (timer != null) { timer.cancel(); } timer = new Timer(getClass().getSimpleName() + " refresh timer"); timer.schedule(new RefreshTimerTask(), delay * 1000); } } SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.registerSuccessful(sipResponse); } } public void transactionTimeout(ClientTransaction clientTransaction) { SipListener sipListener = userAgent.getSipListener(); if (sipListener != null) { sipListener.registerFailed(null); } } public void transactionTransportError() { //TODO alert user } public boolean isRegistered() { return registered; } ////////////////////////////////////////////////////////// // TimerTask ////////////////////////////////////////////////////////// class RefreshTimerTask extends TimerTask { @Override public void run() { try { initialRequestManager.createInitialRequest(requestUriStr, RFC3261.METHOD_REGISTER, profileUriStr, callIDStr); } catch (SipUriSyntaxException e) { logger.error("syntax error", e); } } } public void setInitialRequestManager(InitialRequestManager initialRequestManager) { this.initialRequestManager = initialRequestManager; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/NameAddress.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import net.sourceforge.peers.sip.RFC3261; public class NameAddress { public static String nameAddressToUri(String nameAddress) { int leftPos = nameAddress.indexOf(RFC3261.LEFT_ANGLE_BRACKET); int rightPos = nameAddress.indexOf(RFC3261.RIGHT_ANGLE_BRACKET); if (leftPos < 0 || rightPos < 0) { return nameAddress; } return nameAddress.substring(leftPos + 1, rightPos); } protected String addrSpec; protected String displayName; public NameAddress(String addrSpec) { super(); this.addrSpec = addrSpec; } public NameAddress(String addrSpec, String displayName) { super(); this.addrSpec = addrSpec; this.displayName = displayName; } @Override public String toString() { StringBuffer buf = new StringBuffer(); if (displayName != null) { buf.append(displayName); buf.append(' '); } buf.append(RFC3261.LEFT_ANGLE_BRACKET); buf.append(addrSpec); buf.append(RFC3261.RIGHT_ANGLE_BRACKET); return buf.toString(); } public String getAddrSpec() { return addrSpec; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/RunnableSipParser.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; public class RunnableSipParser implements Runnable { public void run() { // TODO Auto-generated method stub } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeader.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; public class SipHeader { private SipHeaderFieldName name; private SipHeaderFieldValue value; SipHeader(SipHeaderFieldName name, SipHeaderFieldValue value) { super(); this.name = name; this.value = value; } @Override public boolean equals(Object obj) { if (obj instanceof SipHeader) { SipHeader objHdr = (SipHeader) obj; return name.equals(objHdr.name); } return false; } public SipHeaderFieldName getName() { return name; } public SipHeaderFieldValue getValue() { return value; } public void setValue(SipHeaderFieldValue value) { this.value = value; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeaderFieldMultiValue.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import java.util.List; public class SipHeaderFieldMultiValue extends SipHeaderFieldValue { private List<SipHeaderFieldValue> values; private static String toString(List<SipHeaderFieldValue> list) { if (list == null) { return null; } String arrToString = list.toString(); return arrToString.substring(1, arrToString.length() - 1); } public SipHeaderFieldMultiValue(List<SipHeaderFieldValue> values) { super(toString(values)); this.values = values; } public List<SipHeaderFieldValue> getValues() { return values; } @Override public String toString() { return toString(values); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeaderFieldName.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; public class SipHeaderFieldName { private final static SipHeadersTable SIP_HEADER_TABLE = new SipHeadersTable(); private String name; public SipHeaderFieldName(String name) { super(); if (name.length() == 1) { this.name = SIP_HEADER_TABLE.getLongForm(name.charAt(0)); } else { this.name = name; } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } String objName = ((SipHeaderFieldName)obj).getName(); if (name.equalsIgnoreCase(objName)) { return true; } return false; } @Override public int hashCode() { return name.hashCode(); } public String getName() { return name; } @Override public String toString() { return name; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeaderFieldValue.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import java.util.HashMap; import net.sourceforge.peers.sip.RFC3261; public class SipHeaderFieldValue { private String value; private HashMap<SipHeaderParamName, String> params; public SipHeaderFieldValue(String value) { int startPos = value.indexOf(RFC3261.RIGHT_ANGLE_BRACKET); int pos; if (startPos > -1) { pos = value.indexOf(RFC3261.PARAM_SEPARATOR, startPos); } else { pos = value.indexOf(RFC3261.PARAM_SEPARATOR); } String paramsString; if (pos > -1) { this.value = value.substring(0,pos); paramsString = value.substring(pos); } else { this.value = value; paramsString = ""; } params = new HashMap<SipHeaderParamName, String>(); if (paramsString.contains(RFC3261.PARAM_SEPARATOR)) { String[] arr = paramsString.split(RFC3261.PARAM_SEPARATOR); if (arr.length > 1) { for (int i = 1; i < arr.length; ++i) { String paramName = arr[i]; String paramValue = ""; pos = paramName.indexOf(RFC3261.PARAM_ASSIGNMENT); if (pos > -1) { paramName = arr[i].substring(0, pos); paramValue = arr[i].substring(pos + 1); } params.put(new SipHeaderParamName(paramName), paramValue); } } } } public String getParam(SipHeaderParamName name) { return params.get(name); } public void addParam(SipHeaderParamName name, String value) { params.put(name, value); } public void removeParam(SipHeaderParamName name) { params.remove(name); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { if (params == null || params.isEmpty()) { return value; } StringBuffer buf = new StringBuffer(value); for (SipHeaderParamName name: params.keySet()) { buf.append(RFC3261.PARAM_SEPARATOR).append(name); String value = params.get(name); if (!"".equals(value.trim())) { buf.append(RFC3261.PARAM_ASSIGNMENT).append(value); } } return buf.toString(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeaderParamName.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; public class SipHeaderParamName { private String name; public SipHeaderParamName(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } String objName = ((SipHeaderParamName)obj).getName(); if (name.equalsIgnoreCase(objName)) { return true; } return false; } @Override public int hashCode() { return name.toLowerCase().hashCode(); } @Override public String toString() { return name; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeaders.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import java.util.ArrayList; import net.sourceforge.peers.sip.RFC3261; public class SipHeaders { private ArrayList<SipHeader> headers; public SipHeaders() { headers = new ArrayList<SipHeader>(); } /** * * @param name * @param value * @param index -1 to add at the end */ public void add(SipHeaderFieldName name, SipHeaderFieldValue value, int index) { SipHeader header = new SipHeader(name, value); if (headers.contains(header)) { header = headers.get(headers.indexOf(header)); SipHeaderFieldValue oldValue = header.getValue(); //TODO check is header can be multi valued if (oldValue instanceof SipHeaderFieldMultiValue) { SipHeaderFieldMultiValue oldMultiVal = (SipHeaderFieldMultiValue) oldValue; oldMultiVal.getValues().add(value); } else { ArrayList<SipHeaderFieldValue> arr = new ArrayList<SipHeaderFieldValue>(); arr.add(oldValue); arr.add(value); header.setValue(new SipHeaderFieldMultiValue(arr)); } } else { if (index == -1) { headers.add(header); } else { headers.add(index, header); } } } public void add(SipHeaderFieldName name, SipHeaderFieldValue value) { add(name, value, -1); } public void remove(SipHeaderFieldName name) { headers.remove(name); } public boolean contains(SipHeaderFieldName name) { return headers.contains(new SipHeader(name, null)); } public SipHeaderFieldValue get(SipHeaderFieldName name) { int index = headers.indexOf(new SipHeader(name, null)); if (index < 0) { return null; } return headers.get(index).getValue(); } public int getCount() { return headers.size(); } @Override public String toString() { StringBuffer buf = new StringBuffer(); for (SipHeader header : headers) { buf.append(header.getName().toString()); buf.append(": "); buf.append(header.getValue()); buf.append(RFC3261.CRLF); } return buf.toString(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipHeadersTable.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import java.util.HashMap; import net.sourceforge.peers.sip.RFC3261; public class SipHeadersTable { private HashMap<Character, String> headers; /** * should be instanciated only once, it was a singleton. */ public SipHeadersTable() { headers = new HashMap<Character, String>(); //RFC 3261 Section 10 headers.put(RFC3261.COMPACT_HDR_CALLID, RFC3261.HDR_CALLID); headers.put(RFC3261.COMPACT_HDR_CONTACT, RFC3261.HDR_CONTACT); headers.put(RFC3261.COMPACT_HDR_CONTENT_ENCODING, RFC3261.HDR_CONTENT_ENCODING); headers.put(RFC3261.COMPACT_HDR_CONTENT_LENGTH, RFC3261.HDR_CONTENT_LENGTH); headers.put(RFC3261.COMPACT_HDR_CONTENT_TYPE, RFC3261.HDR_CONTENT_TYPE); headers.put(RFC3261.COMPACT_HDR_FROM, RFC3261.HDR_FROM); headers.put(RFC3261.COMPACT_HDR_SUBJECT, RFC3261.HDR_SUBJECT); headers.put(RFC3261.COMPACT_HDR_SUPPORTED, RFC3261.HDR_SUPPORTED); headers.put(RFC3261.COMPACT_HDR_TO, RFC3261.HDR_TO); headers.put(RFC3261.COMPACT_HDR_VIA, RFC3261.HDR_VIA); } public String getLongForm(char compactForm) { return headers.get(compactForm); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipParser.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public class SipParser { private BufferedReader reader; private final static int BUFF_SIZE = 1024; private List<SipHeaderFieldName> singleValueHeaders; public SipParser() { singleValueHeaders = new ArrayList<SipHeaderFieldName>(); singleValueHeaders.add(new SipHeaderFieldName( RFC3261.HDR_WWW_AUTHENTICATE)); singleValueHeaders.add(new SipHeaderFieldName( RFC3261.HDR_AUTHORIZATION)); singleValueHeaders.add(new SipHeaderFieldName( RFC3261.HDR_PROXY_AUTHENTICATE)); singleValueHeaders.add(new SipHeaderFieldName( RFC3261.HDR_PROXY_AUTHORIZATION)); singleValueHeaders.add(new SipHeaderFieldName( RFC3261.HDR_SUPPORTED)); singleValueHeaders.add(new SipHeaderFieldName( RFC3261.HDR_SUBJECT)); } public synchronized SipMessage parse(InputStream in) throws IOException, SipParserException { InputStreamReader inputStreamReader = new InputStreamReader(in); reader = new BufferedReader(inputStreamReader); String startLine = reader.readLine(); while (startLine == null || startLine.equals("")) { startLine = reader.readLine(); } SipMessage sipMessage; if (startLine.toUpperCase().startsWith(RFC3261.DEFAULT_SIP_VERSION)) { sipMessage = parseSipResponse(startLine); } else { sipMessage = parseSipRequest(startLine); } parseHeaders(sipMessage); parseBody(sipMessage); return sipMessage; } private SipRequest parseSipRequest(String startLine) throws SipParserException { String[] params = startLine.split(" "); if (params.length != 3) { throw new SipParserException("invalid request line"); } if (!RFC3261.DEFAULT_SIP_VERSION.equals(params[2].toUpperCase())) { throw new SipParserException("unsupported SIP version"); } SipURI requestUri; try { requestUri = new SipURI(params[1]); } catch (SipUriSyntaxException e) { throw new SipParserException(e); } return new SipRequest(params[0], requestUri); } private SipResponse parseSipResponse(String startLine) throws SipParserException { String[] params = startLine.split(" "); if (params.length < 3) { throw new SipParserException("incorrect status line"); } if (!RFC3261.DEFAULT_SIP_VERSION.equals(params[0].toUpperCase())) { throw new SipParserException("unsupported SIP version"); } StringBuffer buf = new StringBuffer(); for (int i = 2; i < params.length; ++i) { buf.append(params[i]).append(" "); } buf.deleteCharAt(buf.length() - 1); return new SipResponse(Integer.parseInt(params[1]), buf.toString()); } private void parseHeaders(SipMessage sipMessage) throws IOException, SipParserException { SipHeaders sipHeaders = new SipHeaders(); String headerLine = reader.readLine(); if (headerLine == null) { throw new SipParserException(sipMessage.toString()); } while (!"".equals(headerLine)) { String nextLine = reader.readLine(); if (nextLine != null && (nextLine.startsWith(" ") || nextLine.startsWith("\t"))) { StringBuffer buf = new StringBuffer(headerLine); while (nextLine != null && (nextLine.startsWith(" ") || nextLine.startsWith("\t"))) { buf.append(' '); buf.append(nextLine.trim()); nextLine = reader.readLine(); } headerLine = buf.toString(); } if (headerLine == null) { throw new SipParserException(sipMessage.toString()); } int columnPos = headerLine.indexOf(RFC3261.FIELD_NAME_SEPARATOR); if (columnPos < 0) { throw new SipParserException("Invalid header line"); } SipHeaderFieldName sipHeaderName = new SipHeaderFieldName( headerLine.substring(0, columnPos).trim()); String value = headerLine.substring(columnPos + 1).trim(); SipHeaderFieldValue sipHeaderValue; if (!singleValueHeaders.contains(sipHeaderName) && value.indexOf(RFC3261.HEADER_SEPARATOR) > -1) { String[] values = value.split(RFC3261.HEADER_SEPARATOR); List<SipHeaderFieldValue> list = new ArrayList<SipHeaderFieldValue>(); for (String s: values) { list.add(new SipHeaderFieldValue(s)); } sipHeaderValue = new SipHeaderFieldMultiValue(list); } else { sipHeaderValue = new SipHeaderFieldValue(value); } sipHeaders.add(sipHeaderName, sipHeaderValue); headerLine = nextLine; } sipMessage.setSipHeaders(sipHeaders); } public void parseBody(SipMessage sipMessage) throws IOException, SipParserException { SipHeaderFieldValue contentLengthValue = sipMessage.getSipHeaders().get(new SipHeaderFieldName( RFC3261.HDR_CONTENT_LENGTH)); if (contentLengthValue == null) { return; } int length = Integer.parseInt(contentLengthValue.toString()); byte[] buff = new byte[BUFF_SIZE]; int i; int count = 0; while (count < length && (i = reader.read()) != -1) { if (count >= buff.length) { byte[] aux = new byte[buff.length + BUFF_SIZE]; System.arraycopy(buff, 0, aux, 0, buff.length); buff = aux; } buff[count++] = (byte)i; } if (count != buff.length) { byte[] aux = new byte[count]; System.arraycopy(buff, 0, aux, 0, count); buff = aux; } sipMessage.setBody(buff); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipParserException.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; public class SipParserException extends Exception { private static final long serialVersionUID = 1L; public SipParserException() { super(); } public SipParserException(String message, Throwable cause) { super(message, cause); } public SipParserException(String message) { super(message); } public SipParserException(Throwable cause) { super(cause); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipURI.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; import java.util.Hashtable; import net.sourceforge.peers.sip.RFC3261; public class SipURI { public final static int DEFAULT_PORT = -1; private String stringRepresentation; /** * telephone-subscriber and optional port are not managed */ private String userinfo; private String host; private int port = DEFAULT_PORT; /** * Use empty strings in value if the parameter has no value */ private Hashtable<String, String> uriParameters; //headers not implemented //private Hashtable<String, String> headers; public SipURI(String sipUri) throws SipUriSyntaxException { stringRepresentation = sipUri; StringBuffer buf = new StringBuffer(sipUri); String scheme = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR; if (!sipUri.startsWith(scheme)) { throw new SipUriSyntaxException("SIP URI must start with " + scheme); } buf.delete(0, scheme.length()); int atPos = buf.indexOf("@"); if (atPos == 0) { throw new SipUriSyntaxException("userinfo cannot start with a '@'"); } if (atPos > 0) { userinfo = buf.substring(0, atPos); buf.delete(0, atPos + 1); } int endHostport = buf.indexOf(";"); if (endHostport == 0) { throw new SipUriSyntaxException("hostport not present or it cannot start with ';'"); } if (endHostport < 0) { endHostport = buf.length(); } String hostport = buf.substring(0, endHostport); buf.delete(0, endHostport); int colonPos = hostport.indexOf(':'); if (colonPos > -1) { if (colonPos == hostport.length() - 1) { throw new SipUriSyntaxException("hostport cannot terminate with a ':'"); } port = Integer.parseInt(hostport.substring(colonPos + 1)); } else { colonPos = hostport.length(); } host = hostport.substring(0, colonPos); if (buf.length() == 1) { //if there is only one ';' at the end of the uri => do not //parse uri-parameters and headers buf.deleteCharAt(0); } if (buf.length() <= 0) { return; } uriParameters = new Hashtable<String, String>(); while (buf.length() > 0) { buf.deleteCharAt(0);//delete the first ';' int nextSemicolon = buf.indexOf(";"); if (nextSemicolon < 0) { nextSemicolon = buf.length(); } int nextEquals = buf.indexOf("="); if (nextEquals < 0) { nextEquals = nextSemicolon; } if (nextEquals > nextSemicolon) { nextEquals = nextSemicolon; } int afterEquals; if (nextEquals + 1 > nextSemicolon) { afterEquals = nextSemicolon; } else { afterEquals = nextEquals + 1; } uriParameters.put(buf.substring(0, nextEquals), buf.substring(afterEquals, nextSemicolon)); buf.delete(0, nextSemicolon); } } @Override public String toString() { return stringRepresentation; } public String getHost() { return host; } public int getPort() { return port; } public Hashtable<String, String> getUriParameters() { return uriParameters; } public String getUserinfo() { return userinfo; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/syntaxencoding/SipUriSyntaxException.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.syntaxencoding; public class SipUriSyntaxException extends Exception { private static final long serialVersionUID = 1L; public SipUriSyntaxException() { super(); } public SipUriSyntaxException(String message, Throwable cause) { super(message, cause); } public SipUriSyntaxException(String message) { super(message); } public SipUriSyntaxException(Throwable cause) { super(cause); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/ClientTransaction.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.sip.transport.SipResponse; public interface ClientTransaction { public void receivedResponse(SipResponse sipResponse); public void start(); public String getContact(); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/ClientTransactionUser.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.sip.transport.SipResponse; public interface ClientTransactionUser { public void transactionTimeout(ClientTransaction clientTransaction); public void provResponseReceived(SipResponse sipResponse, Transaction transaction); //TODO eventually pass transaction to the transaction user public void errResponseReceived(SipResponse sipResponse);//3XX is considered as an error response public void successResponseReceived(SipResponse sipResponse, Transaction transaction); public void transactionTransportError(); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransaction.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import java.io.IOException; import java.net.InetAddress; import java.util.TimerTask; import net.sourceforge.peers.Timer; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.transport.MessageSender; import net.sourceforge.peers.sip.transport.SipClientTransportUser; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.TransportManager; public class InviteClientTransaction extends InviteTransaction implements ClientTransaction, SipClientTransportUser { public final InviteClientTransactionState INIT; public final InviteClientTransactionState CALLING; public final InviteClientTransactionState PROCEEDING; public final InviteClientTransactionState COMPLETED; public final InviteClientTransactionState TERMINATED; protected ClientTransactionUser transactionUser; protected String transport; private InviteClientTransactionState state; //private SipClientTransport sipClientTransport; private MessageSender messageSender; private int nbRetrans; private SipRequest ack; private int remotePort; private InetAddress remoteInetAddress; InviteClientTransaction(String branchId, InetAddress inetAddress, int port, String transport, SipRequest sipRequest, ClientTransactionUser transactionUser, Timer timer, TransportManager transportManager, TransactionManager transactionManager, Logger logger) { super(branchId, timer, transportManager, transactionManager, logger); this.transport = transport; SipHeaderFieldValue via = new SipHeaderFieldValue(""); via.addParam(new SipHeaderParamName(RFC3261.PARAM_BRANCH), branchId); sipRequest.getSipHeaders().add(new SipHeaderFieldName(RFC3261.HDR_VIA), via, 0); nbRetrans = 0; INIT = new InviteClientTransactionStateInit(getId(), this, logger); state = INIT; CALLING = new InviteClientTransactionStateCalling(getId(), this, logger); PROCEEDING = new InviteClientTransactionStateProceeding(getId(), this, logger); COMPLETED = new InviteClientTransactionStateCompleted(getId(), this, logger); TERMINATED = new InviteClientTransactionStateTerminated(getId(), this, logger); //17.1.1.2 request = sipRequest; this.transactionUser = transactionUser; remotePort = port; remoteInetAddress = inetAddress; try { messageSender = transportManager.createClientTransport( request, remoteInetAddress, remotePort, transport); } catch (IOException e) { logger.error("input/output error", e); transportError(); } } public void setState(InviteClientTransactionState state) { this.state.log(state); this.state = state; if(TERMINATED.equals(state)) { //transactionManager.removeClientTransaction(branchId, method); transactionManager = null; } } public void start() { state.start(); //send request using transport information and sipRequest // try { // sipClientTransport = SipTransportFactory.getInstance() // .createClientTransport(this, request, remoteInetAddress, // remotePort, transport); // sipClientTransport.send(request); // } catch (IOException e) { // //e.printStackTrace(); // transportError(); // } try { messageSender.sendMessage(request); } catch (IOException e) { logger.error("input/output error", e); transportError(); } logger.debug("InviteClientTransaction.start"); if (RFC3261.TRANSPORT_UDP.equals(transport)) { //start timer A with value T1 for retransmission timer.schedule(new TimerA(), RFC3261.TIMER_T1); } //TODO start timer B with value 64*T1 for transaction timeout timer.schedule(new TimerB(), 64 * RFC3261.TIMER_T1); } public synchronized void receivedResponse(SipResponse sipResponse) { responses.add(sipResponse); // 17.1.1 int statusCode = sipResponse.getStatusCode(); if (statusCode < RFC3261.CODE_MIN_PROV) { logger.error("invalid response code"); } else if (statusCode < RFC3261.CODE_MIN_SUCCESS) { state.received1xx(); } else if (statusCode < RFC3261.CODE_MIN_REDIR) { state.received2xx(); } else if (statusCode <= RFC3261.CODE_MAX) { state.received300To699(); } else { logger.error("invalid response code"); } } public void transportError() { state.transportError(); } void createAndSendAck() { //p.126 last paragraph //17.1.1.3 ack = new SipRequest(RFC3261.METHOD_ACK, request.getRequestUri()); SipHeaderFieldValue topVia = Utils.getTopVia(request); SipHeaders ackSipHeaders = ack.getSipHeaders(); ackSipHeaders.add(new SipHeaderFieldName(RFC3261.HDR_VIA), topVia); Utils.copyHeader(request, ack, RFC3261.HDR_CALLID); Utils.copyHeader(request, ack, RFC3261.HDR_FROM); Utils.copyHeader(getLastResponse(), ack, RFC3261.HDR_TO); //TODO what happens if a prov response is received after a 200+ ... SipHeaders requestSipHeaders = request.getSipHeaders(); SipHeaderFieldName cseqName = new SipHeaderFieldName(RFC3261.HDR_CSEQ); SipHeaderFieldValue cseq = requestSipHeaders.get(cseqName); cseq.setValue(cseq.toString().replace(RFC3261.METHOD_INVITE, RFC3261.METHOD_ACK)); ackSipHeaders.add(cseqName, cseq); Utils.copyHeader(request, ack, RFC3261.HDR_ROUTE); sendAck(); } void sendAck() { //ack is passed to the transport layer... //TODO manage ACK retrans //sipClientTransport.send(ack); try { messageSender.sendMessage(ack); } catch (IOException e) { logger.error("input/output error", e); transportError(); } } void sendRetrans() { ++nbRetrans; //sipClientTransport.send(request); try { messageSender.sendMessage(request); } catch (IOException e) { logger.error("input/output error", e); transportError(); } timer.schedule(new TimerA(), (long)Math.pow(2, nbRetrans) * RFC3261.TIMER_T1); } public void requestTransportError(SipRequest sipRequest, Exception e) { // TODO Auto-generated method stub } public void responseTransportError(Exception e) { // TODO Auto-generated method stub } class TimerA extends TimerTask { @Override public void run() { state.timerAFires(); } } class TimerB extends TimerTask { @Override public void run() { state.timerBFires(); } } class TimerD extends TimerTask { @Override public void run() { state.timerDFires(); } } public String getContact() { if (messageSender != null) { return messageSender.getContact(); } return null; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransactionState.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.AbstractState; public abstract class InviteClientTransactionState extends AbstractState { protected InviteClientTransaction inviteClientTransaction; public InviteClientTransactionState(String id, InviteClientTransaction inviteClientTransaction, Logger logger) { super(id, logger); this.inviteClientTransaction = inviteClientTransaction; } public void start() {} public void timerAFires() {} public void timerBFires() {} public void received2xx() {} public void received1xx() {} public void received300To699() {} public void transportError() {} public void timerDFires() {} }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransactionStateCalling.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteClientTransactionStateCalling extends InviteClientTransactionState { public InviteClientTransactionStateCalling(String id, InviteClientTransaction inviteClientTransaction, Logger logger) { super(id, inviteClientTransaction, logger); } @Override public void timerAFires() { InviteClientTransactionState nextState = inviteClientTransaction.CALLING; inviteClientTransaction.setState(nextState); inviteClientTransaction.sendRetrans(); } @Override public void timerBFires() { timerBFiresOrTransportError(); } @Override public void transportError() { timerBFiresOrTransportError(); } private void timerBFiresOrTransportError() { InviteClientTransactionState nextState = inviteClientTransaction.TERMINATED; inviteClientTransaction.setState(nextState); inviteClientTransaction.transactionUser.transactionTimeout( inviteClientTransaction); } @Override public void received2xx() { InviteClientTransactionState nextState = inviteClientTransaction.TERMINATED; inviteClientTransaction.setState(nextState); inviteClientTransaction.transactionUser.successResponseReceived( inviteClientTransaction.getLastResponse(), inviteClientTransaction); } @Override public void received1xx() { InviteClientTransactionState nextState = inviteClientTransaction.PROCEEDING; inviteClientTransaction.setState(nextState); inviteClientTransaction.transactionUser.provResponseReceived( inviteClientTransaction.getLastResponse(), inviteClientTransaction); } @Override public void received300To699() { InviteClientTransactionState nextState = inviteClientTransaction.COMPLETED; inviteClientTransaction.setState(nextState); inviteClientTransaction.createAndSendAck(); inviteClientTransaction.transactionUser.errResponseReceived( inviteClientTransaction.getLastResponse()); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransactionStateCompleted.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; public class InviteClientTransactionStateCompleted extends InviteClientTransactionState { public InviteClientTransactionStateCompleted(String id, InviteClientTransaction inviteClientTransaction, Logger logger) { super(id, inviteClientTransaction, logger); int delay = 0; if (RFC3261.TRANSPORT_UDP.equals(inviteClientTransaction.transport)) { delay = RFC3261.TIMER_INVITE_CLIENT_TRANSACTION; } inviteClientTransaction.timer.schedule(inviteClientTransaction.new TimerD(), delay); } @Override public void received300To699() { InviteClientTransactionState nextState = inviteClientTransaction.COMPLETED; inviteClientTransaction.setState(nextState); inviteClientTransaction.sendAck(); } @Override public void transportError() { InviteClientTransactionState nextState = inviteClientTransaction.TERMINATED; inviteClientTransaction.setState(nextState); inviteClientTransaction.transactionUser.transactionTransportError(); } @Override public void timerDFires() { InviteClientTransactionState nextState = inviteClientTransaction.TERMINATED; inviteClientTransaction.setState(nextState); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransactionStateInit.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteClientTransactionStateInit extends InviteClientTransactionState { public InviteClientTransactionStateInit(String id, InviteClientTransaction inviteClientTransaction, Logger logger) { super(id, inviteClientTransaction, logger); } @Override public void start() { InviteClientTransactionState nextState = inviteClientTransaction.CALLING; inviteClientTransaction.setState(nextState); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransactionStateProceeding.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteClientTransactionStateProceeding extends InviteClientTransactionState { public InviteClientTransactionStateProceeding(String id, InviteClientTransaction inviteClientTransaction, Logger logger) { super(id, inviteClientTransaction, logger); } @Override public void received1xx() { InviteClientTransactionState nextState = inviteClientTransaction.PROCEEDING; inviteClientTransaction.setState(nextState); inviteClientTransaction.transactionUser.provResponseReceived( inviteClientTransaction.getLastResponse(), inviteClientTransaction); } @Override public void received2xx() { InviteClientTransactionState nextState = inviteClientTransaction.TERMINATED; inviteClientTransaction.setState(nextState); inviteClientTransaction.transactionUser.successResponseReceived( inviteClientTransaction.getLastResponse(), inviteClientTransaction); } @Override public void received300To699() { InviteClientTransactionState nextState = inviteClientTransaction.COMPLETED; inviteClientTransaction.setState(nextState); inviteClientTransaction.createAndSendAck(); inviteClientTransaction.transactionUser.errResponseReceived( inviteClientTransaction.getLastResponse()); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteClientTransactionStateTerminated.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteClientTransactionStateTerminated extends InviteClientTransactionState { public InviteClientTransactionStateTerminated(String id, InviteClientTransaction inviteClientTransaction, Logger logger) { super(id, inviteClientTransaction, logger); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransaction.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import java.io.IOException; import java.util.TimerTask; import net.sourceforge.peers.Timer; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import net.sourceforge.peers.sip.transport.SipServerTransportUser; import net.sourceforge.peers.sip.transport.TransportManager; public class InviteServerTransaction extends InviteTransaction implements ServerTransaction, SipServerTransportUser { public final InviteServerTransactionState INIT; public final InviteServerTransactionState PROCEEDING; public final InviteServerTransactionState COMPLETED; public final InviteServerTransactionState CONFIRMED; public final InviteServerTransactionState TERMINATED; protected String transport; protected int nbRetrans; protected ServerTransactionUser serverTransactionUser; private InviteServerTransactionState state; //private SipServerTransport sipServerTransport; private int port; InviteServerTransaction(String branchId, int port, String transport, SipResponse sipResponse, ServerTransactionUser serverTransactionUser, SipRequest sipRequest, Timer timer, TransactionManager transactionManager, TransportManager transportManager, Logger logger) { super(branchId, timer, transportManager, transactionManager, logger); INIT = new InviteServerTransactionStateInit(getId(), this, logger); state = INIT; PROCEEDING = new InviteServerTransactionStateProceeding(getId(), this, logger); COMPLETED = new InviteServerTransactionStateCompleted(getId(), this, logger); CONFIRMED = new InviteServerTransactionStateConfirmed(getId(), this, logger); TERMINATED = new InviteServerTransactionStateTerminated(getId(), this, logger); this.request = sipRequest; this.port = port; this.transport = transport; responses.add(sipResponse); nbRetrans = 0; this.serverTransactionUser = serverTransactionUser; //TODO pass INV to TU, send 100 if TU won't in 200ms } public void start() { state.start(); // sipServerTransport = SipTransportFactory.getInstance() // .createServerTransport(this, port, transport); try { transportManager.createServerTransport(transport, port); } catch (IOException e) { logger.error("input/output error", e); } } public void receivedRequest(SipRequest sipRequest) { String method = sipRequest.getMethod(); if (RFC3261.METHOD_INVITE.equals(method)) { state.receivedInvite(); } else { // if not INVITE, we consider that a ACK is received // in the case the call was not successful state.receivedAck(); } } public void sendReponse(SipResponse sipResponse) { //TODO check that a retransmission response will be considered as //equal (for contains) to the first response if (!responses.contains(sipResponse)) { responses.add(sipResponse); } int statusCode = sipResponse.getStatusCode(); if (statusCode == RFC3261.CODE_MIN_PROV) { // TODO 100 trying } else if (statusCode < RFC3261.CODE_MIN_SUCCESS) { state.received101To199(); } else if (statusCode < RFC3261.CODE_MIN_REDIR) { state.received2xx(); } else if (statusCode <= RFC3261.CODE_MAX) { state.received300To699(); } else { logger.error("invalid response code"); } } public void setState(InviteServerTransactionState state) { this.state.log(state); this.state = state; } public void messageReceived(SipMessage sipMessage) { // TODO Auto-generated method stub } void sendLastResponse() { //sipServerTransport.sendResponse(responses.get(responses.size() - 1)); int nbOfResponses = responses.size(); if (nbOfResponses > 0) { try { transportManager.sendResponse(responses.get(nbOfResponses - 1)); } catch (IOException e) { logger.error("input/output error", e); } } } public SipResponse getLastResponse() { int nbOfResponses = responses.size(); if (nbOfResponses > 0) { return responses.get(nbOfResponses - 1); } return null; } // TODO send provional response /* * maybe the 200 response mechanism could be retrieved for 1xx responses. */ // void stopSipServerTransport() { // sipServerTransport.stop(); // } class TimerG extends TimerTask { @Override public void run() { state.timerGFires(); } } class TimerH extends TimerTask { @Override public void run() { state.timerHFiresOrTransportError(); } } class TimerI extends TimerTask { @Override public void run() { state.timerIFires(); } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransactionState.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.AbstractState; public abstract class InviteServerTransactionState extends AbstractState { protected InviteServerTransaction inviteServerTransaction; public InviteServerTransactionState(String id, InviteServerTransaction inviteServerTransaction, Logger logger) { super(id, logger); this.inviteServerTransaction = inviteServerTransaction; } public void start() {} public void receivedInvite() {} public void received101To199() {} public void transportError() {} public void received2xx() {} public void received300To699() {} public void timerGFires() {} public void timerHFiresOrTransportError() {} public void receivedAck() {} public void timerIFires() {} }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransactionStateCompleted.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; public class InviteServerTransactionStateCompleted extends InviteServerTransactionState { public InviteServerTransactionStateCompleted(String id, InviteServerTransaction inviteServerTransaction, Logger logger) { super(id, inviteServerTransaction, logger); } @Override public void timerGFires() { InviteServerTransactionState nextState = inviteServerTransaction.COMPLETED; inviteServerTransaction.setState(nextState); inviteServerTransaction.sendLastResponse(); long delay = (long)Math.pow(2, ++inviteServerTransaction.nbRetrans) * RFC3261.TIMER_T1; inviteServerTransaction.timer.schedule( inviteServerTransaction.new TimerG(), Math.min(delay, RFC3261.TIMER_T2)); } @Override public void timerHFiresOrTransportError() { InviteServerTransactionState nextState = inviteServerTransaction.TERMINATED; inviteServerTransaction.setState(nextState); inviteServerTransaction.serverTransactionUser.transactionFailure(); } @Override public void receivedAck() { InviteServerTransactionState nextState = inviteServerTransaction.CONFIRMED; inviteServerTransaction.setState(nextState); int delay; if (RFC3261.TRANSPORT_UDP.equals(inviteServerTransaction.transport)) { delay = RFC3261.TIMER_T4; } else { delay = 0; } inviteServerTransaction.timer.schedule( inviteServerTransaction.new TimerI(), delay); } @Override public void receivedInvite() { InviteServerTransactionState nextState = inviteServerTransaction.COMPLETED; inviteServerTransaction.setState(nextState); // retransmission inviteServerTransaction.sendLastResponse(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransactionStateConfirmed.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteServerTransactionStateConfirmed extends InviteServerTransactionState { public InviteServerTransactionStateConfirmed(String id, InviteServerTransaction inviteServerTransaction, Logger logger) { super(id, inviteServerTransaction, logger); } @Override public void timerIFires() { InviteServerTransactionState nextState = inviteServerTransaction.TERMINATED; inviteServerTransaction.setState(nextState); // TODO destroy invite server transaction immediately // (dereference it in transaction manager serverTransactions hashtable) inviteServerTransaction.transactionManager.removeServerTransaction( inviteServerTransaction.branchId, inviteServerTransaction.method); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransactionStateInit.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteServerTransactionStateInit extends InviteServerTransactionState { public InviteServerTransactionStateInit(String id, InviteServerTransaction inviteServerTransaction, Logger logger) { super(id, inviteServerTransaction, logger); } @Override public void start() { InviteServerTransactionState nextState = inviteServerTransaction.PROCEEDING; inviteServerTransaction.setState(nextState); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransactionStateProceeding.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; public class InviteServerTransactionStateProceeding extends InviteServerTransactionState { public InviteServerTransactionStateProceeding(String id, InviteServerTransaction inviteServerTransaction, Logger logger) { super(id, inviteServerTransaction, logger); } @Override public void received101To199() { InviteServerTransactionState nextState = inviteServerTransaction.PROCEEDING; inviteServerTransaction.setState(nextState); //TODO inviteServerTransaction.sendProvisionalResponse(); inviteServerTransaction.sendLastResponse(); } @Override public void transportError() { InviteServerTransactionState nextState = inviteServerTransaction.TERMINATED; inviteServerTransaction.setState(nextState); } @Override public void received2xx() { InviteServerTransactionState nextState = inviteServerTransaction.TERMINATED; inviteServerTransaction.setState(nextState); inviteServerTransaction.sendLastResponse(); } @Override public void received300To699() { InviteServerTransactionState nextState = inviteServerTransaction.COMPLETED; inviteServerTransaction.setState(nextState); inviteServerTransaction.sendLastResponse(); if (RFC3261.TRANSPORT_UDP.equals(inviteServerTransaction.transport)) { inviteServerTransaction.timer.schedule( inviteServerTransaction.new TimerG(), RFC3261.TIMER_T1); } inviteServerTransaction.timer.schedule( inviteServerTransaction.new TimerH(), 64 * RFC3261.TIMER_T1); } @Override public void receivedInvite() { InviteServerTransactionState nextState = inviteServerTransaction.PROCEEDING; inviteServerTransaction.setState(nextState); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteServerTransactionStateTerminated.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Logger; public class InviteServerTransactionStateTerminated extends InviteServerTransactionState { public InviteServerTransactionStateTerminated(String id, InviteServerTransaction inviteServerTransaction, Logger logger) { super(id, inviteServerTransaction, logger); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/InviteTransaction.java
/* This file is part of Peers, a java SIP softphone. 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 3 of the License, or 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, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transaction; import net.sourceforge.peers.Timer; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.transport.TransportManager; public abstract class InviteTransaction extends Transaction { protected InviteTransaction(String branchId, Timer timer, TransportManager transportManager, TransactionManager transactionManager, Logger logger) { super(branchId, RFC3261.METHOD_INVITE, timer, transportManager, transactionManager, logger); } }