Reads the peer's address. First a cookie has to be sent which has to
match my own cookie, otherwise the connection will be refused
359576
protected Address readPeerAddress(Socket client_sock) throws Exception {
        int timeout=client_sock.getSoTimeout();
        client_sock.setSoTimeout(server.peerAddressReadTimeout());

        try {
            // read the cookie first
            byte[] input_cookie=new byte[cookie.length];
            in.readFully(input_cookie, 0, input_cookie.length);
            if(!Arrays.equals(cookie, input_cookie))
                throw new SocketException(String.format("%s: BaseServer.TcpConnection.readPeerAddress(): cookie sent by " +
                                                          "%s:%d does not match own cookie; terminating connection",
                                                        server.localAddress(), client_sock.getInetAddress(), client_sock.getPort()));
            // then read the version
            short version=in.readShort();
            if(!Version.isBinaryCompatible(version))
                throw new IOException("packet from " + client_sock.getInetAddress() + ":" + client_sock.getPort() +
                                        " has different version (" + Version.print(version) +
                                        ") from ours (" + Version.printVersion() + "); discarding it");
            in.readShort(); // address length is only needed by NioConnection

            Address client_peer_addr=new IpAddress();
            client_peer_addr.readFrom(in);
            updateLastAccessed();
            return client_peer_addr;
        }
        finally {
            client_sock.setSoTimeout(timeout);
        }
    }
859712
function readSingleAddress(conn, handleAddress){
	readSingleWallet(conn, function(wallet_id){
		conn.query("SELECT address FROM my_addresses WHERE wallet=?", [wallet_id], function(rows){
			if (rows.length === 0)
				throw Error("no addresses");
			if (rows.length > 1)
				throw Error("more than 1 address");
			handleAddress(rows[0].address);
		});
	})
}
168373
private HashMap deserializePostParam(IExtendedRequest req, byte[] cookieValueBytes, String reqURL) throws IOException, UnsupportedEncodingException, IllegalStateException {
		HashMap output = null;
		List<byte[]> data = splitBytes(cookieValueBytes, (byte) '.');
		int total = data.size();

		if (total > OFFSET_DATA) {
			// url and at least one data. now deserializing the url.
			String url = new String(Base64Coder.base64Decode(data.get(OFFSET_REQURL)), "UTF-8");
			if (url != null && url.equals(reqURL)) {
				byte[][] bytes = new byte[total - OFFSET_DATA][];
				for (int i = 0; i < (total - OFFSET_DATA); i++) {
					bytes[i] = Base64Coder.base64Decode(data.get(OFFSET_DATA + i));
				}
				output = req.deserializeInputStreamData(bytes);
			} else {
				throw new IllegalStateException("The url in the post param cookie does not match the requested url");
			}
		} else {
			throw new IllegalStateException("The data of the post param cookie is too short. The data might be truncated.");
		}
		return output;
	}
991478
function readSession(intentObj, next) {
    let headers = intentObj.client().headers;
    let sessId;
    try {
      let cookies = cookie.parse(headers['cookie']);
      if (typeof cookies[opt.cookieName] === 'string') {
        let tmp = storeObj.verifySignature(cookies[opt.cookieName]);
        if (tmp) {
          sessId = tmp;
        }
      }
    } catch (e) {
    }
    if (!sessId) sessId = storeObj.readCustomSource(intentObj);
    // IF we don't have a session, we don't have what to read.
    if (!sessId) {
      sessId = storeObj.generateId();
      if (opt.authorization && !intentObj.authorization) {
        intentObj._setAuthorization(AUTHORIZATION_TYPE, sessId);
      }
      intentObj.session = new SessionData(sessId);
      intentObj.session.isNew(true);
      return next();
    }
    if (intentObj.session && intentObj.session.id === sessId) {
      return next();
    }
    // otherwise, we have to retrieve it.
    storeObj.readSession(sessId, (err, data, custom) => {
      // if we failed tor ead from store, empty session.
      if (err) {
        if (err.ns !== 'SESSION') {
          logger.warn('Failed to read session data for sid ' + sessId, err);
        }
        intentObj.session = new SessionData(sessId);
        intentObj.session.isNew(true);
      } else {
        // if there is no session data, we have a new session.
        if (typeof data !== 'object' || !data) {
          intentObj.session = new SessionData(sessId);
          intentObj.session.isNew(true);
        } else {
          intentObj.session = new SessionData(sessId, data);
          intentObj.session.isNew(false);
        }
      }
      if (custom && intentObj.session._setFields) {
        intentObj.session._setFields(custom);
      }
      if (opt.authorization && !intentObj.authorization) {
        intentObj._setAuthorization(AUTHORIZATION_TYPE, sessId);
      }
      next();
    }, false);
  }
221287
function peerResolved (ip, addressType) {
    // Possible cancelation during DNS lookup.
    if (!socket._connecting) return;

    socket._peer = { address: ip || '127.0.0.1', port: options.port };

    // Generate random bytes used to set randomized socket properties.
    // `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes.
    //
    //  * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html).
    //  * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517)
    crypto.randomBytes(4, valid(randomzied));
  }
137595
def getPeer(self, url):
        
        peers = list(models.Peer.select().where(models.Peer.url == url))
        if len(peers) == 0:
            raise exceptions.PeerNotFoundException(url)
        return peers[0]
1130318
def initpeer(self, sock):
        '''
        
        '''
        location_json = requests.request("GET", "http://freegeoip.net/json/"
                                         + sock.getpeername()[0]).content
        location = json.loads(location_json)
        tpeer = peer.Peer(sock, self.reactor, self, location)
        self.peer_dict[sock] = tpeer
        self.reactor.select_list.append(tpeer)
132827
static Cookie getLTPACookie(final Subject subject) throws Exception {
        Cookie ltpaCookie = null;
        SingleSignonToken ssoToken = null;
        Set<SingleSignonToken> ssoTokens = subject.getPrivateCredentials(SingleSignonToken.class);
        Iterator<SingleSignonToken> ssoTokensIterator = ssoTokens.iterator();
        if (ssoTokensIterator.hasNext()) {
            ssoToken = ssoTokensIterator.next();
            if (ssoTokensIterator.hasNext()) {
                throw new WSSecurityException("More than one ssotoken found in subject");
            }
        }
        if (ssoToken != null) {
            ltpaCookie = constructLTPACookieObj(ssoToken);
        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "No ssotoken found for this subject");
            }
        }
        return ltpaCookie;
    }
1061815
public function read($cookie_name = null)
    {
        if (!empty($cookie_name)) {
            $this->setName($cookie_name);
        }
        $val = isset($_COOKIE[$this->getName()]) ? $_COOKIE[$this->getName()] : null;
        if ($val && is_string($val) && ($this->getFlag() & self::FLATNESS_ARRAY)) {
            parse_str($val, $tmp_val); 
            if (!empty($tmp_val) && $tmp_val!=$val) {
                $val = $tmp_val;
            }
        }
        $this->setValue($val);
        return $this->getValue();
    }
903545
def decode_address(self, addr):
        """"""
        if _debug: Address._debug("decode_address %r (%s)", addr, type(addr))

        # start out assuming this is a local station
        self.addrType = Address.localStationAddr
        self.addrNet = None

        if addr == "*":
            if _debug: Address._debug("    - localBroadcast")

            self.addrType = Address.localBroadcastAddr
            self.addrNet = None
            self.addrAddr = None
            self.addrLen = None

        elif addr == "*:*":
            if _debug: Address._debug("   - globalBroadcast")

            self.addrType = Address.globalBroadcastAddr
            self.addrNet = None
            self.addrAddr = None
            self.addrLen = None

        elif isinstance(addr, int):
            if _debug: Address._debug("    - int")
            if (addr < 0) or (addr >= 256):
                raise ValueError("address out of range")

            self.addrAddr = struct.pack('B', addr)
            self.addrLen = 1

        elif isinstance(addr, basestring):
            if _debug: Address._debug("    - str")

            m = ip_address_mask_port_re.match(addr)
            if m:
                if _debug: Address._debug("    - IP address")

                net, addr, mask, port = m.groups()
                if not mask: mask = '32'
                if not port: port = '47808'
                if _debug: Address._debug("    - net, addr, mask, port: %r, %r, %r, %r", net, addr, mask, port)

                if net:
                    net = int(net)
                    if (net >= 65535):
                        raise ValueError("network out of range")
                    self.addrType = Address.remoteStationAddr
                    self.addrNet = net

                self.addrPort = int(port)
                self.addrTuple = (addr, self.addrPort)

                addrstr = socket.inet_aton(addr)
                self.addrIP = struct.unpack('!L', addrstr)[0]
                self.addrMask = (_long_mask << (32 - int(mask))) & _long_mask
                self.addrHost = (self.addrIP & ~self.addrMask)
                self.addrSubnet = (self.addrIP & self.addrMask)

                bcast = (self.addrSubnet | ~self.addrMask)
                self.addrBroadcastTuple = (socket.inet_ntoa(struct.pack('!L', bcast & _long_mask)), self.addrPort)

                self.addrAddr = addrstr + struct.pack('!H', self.addrPort & _short_mask)
                self.addrLen = 6

            elif ethernet_re.match(addr):
                if _debug: Address._debug("    - ethernet")

                self.addrAddr = xtob(addr, ':')
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^\d+$", addr):
                if _debug: Address._debug("    - int")

                addr = int(addr)
                if (addr > 255):
                    raise ValueError("address out of range")

                self.addrAddr = struct.pack('B', addr)
                self.addrLen = 1

            elif re.match(r"^\d+:[*]$", addr):
                if _debug: Address._debug("    - remote broadcast")

                addr = int(addr[:-2])
                if (addr >= 65535):
                    raise ValueError("network out of range")

                self.addrType = Address.remoteBroadcastAddr
                self.addrNet = addr
                self.addrAddr = None
                self.addrLen = None

            elif re.match(r"^\d+:\d+$",addr):
                if _debug: Address._debug("    - remote station")

                net, addr = addr.split(':')
                net = int(net)
                addr = int(addr)
                if (net >= 65535):
                    raise ValueError("network out of range")
                if (addr > 255):
                    raise ValueError("address out of range")

                self.addrType = Address.remoteStationAddr
                self.addrNet = net
                self.addrAddr = struct.pack('B', addr)
                self.addrLen = 1

            elif re.match(r"^0x([0-9A-Fa-f][0-9A-Fa-f])+$",addr):
                if _debug: Address._debug("    - modern hex string")

                self.addrAddr = xtob(addr[2:])
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^X'([0-9A-Fa-f][0-9A-Fa-f])+'$",addr):
                if _debug: Address._debug("    - old school hex string")

                self.addrAddr = xtob(addr[2:-1])
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^\d+:0x([0-9A-Fa-f][0-9A-Fa-f])+$",addr):
                if _debug: Address._debug("    - remote station with modern hex string")

                net, addr = addr.split(':')
                net = int(net)
                if (net >= 65535):
                    raise ValueError("network out of range")

                self.addrType = Address.remoteStationAddr
                self.addrNet = net
                self.addrAddr = xtob(addr[2:])
                self.addrLen = len(self.addrAddr)

            elif re.match(r"^\d+:X'([0-9A-Fa-f][0-9A-Fa-f])+'$",addr):
                if _debug: Address._debug("    - remote station with old school hex string")

                net, addr = addr.split(':')
                net = int(net)
                if (net >= 65535):
                    raise ValueError("network out of range")

                self.addrType = Address.remoteStationAddr
                self.addrNet = net
                self.addrAddr = xtob(addr[2:-1])
                self.addrLen = len(self.addrAddr)

            elif netifaces and interface_re.match(addr):
                if _debug: Address._debug("    - interface name with optional port")

                interface, port = interface_re.match(addr).groups()
                if port is not None:
                    self.addrPort = int(port)
                else:
                    self.addrPort = 47808

                interfaces = netifaces.interfaces()
                if interface not in interfaces:
                    raise ValueError("not an interface: %s" % (interface,))
                if _debug: Address._debug("    - interfaces: %r", interfaces)

                ifaddresses = netifaces.ifaddresses(interface)
                if netifaces.AF_INET not in ifaddresses:
                    raise ValueError("interface does not support IPv4: %s" % (interface,))

                ipv4addresses = ifaddresses[netifaces.AF_INET]
                if len(ipv4addresses) > 1:
                    raise ValueError("interface supports multiple IPv4 addresses: %s" % (interface,))
                ifaddress = ipv4addresses[0]
                if _debug: Address._debug("    - ifaddress: %r", ifaddress)

                addr = ifaddress['addr']
                self.addrTuple = (addr, self.addrPort)
                if _debug: Address._debug("    - addrTuple: %r", self.addrTuple)

                addrstr = socket.inet_aton(addr)
                self.addrIP = struct.unpack('!L', addrstr)[0]

                if 'netmask' in ifaddress:
                    maskstr = socket.inet_aton(ifaddress['netmask'])
                    self.addrMask = struct.unpack('!L', maskstr)[0]
                else:
                    self.addrMask = _long_mask

                self.addrHost = (self.addrIP & ~self.addrMask)
                self.addrSubnet = (self.addrIP & self.addrMask)

                if 'broadcast' in ifaddress:
                    self.addrBroadcastTuple = (ifaddress['broadcast'], self.addrPort)
                else:
                    self.addrBroadcastTuple = None
                if _debug: Address._debug("    - addrBroadcastTuple: %r", self.addrBroadcastTuple)

                self.addrAddr = addrstr + struct.pack('!H', self.addrPort & _short_mask)
                self.addrLen = 6

            else:
                raise ValueError("unrecognized format")

        elif isinstance(addr, tuple):
            addr, port = addr
            self.addrPort = int(port)

            if isinstance(addr, basestring):
                if not addr:
                    # when ('', n) is passed it is the local host address, but that
                    # could be more than one on a multihomed machine, the empty string
                    # means "any".
                    addrstr = '\0\0\0\0'
                else:
                    addrstr = socket.inet_aton(addr)
                self.addrTuple = (addr, self.addrPort)

            elif isinstance(addr, (int, long)):
                addrstr = struct.pack('!L', addr & _long_mask)
                self.addrTuple = (socket.inet_ntoa(addrstr), self.addrPort)

            else:
                raise TypeError("tuple must be (string, port) or (long, port)")
            if _debug: Address._debug("    - addrstr: %r", addrstr)

            self.addrIP = struct.unpack('!L', addrstr)[0]
            self.addrMask = _long_mask
            self.addrHost = None
            self.addrSubnet = None
            self.addrBroadcastTuple = self.addrTuple

            self.addrAddr = addrstr + struct.pack('!H', self.addrPort & _short_mask)
            self.addrLen = 6

        else:
            raise TypeError("integer, string or tuple required")
1041834
def data(hexdata)
      require "digest/sha1"
      data = hex_decode(hexdata)
      # name of cookie file, id of cookie in file, servers random challenge
      context, id, s_challenge = data.split(" ")
      # Random client challenge
      c_challenge = 1.upto(s_challenge.bytesize / 2).map { rand(255).to_s }.join
      # Search cookie file for id
      path = File.join(ENV["HOME"], ".dbus-keyrings", context)
      DBus.logger.debug "path: #{path.inspect}"
      File.foreach(path) do |line|
        if line.index(id).zero?
          # Right line of file, read cookie
          cookie = line.split(" ")[2].chomp
          DBus.logger.debug "cookie: #{cookie.inspect}"
          # Concatenate and encrypt
          to_encrypt = [s_challenge, c_challenge, cookie].join(":")
          sha = Digest::SHA1.hexdigest(to_encrypt)
          # the almighty tcp server wants everything hex encoded
          hex_response = hex_encode("#{c_challenge} #{sha}")
          # Return response
          response = [:AuthOk, hex_response]
          return response
        end
      end
      # a little rescue magic
      unless @retries <= 0
        puts "ERROR: Could not auth, will now exit."
        puts "ERROR: Unable to locate cookie, retry in 1 second."
        @retries -= 1
        sleep 1
        data(hexdata)
      end
    end
556173
function(cb){
				deposit.getDepositAddressBySupernodeAddress(conn, objUnit.authors[0].address, function (err,depositAddress){
					if(err)
						 return cb(err + " can not send pow unit");
					if(payload.deposit != depositAddress)
						return cb("pow unit deposit address is invalid expeected :" + depositAddress +" Actual :" + payload.deposit);
					deposit.getBalanceOfDepositContract(conn, depositAddress,objUnit.round_index,  function (err,balance){
						if(err)
							return cb(err);
						depositBalance = balance;
						cb();
					   }); 
				});
			}
1346856
private static String convertV0SetCookie(HttpCookie cookie, boolean isRFC1123DateEnabled) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Cookie Name: " + cookie.getName());
            Tr.debug(tc, "Cookie MaxAge: " + cookie.getMaxAge());
            Tr.debug(tc, "RFC1123 Date Enabled (4 digit year): " + isRFC1123DateEnabled);
        }

        StringBuilder buffer = new StringBuilder(40);

        // Append name=value
        buffer.append(cookie.getName());
        String value = cookie.getValue();
        if (null != value && 0 != value.length()) {
            buffer.append('=');
            buffer.append(value);
        } else {
            // PK48196 - send an empty value string
            buffer.append("=\"\"");
        }

        // check for optional comment
        String comment = cookie.getComment();
        if (null != comment && 0 != comment.length()) {
            buffer.append("; Comment=");
            maybeQuote(buffer, comment);
        }

        // check for optional max-age/expires
        int expires = cookie.getMaxAge();
        if (-1 < expires) {
            if (0 == expires) {
                if (!isRFC1123DateEnabled) {
                    buffer.append(longAgo);
                } else {
                    buffer.append(longAgoRFC1123);
                }
            } else {
                buffer.append("; Expires=");
                if (!isRFC1123DateEnabled) {
                    buffer.append(HttpDispatcher.getDateFormatter().getRFC2109Time(new Date(HttpDispatcher.getApproxTime() + (expires * 1000L))));
                } else {
                    buffer.append(HttpDispatcher.getDateFormatter().getRFC1123Time(new Date(HttpDispatcher.getApproxTime() + (expires * 1000L))));
                }
            }
        } else if (cookie.isDiscard()) {
            // convert discard to immediate expiration
            if (!isRFC1123DateEnabled) {
                buffer.append(longAgo);
            } else {
                buffer.append(longAgoRFC1123);
            }
        }

        // check for optional path
        value = cookie.getPath();
        if (null != value && 0 != value.length()) {
            buffer.append("; Path=");
            buffer.append(value);
        }

        // check for optional domain
        value = cookie.getDomain();
        if (null != value && 0 != value.length()) {
            buffer.append("; Domain=");
            buffer.append(value);
        }

        if (cookie.isSecure()) {
            buffer.append("; Secure");
        }

        if (cookie.isHttpOnly()) {
            buffer.append("; HttpOnly");
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Created v0 Set-Cookie: [" + GenericUtils.nullOutPasswords(buffer.toString(), (byte) '&') + "]");
        }
        return buffer.toString();
    }
247915
def _parse_peer_address(self, config):
        
        match = re.search(r'peer-address ([^\s]+)', config)
        value = match.group(1) if match else None
        return dict(peer_address=value)
1245232
private static HttpCookie parseInternal(String header,
                                            boolean retainHeader)
    {
        HttpCookie cookie = null;
        String namevaluePair = null;

        StringTokenizer tokenizer = new StringTokenizer(header, ";");

        // there should always have at least on name-value pair;
        // it's cookie's name
        try {
            namevaluePair = tokenizer.nextToken();
            int index = namevaluePair.indexOf('=');
            if (index != -1) {
                String name = namevaluePair.substring(0, index).trim();
                String value = namevaluePair.substring(index + 1).trim();
                if (retainHeader)
                    cookie = new HttpCookie(name,
                                            stripOffSurroundingQuote(value),
                                            header);
                else
                    cookie = new HttpCookie(name,
                                            stripOffSurroundingQuote(value));
            } else {
                // no "=" in name-value pair; it's an error
                throw new IllegalArgumentException("Invalid cookie name-value pair");
            }
        } catch (NoSuchElementException ignored) {
            throw new IllegalArgumentException("Empty cookie header string");
        }

        // remaining name-value pairs are cookie's attributes
        while (tokenizer.hasMoreTokens()) {
            namevaluePair = tokenizer.nextToken();
            int index = namevaluePair.indexOf('=');
            String name, value;
            if (index != -1) {
                name = namevaluePair.substring(0, index).trim();
                value = namevaluePair.substring(index + 1).trim();
            } else {
                name = namevaluePair.trim();
                value = null;
            }

            // assign attribute to cookie
            assignAttribute(cookie, name, value);
        }

        return cookie;
    }
913715
def my_address_string(self):
        
        addr = getattr(self, 'client_address', ('', None))[0]

        # If listed in proxy_ips, use the X-Forwarded-For header, if present.
        if addr in self.proxy_ips:
            return self.headers.getheader('x-forwarded-for', addr)
        return addr
253934
private synchronized void bind(TcpIpConnection connection, Address remoteEndPoint, Address localEndpoint, boolean reply) {
        if (logger.isFinestEnabled()) {
            logger.finest("Binding " + connection + " to " + remoteEndPoint + ", reply is " + reply);
        }

        final Address thisAddress = ioService.getThisAddress();

        // Some simple spoofing attack prevention
        // Prevent BINDs from src that doesn't match the BIND local address
        // Prevent BINDs from src that match us (same host & port)
        if (spoofingChecks && (!ensureValidBindSource(connection, remoteEndPoint) || !ensureBindNotFromSelf(connection,
                remoteEndPoint, thisAddress))) {
            return;
        }

        // Prevent BINDs that don't have this node as the destination
        if (!ensureValidBindTarget(connection, remoteEndPoint, localEndpoint, thisAddress)) {
            return;
        }

        bind0(connection, remoteEndPoint, null, reply);
    }