private final void socketrun() { do { if (link.socketport != 0) { try { Socket socket = new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport); socket.setSoTimeout(30000); socket.setTcpNoDelay(true); link.s = socket; } catch (Exception _ex) { link.s = null; } link.socketport = 0; } if (link.runme != null) { Thread thread = new Thread(link.runme); thread.setDaemon(true); thread.start(); link.runme = null; } if (link.iplookup != null) { String s = "unknown"; try { s = InetAddress.getByName(link.iplookup).getHostName(); } catch (Exception _ex) { } link.host = s; link.iplookup = null; } try { Thread.sleep(100L); } catch (Exception _ex) { } } while (true); }
void start() { if (t == null) { t = new Thread(this, "UDP.OutgoingPacketHandler thread"); t.setDaemon(true); t.start(); } }
@Override /** {@inheritDoc} */ public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; }
/** * Send a message to a specified address. * * @param message Pre-formatted message to send. * @param receiverAddress Address to send it to. * @param receiverPort Receiver port. * @throws IOException If there is a problem connecting or sending. */ public void sendMessage( byte message[], InetAddress receiverAddress, int receiverPort, boolean retry) throws IOException { if (message == null || receiverAddress == null) throw new IllegalArgumentException("Null argument"); SSLSocket sock = (SSLSocket) this.stack.ioHandler.sendBytes(receiverAddress, receiverPort, "TLS", message, retry); // // Created a new socket so close the old one and s // Check for null (bug fix sent in by Christophe) if (sock != mySock && sock != null) { try { if (mySock != null) mySock.close(); } catch (IOException ex) { /* ignore */ } mySock = sock; this.myClientInputStream = mySock.getInputStream(); this.myClientOutputStream = mySock.getOutputStream(); // start a new reader on this end of the pipe. Thread mythread = new Thread(this); mythread.setDaemon(true); mythread.setName("TLSMessageChannelThread"); mythread.start(); } }
/** * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by * the interface (and its superinterfaces) will be invocable. */ public <T> InAppServer( String name, String portFilename, InetAddress inetAddress, Class<T> exportedInterface, T handler) { this.fullName = name + "Server"; this.exportedInterface = exportedInterface; this.handler = handler; // In the absence of authentication, we shouldn't risk starting a server as root. if (System.getProperty("user.name").equals("root")) { Log.warn( "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!"); return; } try { File portFile = FileUtilities.fileFromString(portFilename); secretFile = new File(portFile.getPath() + ".secret"); Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName); // If there are no other threads left, the InApp server shouldn't keep us alive. serverThread.setDaemon(true); serverThread.start(); } catch (Throwable th) { Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th); } writeNewSecret(); }
/** Start the network listening thread. */ void start() { this.running = true; Thread thread = new Thread(this, "IceConnector@" + hashCode()); thread.setDaemon(true); thread.start(); }
void start() { logger.log(Level.FINEST, "Starting TCP node"); please_stop = false; node_thread = new SelectThread(); node_thread.setDaemon(true); node_thread.start(); logger.log(Level.FINEST, "Started TCP node"); }
public void start() { if (thread == null) { thread = new Thread(this, "UDP.UcastReceiverThread"); thread.setDaemon(true); running = true; thread.start(); } }
private void startReceiver() { if (receiver == null || !receiver.isAlive()) { receiver = new Thread(Util.getGlobalThreadGroup(), this, "ReceiverThread"); receiver.setDaemon(true); receiver.start(); if (log.isTraceEnabled()) log.trace("receiver thread started"); } }
public TRTrackerServerUDP(String _name, int _port, boolean _start_up_ready) { super(_name, _start_up_ready); port = _port; thread_pool = new ThreadPool("TrackerServer:UDP:" + port, THREAD_POOL_SIZE); try { InetAddress bind_ip = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress(); InetSocketAddress address; DatagramSocket socket; if (bind_ip == null) { address = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port); socket = new DatagramSocket(port); } else { current_bind_ip = bind_ip; address = new InetSocketAddress(bind_ip, port); socket = new DatagramSocket(address); } socket.setReuseAddress(true); dg_socket = socket; final InetSocketAddress f_address = address; Thread recv_thread = new AEThread("TRTrackerServerUDP:recv.loop") { public void runSupport() { recvLoop(dg_socket, f_address); } }; recv_thread.setDaemon(true); recv_thread.start(); Logger.log(new LogEvent(LOGID, "TRTrackerServerUDP: recv established on port " + port)); } catch (Throwable e) { Logger.log( new LogEvent( LOGID, "TRTrackerServerUDP: " + "DatagramSocket bind failed on port " + port, e)); } }
public synchronized void connect(long timeout) throws TransportException { try { switch (state) { case 0: break; case 3: return; // already connected case 4: state = 0; throw new TransportException("Connection in error", te); default: TransportException te = new TransportException("Invalid state: " + state); state = 0; throw te; } state = 1; te = null; thread = new Thread(this, name); thread.setDaemon(true); synchronized (thread) { thread.start(); thread.wait(timeout); /* wait for doConnect */ switch (state) { case 1: /* doConnect never returned */ state = 0; thread = null; throw new TransportException("Connection timeout"); case 2: if (te != null) { /* doConnect throw Exception */ state = 4; /* error */ thread = null; throw te; } state = 3; /* Success! */ return; } } } catch (InterruptedException ie) { state = 0; thread = null; throw new TransportException(ie); } finally { /* This guarantees that we leave in a valid state */ if (state != 0 && state != 3 && state != 4) { if (log.level >= 1) log.println("Invalid state: " + state); state = 0; thread = null; } } }
/** * Constructor - takes a datagram packet and a stack structure Extracts the address of the other * from the datagram packet and stashes away the pointer to the passed stack structure. * * @param stack is the shared SIPStack structure * @param messageProcessor is the creating message processor. */ protected UDPMessageChannel(SIPTransactionStack stack, UDPMessageProcessor messageProcessor) { super.messageProcessor = messageProcessor; this.sipStack = stack; Thread mythread = new Thread(this); this.myAddress = messageProcessor.getIpAddress().getHostAddress(); this.myPort = messageProcessor.getPort(); mythread.setName("UDPMessageChannelThread"); mythread.setDaemon(true); mythread.start(); }
/** * Constructor. We create one of these in order to process an incoming message. * * @param stack is the SIP sipStack. * @param messageProcessor is the creating message processor. * @param packet is the incoming datagram packet. */ protected UDPMessageChannel( SIPTransactionStack stack, UDPMessageProcessor messageProcessor, DatagramPacket packet) { this.incomingPacket = packet; super.messageProcessor = messageProcessor; this.sipStack = stack; this.myAddress = messageProcessor.getIpAddress().getHostAddress(); this.myPort = messageProcessor.getPort(); Thread mythread = new Thread(this); mythread.setDaemon(true); mythread.start(); }
/** * Asynchronously sends a message to a single server, registering a listener to receive a callback * on success or exception. Multiple asynchronous lookups can be performed in parallel. Since the * callback may be invoked before the function returns, external synchronization is necessary. * * @param query The query to send * @param listener The object containing the callbacks. * @return An identifier, which is also a parameter in the callback */ public Object sendAsync(final Message query, final ResolverListener listener) { final Object id; synchronized (this) { id = new Integer(uniqueID++); } Record question = query.getQuestion(); String qname; if (question != null) qname = question.getName().toString(); else qname = "(none)"; String name = this.getClass() + ": " + qname; Thread thread = new ResolveThread(this, query, id, listener); thread.setName(name); thread.setDaemon(true); thread.start(); return id; }
/** Re Initialize the stack instance. */ protected void reInit() { super.reInit(); clientTransactions = Collections.synchronizedList(new ArrayList<SIPClientTransaction>()); serverTransactions = Collections.synchronizedList(new ArrayList<SIPServerTransaction>()); pendingTransactions = new HashSet<SIPServerTransaction>(); pendingRecords = Collections.synchronizedList(new ArrayList<PendingRecord>()); clientTransactionTable = new Hashtable<String, SIPTransaction>(); serverTransactionTable = new Hashtable<String, SIPTransaction>(); // Dialog dable. this.dialogTable = new Hashtable<String, SIPDialog>(); this.timer = new Timer(); pendingRecordScanner = new Thread(new PendingRecordScanner(this)); pendingRecordScanner.setDaemon(true); pendingRecordScanner.setName("PendingRecordScanner"); pendingRecordScanner.start(); }
public static void main(final String[] args) throws Exception { // System.setProperty("java.net.preferIPv4Stack", "true"); if (2 != args.length && 3 != args.length) { System.out.println( "Usage: java MulticastSender <multicast address> <number of messages> [interface]"); return; } final String address = args[0]; final long count = Long.parseLong(args[1]); final int port = 4445; final int serverPort = 4447; final byte[] buffer = "This is a test string with sufficient data to send".getBytes("ASCII"); final InetAddress group = InetAddress.getByName(address); MulticastSocket socket; if (3 == args.length) { final String interfaceAddress = args[2]; System.out.println("Binding to interface: " + interfaceAddress); socket = new MulticastSocket(new InetSocketAddress(interfaceAddress, serverPort)); } else { socket = new MulticastSocket(serverPort); } final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port); final MulticastSender sender = new MulticastSender(); final Thread t = new Thread(sender); t.setDaemon(true); t.start(); for (long i = count; --i != 0; ) { packet.setData(buffer); socket.send(packet); sender.messageCounter++; } Thread.sleep(1000); socket.close(); }
void requestAccountList() { prog = ProgressDialog.show( this, null, getString(R.string.account_list_progress), false, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { cancel(); } }); queryThread = new Thread(this, "Requestor Thread"); queryThread.setDaemon(true); queryThread.start(); }
public static void main(PeerFactory peerFactory, KeyStore keyStore, String[] args) throws Exception { long time = System.currentTimeMillis(); String relPath; if ((args != null) && (args.length > 0) && args[0].equals("sh")) { relPath = pathToStoresSH; } else { relPath = pathToStores; } PATH = new File(System.getProperty("test.src", "."), relPath); CipherTest.peerFactory = peerFactory; System.out.print("Initializing test '" + peerFactory.getName() + "'..."); // secureRandom = new SecureRandom(); // secureRandom.nextInt(); // trustStore = readKeyStore(trustStoreFile); CipherTest.keyStore = keyStore; // keyStore = readKeyStore(keyStoreFile); KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyFactory.init(keyStore, "test12".toCharArray()); keyManager = (X509ExtendedKeyManager) keyFactory.getKeyManagers()[0]; TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); trustManager = (X509TrustManager) tmf.getTrustManagers()[0]; // trustManager = new AlwaysTrustManager(); SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null); SSLContext.setDefault(context); CipherTest cipherTest = new CipherTest(peerFactory); Thread serverThread = new Thread(peerFactory.newServer(cipherTest), "Server"); serverThread.setDaemon(true); serverThread.start(); System.out.println("Done"); cipherTest.run(); time = System.currentTimeMillis() - time; System.out.println("Done. (" + time + " ms)"); }
@Override public void run() { for (; ; ) { Transport service = new Transport(this); PrologReader R; PrologWriter W; try { Socket socket = service.client_socket; R = toReader(socket.getInputStream()); W = toWriter(socket.getOutputStream()); } catch (IOException e) { errmes("error in ShellServer", e); break; } Shell S = new Shell(args, R, W, false, "?-| "); Thread T = new Thread(S, "ShellThread"); T.setDaemon(true); T.start(); } }
/** * Initializes the server stored list. Synchronize server stored groups and contacts with the * local groups and contacts. */ @Override public void init() { try { SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID(); if (!accountID.isXiVOEnable()) return; boolean useSipCredentials = accountID.isClistOptionUseSipCredentials(); String serverAddress = accountID.getClistOptionServerUri(); String username = accountID.getAccountPropertyString(ProtocolProviderFactory.USER_ID); Address userAddress = sipProvider.parseAddressString(username); if (useSipCredentials) { username = ((SipUri) userAddress.getURI()).getUser(); } else { username = accountID.getClistOptionUser(); } try { connect(serverAddress); } catch (Throwable ex) { showError(ex, null, null); logger.error("Error connecting to server", ex); return; } Thread thread = new Thread(this, this.getClass().getName()); thread.setDaemon(true); thread.start(); if (!login(username)) { showError(null, null, "Unauthorized. Cannot login."); logger.error("Cannot login."); return; } } catch (Throwable t) { logger.error("Error init clist from xivo server"); } }
/** * Send message to whoever is connected to us. Uses the topmost via address to send to. * * @param msg is the message to send. * @param retry */ private void sendMessage(byte[] msg, boolean retry) throws IOException { SSLSocket sock = (SSLSocket) this.stack.ioHandler.sendBytes( this.peerAddress, this.peerPort, this.peerProtocol, msg, retry); // Created a new socket so close the old one and stick the new // one in its place but dont do this if it is a datagram socket. // (could have replied via udp but received via tcp!). if (sock != mySock && sock != null) { try { if (mySock != null) mySock.close(); } catch (IOException ex) { } mySock = sock; this.myClientInputStream = mySock.getInputStream(); this.myClientOutputStream = mySock.getOutputStream(); Thread thread = new Thread(this); thread.setDaemon(true); thread.setName("TLSMessageChannelThread"); thread.start(); } }
/** Starts the unicast and multicast receiver threads */ void startThreads() throws Exception { if (ucast_receiver == null) { // start the listener thread of the ucast_recv_sock ucast_receiver = new UcastReceiver(); ucast_receiver.start(); if (Trace.trace) { Trace.info("UDP.startThreads()", "created unicast receiver thread"); } } if (ip_mcast) { if (mcast_receiver != null) { if (mcast_receiver.isAlive()) { if (Trace.trace) { Trace.info( "UDP.createThreads()", "did not create new multicastreceiver thread as existing " + "multicast receiver thread is still running"); } } else { mcast_receiver = null; // will be created just below... } } if (mcast_receiver == null) { mcast_receiver = new Thread(this, "UDP mcast receiver"); mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ???? mcast_receiver.setDaemon(true); mcast_receiver.start(); } } if (use_outgoing_packet_handler) { outgoing_packet_handler.start(); } if (use_incoming_packet_handler) { incoming_packet_handler.start(); } }
/** * Runs a test query agains the stun server. If it works we set useStun to true, otherwise we set * it to false. */ private void launchStunServerTest() { Thread stunServerTestThread = new Thread("StunServerTestThread") { public void run() { DatagramSocket randomSocket = initRandomPortSocket(); try { StunAddress stunAddress = detector.getMappingFor(randomSocket); randomSocket.disconnect(); if (stunAddress != null) { useStun = true; logger.trace( "StunServer check succeeded for server: " + detector.getServerAddress() + " and local port: " + randomSocket.getLocalPort()); } else { useStun = false; logger.trace( "StunServer check failed for server: " + detector.getServerAddress() + " and local port: " + randomSocket.getLocalPort() + ". No address returned by server."); } } catch (Throwable ex) { logger.error( "Failed to run a stun query against " + "server :" + detector.getServerAddress(), ex); if (randomSocket.isConnected()) randomSocket.disconnect(); useStun = false; } } }; stunServerTestThread.setDaemon(true); stunServerTestThread.start(); }
/** * Constructor - gets called from the SIPStack class with a socket on accepting a new client. All * the processing of the message is done here with the stack being freed up to handle new * connections. The sock input is the socket that is returned from the accept. Global data that is * shared by all threads is accessible in the Server structure. * * @param sock Socket from which to read and write messages. The socket is already connected (was * created as a result of an accept). * @param sipStack Ptr to SIP Stack */ protected TLSMessageChannel( SSLSocket sock, SIPMessageStack sipStack, TLSMessageProcessor msgProcessor) throws IOException { if (LogWriter.needsLogging) { sipStack.logWriter.logMessage("creating new TLSMessageChannel "); sipStack.logWriter.logStackTrace(); } mySock = sock; peerAddress = mySock.getInetAddress(); myAddress = sipStack.getHostAddress(); myClientInputStream = mySock.getInputStream(); myClientOutputStream = mySock.getOutputStream(); mythread = new Thread(this); mythread.setDaemon(true); mythread.setName("TLSMessageChannelThread"); // Stash away a pointer to our stack structure. stack = sipStack; this.tlsMessageProcessor = msgProcessor; this.myPort = this.tlsMessageProcessor.getPort(); // Bug report by Vishwashanti Raj Kadiayl super.messageProcessor = msgProcessor; // Can drop this after response is sent potentially. mythread.start(); }
public static void startpriv(InetAddress inetaddress) { threadliveid = (int) (Math.random() * 99999999D); if (active) { try { Thread.sleep(500L); } catch (Exception _ex) { } active = false; } socketreq = 0; threadreq = null; dnsreq = null; savereq = null; urlreq = null; socketip = inetaddress; Thread thread = new Thread(new signlink()); thread.setDaemon(true); thread.start(); while (!active) try { Thread.sleep(50L); } catch (Exception _ex) { } }
public Thread newThread(Runnable r) { Thread t = DEFAULT.newThread(r); t.setDaemon(true); return t; }
public static void launch(String[] args) { if (Launcher.checkAndLaunch(PluginLauncherImpl.class, args)) return; // This *has* to be done first as it sets system properties that are read and cached by Java COConfigurationManager.preInitialise(); final LoggerChannelListener listener = new LoggerChannelListener() { public void messageLogged(int type, String content) { log(content, false); } public void messageLogged(String str, Throwable error) { log(str, true); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); error.printStackTrace(pw); pw.flush(); log(sw.toString(), true); } protected synchronized void log(String str, boolean stdout) { File log_file = getApplicationFile("launch.log"); PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(log_file, true)); if (str.endsWith("\n")) { if (stdout) { System.err.print("PluginLauncher: " + str); } pw.print(str); } else { if (stdout) { System.err.println("PluginLauncher: " + str); } pw.println(str); } } catch (Throwable e) { } finally { if (pw != null) { pw.close(); } } } }; LaunchablePlugin[] launchables = findLaunchablePlugins(listener); if (launchables.length == 0) { listener.messageLogged(LoggerChannel.LT_ERROR, "No launchable plugins found"); return; } else if (launchables.length > 1) { listener.messageLogged( LoggerChannel.LT_ERROR, "Multiple launchable plugins found, running first"); } try { // set default details for restarter SystemProperties.setApplicationEntryPoint("org.gudy.azureus2.plugins.PluginLauncher"); launchables[0].setDefaults(args); // see if we're a secondary instance if (PluginSingleInstanceHandler.process(listener, args)) { return; } // we have to run the core startup on a separate thread and then effectively pass "this // thread" // through to the launchable "process" method Thread core_thread = new Thread("PluginLauncher") { public void run() { try { // give 'process' call below some time to start up Thread.sleep(500); AzureusCore azureus_core = AzureusCoreFactory.create(); azureus_core.start(); } catch (Throwable e) { listener.messageLogged("PluginLauncher: launch fails", e); } } }; core_thread.setDaemon(true); core_thread.start(); boolean restart = false; boolean process_succeeded = false; try { restart = launchables[0].process(); process_succeeded = true; } finally { try { if (restart) { AzureusCoreFactory.getSingleton().restart(); } else { AzureusCoreFactory.getSingleton().stop(); } } catch (Throwable e) { // only report this exception if we're not already failing if (process_succeeded) { throw (e); } } } } catch (Throwable e) { listener.messageLogged("PluginLauncher: launch fails", e); } }
/** * Provides the default host name that will be proposed to the user for the local host. * * @return the default host name that will be proposed to the user for the local host. */ public static String getDefaultHostName() { if (defaultHostName == null) { // Run a thread in the background in order to avoid blocking the // application if reverse DNS lookups take a long time. final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread( new Runnable() { /** * Search for a host name of the form host.example.com on each interface, except the * loop back. Prefer interfaces of the form ethX. */ public void run() { try { SortedMap<String, String> hostNames = new TreeMap<>(); Enumeration<NetworkInterface> i = NetworkInterface.getNetworkInterfaces(); while (i.hasMoreElements()) { NetworkInterface n = i.nextElement(); // Skip loop back interface. if (n.isLoopback()) { continue; } // Check each interface address (IPv4 and IPv6). String ipv4HostName = null; String ipv6HostName = null; Enumeration<InetAddress> j = n.getInetAddresses(); while (j.hasMoreElements()) { InetAddress address = j.nextElement(); String hostAddress = address.getHostAddress(); String hostName = address.getCanonicalHostName(); // Ignore hostnames which are IP addresses. if (!hostAddress.equals(hostName)) { if (address instanceof Inet4Address) { ipv4HostName = hostName; } else if (address instanceof Inet6Address) { ipv6HostName = hostName; } } } // Remember the host name if it looks fully qualified. String fqHostName = null; if (ipv4HostName != null && ipv4HostName.contains(".")) { fqHostName = ipv4HostName; } else if (ipv6HostName != null && ipv6HostName.contains(".")) { fqHostName = ipv6HostName; } if (fqHostName != null) { hostNames.put(n.getName(), fqHostName); // This looks like a fully qualified name on a ethX interface, // so // use that and break out. if (n.getName().startsWith("eth")) { defaultHostName = fqHostName; break; } } } if (defaultHostName == null && !hostNames.isEmpty()) { // No ethX host name, so try any other host name that was found. defaultHostName = hostNames.values().iterator().next(); } } catch (Exception e) { // Ignore - we'll default to the loopback address later. } latch.countDown(); } }); try { t.setDaemon(true); t.start(); latch.await(1, TimeUnit.SECONDS); } catch (Exception e) { // Ignore - we'll default to the loopback address later. } if (defaultHostName == null) { // No host names found, so use the loop back. try { defaultHostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { // Not much we can do here. defaultHostName = "localhost"; } } } return defaultHostName; }
public void run() { active = true; String s = findcachedir(); uid = getuid(s); try { File file = new File(s + "main_file_cache.dat"); if (file.exists() && file.length() > 0x3200000L) file.delete(); cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw"); for (int j = 0; j < 5; j++) cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw"); } catch (Exception exception) { exception.printStackTrace(); } for (int i = threadliveid; threadliveid == i; ) { if (socketreq != 0) { try { socket = new Socket(socketip, socketreq); } catch (Exception _ex) { socket = null; } socketreq = 0; } else if (threadreq != null) { Thread thread = new Thread(threadreq); thread.setDaemon(true); thread.start(); thread.setPriority(threadreqpri); threadreq = null; } else if (dnsreq != null) { try { dns = InetAddress.getByName(dnsreq).getHostName(); } catch (Exception _ex) { dns = "unknown"; } dnsreq = null; } else if (savereq != null) { if (savebuf != null) try { FileOutputStream fileoutputstream = new FileOutputStream(s + savereq); fileoutputstream.write(savebuf, 0, savelen); fileoutputstream.close(); } catch (Exception _ex) { } if (waveplay) { String wave = s + savereq; waveplay = false; } if (midiplay) { midi = s + savereq; midiplay = false; } savereq = null; } else if (urlreq != null) { try { System.out.println("urlstream"); urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream()); } catch (Exception _ex) { urlstream = null; } urlreq = null; } try { Thread.sleep(50L); } catch (Exception _ex) { } } }