内部RPC调用的认证鉴权
@param {MiddlewareParam} sofar
329901
async function handle(sofar) {
    try {
        if (!sofar.socket.user) {
            if (sofar.msg.oemInfo.openkey == sofar.facade.options.admin.role[sofar.msg.oemInfo.openid]) {
                sofar.socket.user = { domain: "system", stype: sofar.msg.stype, sid: sofar.msg.sid, socket: sofar.socket };
            }
        }
        if (!sofar.socket.user) {//未通过身份校验
            sofar.fn({ code: facade.const.ReturnCode.userIllegal });
            sofar.recy = false;
        }
    }
    catch (e) {
        sofar.fn({ code: facade.const.ReturnCode.illegalData });
        sofar.recy = false;
    }
}
546015
private SofaRpcException cannotFoundServiceMethod(String appName, String serviceName, String methodName) {
        String errorMsg = LogCodes.getLog(
            LogCodes.ERROR_PROVIDER_SERVICE_METHOD_CANNOT_FOUND, serviceName, methodName);
        LOGGER.errorWithApp(appName, errorMsg);
        return new SofaRpcException(RpcErrorType.SERVER_NOT_FOUND_INVOKER, errorMsg);
    }
1290489
private SofaRpcException clientTimeoutWhenSendResponse(String appName, String serviceName, String remoteAddress) {
        String errorMsg = LogCodes.getLog(
            LogCodes.ERROR_DISCARD_TIMEOUT_RESPONSE, serviceName, remoteAddress);
        if (LOGGER.isWarnEnabled(appName)) {
            LOGGER.warnWithApp(appName, errorMsg);
        }
        return new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, errorMsg);
    }
675127
function Client(rwStream, options)
{
	events.EventEmitter.call(this);
	
	var tidCounter = 0;
	var requestMap = {};
	var isClosed = true;
	var address = '';
	var host = '';
	
	var idlePingTimeout 	= getOption(options, 'idlePingTimeout',		0);
	var idleCloseTimeout	= getOption(options, 'idleCloseTimeout',	0);
	var autoRegister		= getOption(options, 'autoRegister', 		false);
	var logConnection		= getOption(options, 'logConnection', 		true);
	var autoResponseUnhandledCommand = getOption(options, 'autoResponseUnhandledCommand', true);
	
	this.isServer = options.isServer;
	
	function getAddress()
	{
		return util.format('%s:%s', rwStream.remoteAddress.replace(/^::ffff:/i, ''), rwStream.remotePort);		
	}
	
	function log(event)
	{
		if ( logConnection )
		{
			console.log(util.format('%s %s(%s)', event, host, address));
		}
	}
	
	this.closeStream = function() {

		//console.log('isClosed ' + isClosed);
		
		if ( !isClosed )
		{
			isClosed = true;
			
			log('CLOSE');
			
			if ( rwStream instanceof stream.Writable )
			{
				rwStream.end();
			}
		
			for ( var tid in requestMap )
			{
				if ( requestMap.hasOwnProperty(tid) )
				{
					clearTimeout(requestMap[tid].timer);
					requestMap[tid].callback({code: '500', tid: tid, args: ['socket_closed'], body: null, isValid: true});
					delete requestMap[tid];
				}
			}
			
			this.emit('close');
		}
	};
	
	if ( rwStream instanceof stream.Writable )
	{
		this.sendMessage = function(code, tid, args, body, callback) {
			var bodyBuf = Buffer.isBuffer(body) ? body : 
				typeof(body) === 'string' ? Buffer.from(body) : 
					null;
			tid = tid === -1 ? ++tidCounter : tid;
			tid = '' + tid;
			var bodyLen = bodyBuf ? bodyBuf.length : 0;
			var header = util.format('%s %s %d%s\r\n', code, tid, bodyLen, encodeArgs(args));
			var headerLen = Buffer.byteLength(header);
			var msg = {code: code, tid: tid, args: args, body: body};
			if ( options.debugHeader )
			{
				console.log("send msg: %s", msg2str(msg));
			}
			rwStream.write(header, callback);
			if ( bodyLen > 0 )
			{
				rwStream.write(bodyBuf);
			}
		};

		this.sendRequest = function(code, args, body, timeout, callback) {
			var tid = ++tidCounter;
			this.sendMessage(code, tid, args, body);
			requestMap[tid] = {
				callback: callback,
				timer: setTimeout(() => this.emit('message_timeout', tid), timeout)
			};
		};
	}
	
	if ( rwStream instanceof stream.Readable )
	{
		var parser = textParser.createParser((msg) => {

			if ( options.debugHeader )
			{
				console.log("recv msg: %s", msg2str(msg));
			}

			if ( !msg.isValid && this.sendMessage )
			{
				this.sendMessage('201', 0, 'invalid_command');
			}
			else
			{
				if ( /^\d+$/.test(msg.code) )
				{
					var tid = msg.tid !== null && /^\d+$/.test(msg.tid) ? msg.tid * 1 : 0;
					
					if ( tid > 0 )
					{
						if ( requestMap.hasOwnProperty(msg.tid) )
						{
							clearTimeout(requestMap[msg.tid].timer);
							requestMap[msg.tid].callback(msg);
							delete requestMap[msg.tid];
						}
						else
						{
							console.log(util.format('ERR dangling response: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
						}
					}
					else
					{
						console.log(util.format('ERR invalid tid: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
					}
				}
				else
				{
					var isHandled = false;
					
					if ( this.listenerCount(msg.code) > 0 )
					{
						isHandled = true;
						this.emit(msg.code, msg);
					}
					
					if ( this.listenerCount('message') > 0 )
					{
						isHandled = true;
						this.emit('message', msg);
					} 
					
					if ( !isHandled && autoResponseUnhandledCommand && this.sendMessage )
					{
						this.sendMessage('201', msg.tid, 'unknown_command');
					}
				}
			}
		});
		
		rwStream.on('data', (data) => {
			parser.feed(data);
		});
		
		rwStream.on('end', (e) => {
			this.closeStream();
		});
	}
	
	if ( rwStream instanceof net.Socket )
	{
		if ( !rwStream.connecting )
		{
			this.address = address = getAddress();
			isClosed = false;
			log('ACCEPT');
		}

		if ( idlePingTimeout > 0 )
		{
			rwStream.setTimeout(idlePingTimeout);
		}
		else if ( idleCloseTimeout > 0 )
		{
			rwStream.setTimeout(idleCloseTimeout);
		}
		
		rwStream.on('timeout', () => {
			if ( idlePingTimeout > 0 )
			{
				this.sendMessage('PING', 0, [], null);
				log('PING');
			}
			else if ( idleCloseTimeout > 0 )
			{
				this.closeStream();
			}
			else
			{
				this.emit('timeout');
			}
		});
		
		rwStream.on('connect', () => {
			this.address = address = getAddress();
			isClosed = false;
			log('CONNECT');
			if ( autoRegister )
			{
				this.sendMessage('RGST', 0, os.hostname());
				log('RGST');
			}
			this.emit('connect');
		});
		
		rwStream.on('close', (had_error) => {
			this.closeStream();
		});
		
		this._getSessionManager = function() {
			if ( !this.sessionManager )
			{
				this.sessionManager = new SessionManager(this, options);
			}
			return this.sessionManager;
		};
		
		this.onSession = function(protocol, callback) {
			var smgr = this._getSessionManager();
			var listener_options = Object.assign({}, options, {protocol: protocol});
			var slnr = new SessionListener(listener_options);
			slnr.on('session', callback);
			smgr.registerListener(slnr);
		};
		
		this.createSession = function(protocol, session_args) {
			var smgr = this._getSessionManager();
			var session_options = Object.assign({}, options, {protocol: protocol, session_args: session_args});
			return smgr.createSession(session_options);
		};
	} 
	
	rwStream.on('error', (e) => {
		log('ERROR ' + e.message);
		this.closeStream();
		this.emit('error', e);
	});
	
	this.on('message_timeout', (tid) => {
		if ( requestMap.hasOwnProperty(tid) )
		{
			requestMap[tid].callback({code: '500', tid: tid, args:['message_timeout'], body: null, isValid: true});
			delete requestMap[tid];
		}
	});
	
	this.on('RGST', (msg) => {
		host = msg.args.length > 0 ? msg.args[0] : '';
		log('RGST');
	});
	
	this.on('PING', (msg) => {
		log('PING');
	});
}
842779
@Override
    public SofaResponse invoke(SofaRequest request) throws SofaRpcException {
        SofaResponse response = null;
        Throwable throwable = null;
        try {
            RpcInternalContext.pushContext();
            RpcInternalContext context = RpcInternalContext.getContext();
            context.setProviderSide(false);
            // 包装请求
            decorateRequest(request);
            try {
                // 产生开始调用事件
                if (EventBus.isEnable(ClientStartInvokeEvent.class)) {
                    EventBus.post(new ClientStartInvokeEvent(request));
                }
                // 得到结果
                response = cluster.invoke(request);
            } catch (SofaRpcException e) {
                throwable = e;
                throw e;
            } finally {
                // 产生调用结束事件
                if (!request.isAsync()) {
                    if (EventBus.isEnable(ClientEndInvokeEvent.class)) {
                        EventBus.post(new ClientEndInvokeEvent(request, response, throwable));
                    }
                }
            }
            // 包装响应
            decorateResponse(response);
            return response;
        } finally {
            RpcInternalContext.removeContext();
            RpcInternalContext.popContext();
        }
    }
463540
public Connection getConnection(RpcClient rpcClient, ClientTransportConfig transportConfig, Url url) {
        if (rpcClient == null || transportConfig == null || url == null) {
            return null;
        }
        Connection connection;
        try {
            connection = rpcClient.getConnection(url, url.getConnectTimeout());
        } catch (InterruptedException e) {
            throw new SofaRpcRuntimeException(e);
        } catch (RemotingException e) {
            throw new SofaRpcRuntimeException(e);
        }
        if (connection == null) {
            return null;
        }

        return connection;
    }
310508
function clientRes(res) {
    if (!res || !res.statusCode) {
        return (res);
    }

    return ({
        statusCode: res.statusCode,
        headers: res.headers
    });
}
982286
public static void mlock(Pointer addr, long len) {

        int res = Delegate.mlock(addr, new NativeLong(len));
        if(res != 0) {
            if(logger.isDebugEnabled()) {
                logger.debug("Mlock failed probably because of insufficient privileges, errno:"
                             + errno.strerror() + ", return value:" + res);
            }
        } else {
            if(logger.isDebugEnabled())
                logger.debug("Mlock successfull");

        }

    }
1198280
function requestHandler(req, res, next) {
  const start = Date.now();
  let source;

  return Promise.try(() => {
    source = core.getPublicSource(req.params.src);
    return source.getHandler().getInfoAsync().then(info => [info, infoHeaders]);
  }).spread((data, dataHeaders) => {
    core.setResponseHeaders(res, source, dataHeaders);

    if (req.query && req.query.format) {
      const escapedText = JSON.stringify(data, null, ' ').replace(/&/g, '&amp;').replace(/</g, '&lt;');
      res.send(`<pre>${escapedText}</pre>`);
    } else {
      res.json(data);
    }

    const mx = util.format('req.%s.info', req.params.src);
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
313573
protected SofaRpcException convertToRpcException(Exception e) {
        SofaRpcException exception;
        if (e instanceof SofaRpcException) {
            exception = (SofaRpcException) e;
        }
        // 超时
        else if (e instanceof InvokeTimeoutException) {
            exception = new SofaTimeOutException(e);
        }
        // 服务器忙
        else if (e instanceof InvokeServerBusyException) {
            exception = new SofaRpcException(RpcErrorType.SERVER_BUSY, e);
        }
        // 序列化
        else if (e instanceof SerializationException) {
            boolean isServer = ((SerializationException) e).isServerSide();
            exception = isServer ? new SofaRpcException(RpcErrorType.SERVER_SERIALIZE, e)
                : new SofaRpcException(RpcErrorType.CLIENT_SERIALIZE, e);
        }
        // 反序列化
        else if (e instanceof DeserializationException) {
            boolean isServer = ((DeserializationException) e).isServerSide();
            exception = isServer ? new SofaRpcException(RpcErrorType.SERVER_DESERIALIZE, e)
                : new SofaRpcException(RpcErrorType.CLIENT_DESERIALIZE, e);
        }
        // 长连接断连
        else if (e instanceof ConnectionClosedException) {
            exception = new SofaRpcException(RpcErrorType.CLIENT_NETWORK, e);
        }
        // 客户端发送失败
        else if (e instanceof InvokeSendFailedException) {
            exception = new SofaRpcException(RpcErrorType.CLIENT_NETWORK, e);
        }
        // 服务端未知异常
        else if (e instanceof InvokeServerException) {
            exception = new SofaRpcException(RpcErrorType.SERVER_UNDECLARED_ERROR, e.getCause());
        }
        // 客户端未知
        else {
            exception = new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, e);
        }
        return exception;
    }
533709
function(r) {
    if (!seenConnectionBanner) {
      self.emit('connected', r);
      seenConnectionBanner = true;
      deferredSetup.resolve(r);
      return;
    }

    if (r.hasOwnProperty("rx") && self.serialPortData === null) {
      self.ignoredResponses--;
      if (!self.timedSendsOnly) {
        self.linesRequested = r.rx - 1;
      }
      // -1 is okay, that just means wait until we've sent two lines to send again
    } else if (self.ignoredResponses > 0) {
      self.ignoredResponses--;
      return;
    } else {
        if (!self.timedSendsOnly) {
          self.linesRequested++;
        }
    }

    self._sendLines();
  }
710460
async function handle(sofar) {
    if (!sofar.fn) {
        sofar.fn = ret => { }; // 兼容 notify 和 jsonp 两种情形
    }
    if (!sofar.socket) {
        sofar.socket = {};  //兼容WS、Socket、Http等模式
    }

    //更新时间戳
    sofar.socket.stamp = (new Date()).valueOf(); 

    //对数据进行规整
    sofar.msg.control = sofar.msg.control || 'index';
    sofar.msg.func = sofar.msg.func || 'login';
    sofar.msg.oemInfo = sofar.msg.oemInfo || {};
    if (sofar.msg.oemInfo.constructor == String) {
        sofar.msg.oemInfo = JSON.parse(sofar.msg.oemInfo);
    }
    sofar.msg.oemInfo.domain = !!sofar.msg.oemInfo.domain ? sofar.msg.oemInfo.domain : "official";
    if (sofar.facade.options.serverType == "Test") {
        facade.CoreOfLogic.mapping.map(lt=>{
            let reg = new RegExp(lt, 'g');
            sofar.msg.oemInfo.domain = sofar.msg.oemInfo.domain.replace(reg, "Test");
        });
    }
    sofar.msg.token = sofar.msg.token || {};
    if(sofar.msg.token.constructor == String){
        sofar.msg.token = JSON.parse(sofar.msg.token);
    }
    sofar.msg.userinfo = sofar.msg.userinfo || {};
    if(sofar.msg.userinfo.constructor == String){
        sofar.msg.userinfo = JSON.parse(sofar.msg.userinfo);
    }
    sofar.msg.domainId = !!sofar.msg.oemInfo.openid ? sofar.msg.oemInfo.domain + '.' + sofar.msg.oemInfo.openid : '';
}
536150
protected ProviderInfo select(SofaRequest message, List<ProviderInfo> invokedProviderInfos)
        throws SofaRpcException {
        // 粘滞连接，当前连接可用
        if (consumerConfig.isSticky()) {
            if (lastProviderInfo != null) {
                ProviderInfo providerInfo = lastProviderInfo;
                ClientTransport lastTransport = connectionHolder.getAvailableClientTransport(providerInfo);
                if (lastTransport != null && lastTransport.isAvailable()) {
                    checkAlias(providerInfo, message);
                    return providerInfo;
                }
            }
        }
        // 原始服务列表数据 --> 路由结果
        List<ProviderInfo> providerInfos = routerChain.route(message, null);

        //保存一下原始地址,为了打印
        List<ProviderInfo> orginalProviderInfos = new ArrayList<ProviderInfo>(providerInfos);

        if (CommonUtils.isEmpty(providerInfos)) {
            throw noAvailableProviderException(message.getTargetServiceUniqueName());
        }
        if (CommonUtils.isNotEmpty(invokedProviderInfos) && providerInfos.size() > invokedProviderInfos.size()) { // 总数大于已调用数
            providerInfos.removeAll(invokedProviderInfos);// 已经调用异常的本次不再重试
        }

        String targetIP = null;
        ProviderInfo providerInfo;
        RpcInternalContext context = RpcInternalContext.peekContext();
        if (context != null) {
            targetIP = (String) RpcInternalContext.getContext().getAttachment(RpcConstants.HIDDEN_KEY_PINPOINT);
        }
        if (StringUtils.isNotBlank(targetIP)) {
            // 如果指定了调用地址
            providerInfo = selectPinpointProvider(targetIP, providerInfos);
            if (providerInfo == null) {
                // 指定的不存在
                throw unavailableProviderException(message.getTargetServiceUniqueName(), targetIP);
            }
            ClientTransport clientTransport = selectByProvider(message, providerInfo);
            if (clientTransport == null) {
                // 指定的不存在或已死，抛出异常
                throw unavailableProviderException(message.getTargetServiceUniqueName(), targetIP);
            }
            return providerInfo;
        } else {
            do {
                // 再进行负载均衡筛选
                providerInfo = loadBalancer.select(message, providerInfos);
                ClientTransport transport = selectByProvider(message, providerInfo);
                if (transport != null) {
                    return providerInfo;
                }
                providerInfos.remove(providerInfo);
            } while (!providerInfos.isEmpty());
        }
        throw unavailableProviderException(message.getTargetServiceUniqueName(),
            convertProviders2Urls(orginalProviderInfos));
    }
931931
function(response, resolver, callbackSuccess, callbackError) {

            //xhr = xhr.target || xhr || {};
            var statusCode = xhrSuccessStatus[response.status] || response.status,
                statusType = Number(response.status.toString()[0]),
                promiseResponse;

            var data = response.response;
            var headers = corbel.utils.keysToLowerCase(response.headers);

            if (statusType <= 3 && !response.error) {

                if (response.response) {
                    data = request.parse(response.response, response.responseType, response.dataType);
                }

                if (callbackSuccess) {
                    callbackSuccess.call(this, data, statusCode, response.responseObject, headers);
                }

                promiseResponse = {
                    data: data,
                    status: statusCode,
                    headers: headers
                };

                promiseResponse[response.responseObjectType] = response.responseObject;

                resolver.resolve(promiseResponse);
            } else {

                var disconnected = response.error && response.status === 0;
                statusCode = disconnected ? 0 : statusCode;

                if (callbackError) {
                    callbackError.call(this, response.error, statusCode, response.responseObject, headers);
                }

                if (response.response) {
                    data = request.parse(response.response, response.responseType, response.dataType);
                }

                promiseResponse = {
                    data: data,
                    status: statusCode,
                    error: response.error,
                    headers: headers
                };

                promiseResponse[response.responseObjectType] = response.responseObject;

                resolver.reject(promiseResponse);
            }
        }
1018150
private RpcServerLookoutModel createServerMetricsModel(SofaRequest request, SofaResponse response) {

        RpcServerLookoutModel rpcServerMetricsModel = new RpcServerLookoutModel();

        RpcInternalContext context = RpcInternalContext.getContext();

        String app = request.getTargetAppName();
        String service = request.getTargetServiceUniqueName();
        String method = request.getMethodName();
        String protocol = getStringAvoidNull(request.getRequestProp(RemotingConstants.HEAD_PROTOCOL));
        String invokeType = request.getInvokeType();
        String callerApp = getStringAvoidNull(request.getRequestProp(RemotingConstants.HEAD_APP_NAME));
        Long elapsedTime = getLongAvoidNull(context.getAttachment(RpcConstants.INTERNAL_KEY_IMPL_ELAPSE));
        boolean success = response != null && !response.isError() && response.getErrorMsg() == null &&
            (!(response.getAppResponse() instanceof Throwable));

        rpcServerMetricsModel.setApp(app);
        rpcServerMetricsModel.setService(service);
        rpcServerMetricsModel.setMethod(method);
        rpcServerMetricsModel.setProtocol(protocol);
        rpcServerMetricsModel.setInvokeType(invokeType);
        rpcServerMetricsModel.setCallerApp(callerApp);
        rpcServerMetricsModel.setElapsedTime(elapsedTime);
        rpcServerMetricsModel.setSuccess(success);

        return rpcServerMetricsModel;
    }
1085700
function(r) {
		r.callbackParamName = r.callbackParamName || "callback";
		var fctName = encodeURIComponent("inputEx.RPC.Transport.JSONP.jsonpCallback"+inputEx.RPC.Transport.jsonp_id);
		inputEx.RPC.Transport["JSONP"]["jsonpCallback"+inputEx.RPC.Transport.jsonp_id] = function(results) {
      	if(lang.isObject(r.callback) && lang.isFunction(r.callback.success)) {
      	   r.callback.success.call(r.callback.scope || this, results);
      	}
		};
   	inputEx.RPC.Transport.jsonp_id+=1;
      return util.Get.script( r.target + ((r.target.indexOf("?") == -1) ? '?' : '&') + r.data + "&"+r.callbackParamName+"="+fctName);
   }
443050
function LazyRelayInReq(conn, reqFrame) {
    this.channel = null;
    this.conn = null;
    this.start = null;
    this.remoteAddr = null;
    this.logger = null;
    this.peer = null;
    this.outreq = null;
    this.reqFrame = null;
    this.id = null;
    this.serviceName = null;
    this.callerName = null;
    this.timeout = null;
    this.alive = null;
    this.operations = null;
    this.timeHeapHandle = null;
    this.endpoint = null;
    this.error = null;
    this.tracing = null;
    this.reqContFrames = [];
    this.hasRead = null;
    this.waitForIdentSlot = null;

    this.boundExtendLogInfo = extendLogInfo;
    this.boundOnIdentified = onIdentified;

    var self = this;

    function extendLogInfo(info) {
        return self.extendLogInfo(info);
    }

    function onIdentified(err) {
        // The ident descriptor will be cleared out of the peer when the ident
        // comes back, so this slot id will be invalid once ident happens.
        self.waitForIdentSlot = -1;

        if (err) {
            self.onError(err);
        } else {
            self.onIdentified();
        }
    }
}