Basic Use of Tmp-String-0 - freeradius

I'm trying to use the Tmp-String-0 variable within a dhcp site enabled.
My version is old and in production (2.1.12).
Here is the content of my dhcp file.
dhcp DHCP-Discover {
update control{
Tmp-String-0 = "%{sql: CALL sqlprocedure('%{DHCP-Agent-Circuit-Id}','%{DHCP-Gateway-IP-Address}','%{DHCP-Relay-Remote-Id}')}"
}
if(control:Tmp-String-0 != "" ) {
update reply {
DHCP-Message-Type = DHCP-Offer
}
}
else {
update reply {
DHCP-Message-Type = DHCP-NAK
}
}
update reply {
DHCP-Your-IP-Address = "control:Tmp-String-0"
}
}
And here is the result I have in debug mode.
rlm_sql_mysql: query: CALL sqlprocedure('value','1.2.3.4','value')
sql_xlat finished
rlm_sql (sql): Released sql socket id: 4
expand: %{sql: CALL sqlprocedure('%{DHCP-Agent-Circuit-Id}','%{DHCP-Gateway-IP-Address}','%{DHCP-Relay-Remote-Id}')} -> 10.10.10.10
++[control] returns noop
++? if (control:Tmp-String-0 != "" )
? Evaluating (control:Tmp-String-0 != "" ) -> TRUE
++? if (control:Tmp-String-0 != "" ) -> TRUE
++- entering if (control:Tmp-String-0 != "" ) {...}
+++[reply] returns noop
++- if (control:Tmp-String-0 != "" ) returns noop
++ ... skipping else for request 445: Preceding "if" was taken
ERROR: Failed parsing value "control:Tmp-String-0" for attribute DHCP-Your-
IP-Address: Failed to find IP address for control:Tmp-String-0
++[reply] returns fail
I don't know what is wrong with that maybe I should use the operator "=" instead of ":=".
What do you think?
Many thanks, Will

Did you try the following
update reply {
DHCP-Your-IP-Address = "Tmp-String-0"
}

Related

NSwagStudio deserializing error when return type is string

I am experiencing the following error: NSwagStudio generates a typescript client which is trying to deserializing json when api return type is plain string.
I am using .netCore 2.2 and NSwagStudio 13.16.1
The client generated is:
if (status === 400) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result400: any = null;
result400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as string;
return throwException("A server side error occurred.", status, _responseText, _headers, result400);
}));
while the API has the following decorator:
[ProducesResponseType(typeof(string),StatusCodes.Status400BadRequest)]
As you can see, the client is trying to parse the _responseText, which causes the error. The _responseText is a plain string.
How can i solve this problem?
I think it's a Front End problem. Please, don't minimize.
if (status === 400) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result400: any = null;
result400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as string;
return throwException("A server side error occurred.", status, _responseText, _headers,
}));
}

Postman GET request to Binance API

I'm trying to send a GET request to Binance's API, but I don't exactly know how to.
Here is the documentation page: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data
I have a private apiKey and secretKey.
I can do a general request to Binance, but I cannot get my private data, using my private keys.
First try:
For the GET request in Postman I use this string:
https://api.binance.com/api/v3/account?timestamp=1499827319559&signature=here_I_put_my_secret_key
And I pass as a header as Danny suggested the apiKey.
But I get:
{
"code": -1021,
"msg": "Timestamp for this request is outside of the recvWindow."
}
Thanks.
I solved this correcting the time using javascript in Postman.
Another easy fix is to use the ccxt library : https://github.com/ccxt/ccxt
This might be what you're after, as per the documentation.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#endpoint-security-type
API-keys are passed into the Rest API via the X-MBX-APIKEY header.
In your Request, add that as the header key and your API Key as the value.
You can try this. This is working for me. Just Replace your API_KEY and SECRET
You need to retrieve serverTime time from https://api.binance.com/api/v3/time and need to use that serverTime to sign the request.
GET : https://api.binance.com/api/v3/account?timestamp={{timestamp}}&signature={{signature}}
Header:
Content-Type:application/json
X-MBX-APIKEY:YOUR_API_KEY
Pre-request Script :
pm.sendRequest('https://api.binance.com/api/v3/time', function (err, res) {
console.log('Timestamp Response: '+res.json().serverTime);
pm.expect(err).to.not.be.ok;
var timestamp = res.json().serverTime;
postman.setEnvironmentVariable('timestamp',timestamp)
postman.setGlobalVariable('timestamp',timestamp)
let paramsObject = {};
const binance_api_secret = 'YOUR_API_SECRET';
const parameters = pm.request.url.query;
parameters.map((param) => {
if (param.key != 'signature' &&
param.key != 'timestamp' &&
!is_empty(param.value) &&
!is_disabled(param.disabled)) {
paramsObject[param.key] = param.value;
}
})
Object.assign(paramsObject, {'timestamp': timestamp});
if (binance_api_secret) {
const queryString = Object.keys(paramsObject).map((key) => {
return `${encodeURIComponent(key)}=${paramsObject[key]}`;
}).join('&');
console.log(queryString);
const signature = CryptoJS.HmacSHA256(queryString, binance_api_secret).toString();
pm.environment.set("signature", signature);
}
function is_disabled(str) {
return str == true;
}
function is_empty(str) {
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
{
return true;
}
else
{
return false;
}
}
}
);
Get the official Postman collections for the Binance API from here:
https://github.com/binance/binance-api-postman
Import the desired collection and environment in Postman, for instance
binance_spot_api_v1.postman_collection.json
and binance_com_spot_api.postman_environment.json
Add your API key to the binance-api-key environment variable and your secret key to the binance-api-secret variable.
CAUTION: Limit what the key can do in Binance key management. Do not use this key for production, only for testing. Create new key for production.
For the signed requests calculate the signature in a Pre-request Script then set the signature environment variable.
Example Pre-request Script:
function resolveQueryString() {
const query = JSON.parse(JSON.stringify(pm.request.url.query))
const keyPairs = []
for (param of query) {
if (param.key === 'signature') continue
if (param.disabled) continue
if (param.value === null) continue
const value = param.value.includes('{{') ? pm.environment.get(param.key) : param.value
keyPairs.push(`${param.key}=${value}`)
}
return keyPairs.join('&')
}
const signature = CryptoJS.HmacSHA256(
resolveQueryString(),
pm.environment.get('binance-api-secret')
).toString(CryptoJS.enc.Hex)
pm.environment.set('signature', signature)

Application crashes in IBM Mobilfirst

I am developing a hybrid application with IBM Worklight 7.0.
I am searching with the following command from the local store with the following code. This code works by pressing each button on the screen. After the user has been running for a while, the application crashes. Does this cause a search with "like" command? Does the this code work asynchronously?
My Code :
var queryPart = WL.JSONStore.QueryPart().like('name', str).like('type',
typeStr);
WL.JSONStore.get(allReason.name).advancedFind([queryPart]).
then(function(arrayResults) { ... }
Logcat :
E/SQLiteLog( 1481): (10) POSIX Error : 11 SQLite Error : 3850
D/NONE (26304): reasons event binded!
D/PhoneWindow(26304): *FMB* installDecor mIsFloating : true
D/PhoneWindow(26304): *FMB* installDecor flags : 8388610
W/ResourceType(26304): Failure getting entry for 0x01080ad0 (t=7 e=2768)
(error -75)
D/InputDispatcher( 898): Focus left window: 26304
D/InputDispatcher( 898): Focus entered window: 26304
D/PhoneWindow(26304): *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
D/PhoneWindow(26304): *FMB* isFloatingMenuEnabled return false
D/NONE (26304): Request [/apps/services/api/Bukalemun/android/ heartbeat]
I/System.out(26304): Thread-1548(ApacheHTTPLog):isSBSettingEnabled false
I/System.out(26304): Thread-1548(ApacheHTTPLog):isShipBuild true
I/System.out(26304): Thread-1548(ApacheHTTPLog):SMARTBONDING_ENABLED is
false
I/System.out(26304): Thread-1548(ApacheHTTPLog):SmartBonding Enabling is
false, SHIP_BUILD is true, log to file is false, DBG is false
D/Netd ( 256): getNetworkForDns: using netid 0 for uid 10187
I/System.out(26304): pool-5-thread-6 calls detatch()
D/HttpPostRequestSender(26304): WLHybridRequestSender.run in
WLHybridRequestSender.java:42 :: Sending request
http://
xxxx.org.tr:80 /Bukalemun/apps/services/api/Bukalemun/android/heartbeat
E/NONE (26304): [/apps/services/api/Bukalemun/android/heartbeat] Host is
not responsive. Try to manually access the URL through the android emulator
browser to verify connectivity.
D/NONE (26304): Failed to send heartbeat
Below is the code that pulls the data to the selectboxes.
var queryPart = WL.JSONStore.QueryPart().like('name', regexStr3).like('type',
asansorTipi);
WL.JSONStore.get(allReason.name).advancedFind([queryPart]).then(function(arrayResults) {
// if data not present , get the data from DB
if (arrayResults.length == 0) {
} else {
var myLikeReasonId = arrayResults[0].json.reasonid;
if(myLikeReasonId != null && myLikeReasonId != ' '){
tmpVal = myLikeReasonId +','+ '2';
reasonValue = tmpVal.split(',');
$("#"+reasonValue[0]).each ( function() {
if(reasonValue[1] == 1 || reasonValue[1] == 2 || reasonValue[1] == 3){
$(this).val(reasonValue[1]).change();
if(reasonValue[1] == "2") {
uygundegil = true;
uygunDegilArray.push(reasonValue[0]);
} else if(reasonValue[1] == "3"){
uygulanamaz = true;
uygulanamazArray.push(reasonValue[0]);
} else {
uygun = true;
uygunArray.push(reasonValue[0]);
}
}
});
} else {
WL.Logger.error("collection filter returns null result.");
}
}
}).fail(function(errorObject) {
WL.Logger.error("fail" + errorObject);
});
By looking up the error code: 3850. It seems there is an IO lock problem. I would surround your code with a try{}catch() and if you receive the 3850 error, wait and try the process again.
The SQLITE_IOERR_LOCK error code is an extended error code for SQLITE_IOERR indicating an I/O error in the advisory file locking logic. Usually an SQLITE_IOERR_LOCK error indicates a problem obtaining a PENDING lock. However it can also indicate miscellaneous locking errors on some of the specialized VFSes used on Macs.

How to get all transaction history against a chaincode in Hyperledger fabric

I am able to do transactions in Hyperledger (fabric implementation). I want to see all the transactions and its payload details initiated by a user by passing the user's key.
for example:
A transfers 10 units to B
A transfers 5 units to C
D transfers 8 units to A
When I pass A's key then fabric must provide me all the transactions of A.
Is there any way? Or which fabric API function call should I use?
/chain/blocks/{Block} endpoint carries ordered list of transactions in a specified block.
Use /chain endpoint to get the height (number of blocks) of your chain, and then retrieve transactions from each block using /chain/blocks/{Block} REST endpoint.
You can develop the proper indexing and query function in your chaincode.
Meaning for each transaction you store its details in the internal key/value store (stub.PutState) with the user as key and return all the transactions associated to a user in your query (stub.GetState).
The best and simplest way is to use the shim package function
GetHistoryForKey(key string)
As the documentation says:
GetHistoryForKey function can be invoked by a chaincode to return a history of key values across time.
GetHistoryForKey is intended to be used for read-only queries.
IF anyone need Java SDk and go chaincode combination. There you go
answered here similar question
Java code
public List<HistoryDao> getUFOHistory(String key) throws Exception {
String[] args = { key };
Logger.getLogger(QueryChaincode.class.getName()).log(Level.INFO, "UFO communication history - " + args[0]);
Collection<ProposalResponse> responses1Query = ucc.getChannelClient().queryByChainCode("skynetchaincode", "getHistoryForUFO", args);
String stringResponse = null;
ArrayList<HistoryDao> newArrayList = new ArrayList<>();
for (ProposalResponse pres : responses1Query) {
stringResponse = new String(pres.getChaincodeActionResponsePayload());
Logger.getLogger(QueryChaincode.class.getName()).log(Level.INFO, stringResponse);
newArrayList = gson.fromJson(stringResponse, new TypeToken<ArrayList<HistoryDao>>() {
}.getType());
}
if (null == stringResponse)
stringResponse = "Not able to find any ufo communication history";
return newArrayList;
}
and you go chancode implemetation is as follows
Go code
func (t *SmartContract) getHistoryForUFO(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) < 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
ufoId := args[0]
resultsIterator, err := APIstub.GetHistoryForKey(ufoId)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
response, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"TxId\":")
buffer.WriteString("\"")
buffer.WriteString(response.TxId)
buffer.WriteString("\"")
buffer.WriteString(", \"Value\":")
// if it was a delete operation on given key, then we need to set the
//corresponding value null. Else, we will write the response.Value
//as-is (as the Value itself a JSON)
if response.IsDelete {
buffer.WriteString("null")
} else {
buffer.WriteString(string(response.Value))
}
buffer.WriteString(", \"Timestamp\":")
buffer.WriteString("\"")
buffer.WriteString(time.Unix(response.Timestamp.Seconds, int64(response.Timestamp.Nanos)).String())
buffer.WriteString("\"")
buffer.WriteString(", \"IsDelete\":")
buffer.WriteString("\"")
buffer.WriteString(strconv.FormatBool(response.IsDelete))
buffer.WriteString("\"")
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("- History returning:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
Let me know if you question.
If you are using composer-client, you can simply use the Historian command.
var historian = await businessNetworkConnection.getHistorian();
historian.getAll().then(historianRecords => console.log(historianRecords));

What does these F5 iRules mean?

I have no knowledge of F5 and trying to read these rules. If some one can help me understand them.
Following rules is reading HTTP request and (defining variable INTRSSN?) getting a node and saving it in a persistence table.
when HTTP_REQUEST {
if { ( [HTTP::method] eq "POST") and
( [HTTP::path] equals "/webserv/Interaction") and
( [HTTP::header value "Content-Length"] < 1024 ) }{
#Debugging Purpose
#log local0. "First Request: [HTTP::uri]"
HTTP::collect [HTTP::header Content-Length]
if { [info exists "INTRSSN"] }{
set IntrExist [persist lookup uie $INTRSSN node]
#log local0. "Response check if exist $IntrExist"
if {($IntrExist != "")}{
node $IntrExist
}
}
}
}
This rule will read the HTTP request and extract a specific tag value is put it in INTRSSN variable. This variable will be saved in persistence table.
when HTTP_REQUEST_DATA {
if { ( [HTTP::path] equals "/webserv/Interaction") and
( [HTTP::header value "Content-Length"] < 1024 ) }{
set INTRSSN [findstr [HTTP::payload] "<soap1:sessionID>" 17 "<"]}
if { $INTRSSN != "" } {
#Debugging Purpose
#log local0. "SOAP Session ID: $INTRSSN"
catch { persist uie "$INTRSSN"}
#log local0. "Request_Data $INTRSSN"
}
}
I did not understand this event.
when HTTP_RESPONSE {
if { [HTTP::header "Content-Type" ] equals "text/xml" }{
set resdata [HTTP::payload]
set INTRSSN [findstr $resdata "<sessionID>" 11 "<"]
if { $INTRSSN != "" } {
#Debugging Purpose
#log local0. "Found sessionID on Response: $INTRSSN in SOAP response from: [LB::server addr]"
#log local0. "Interaction $INTRSSN"
catch {persist add uie $INTRSSN 600}
}
}
}
The HTTP_RESPONSE portion attempts to read the XML response and also extract a specific tag value, put it in the $INTRSSN value and save/update a persistence record.
Basically, the whole iRule put together is a way of mapping a specific field within the HTTP body to use for persistence (ensuring the connection goes to the same backend server for the life of the connection).

Resources