Transformações

De opensipsbrasil - wiki
Revisão de 17h15min de 23 de abril de 2014 por Mike (discussão | contribs)
Ir para navegação Ir para pesquisar

Transformação é basicamente a função que é aplicada a uma variável (variavel de script, pseudo-variavel, AVPS, strings staticas), para pegar um valor especial, o valor da variável horiginal não é alterado.

Exemplo utilizando diferentes tipos de variáveis em no script OpenSIPS

# verificando se o usuário no cabeçalho From é igual ao usuário no cabeçalho To 

if($fU==$tU) {
   ...
}

# checagem de usuário baseado em r-uri 

switch($ruri.user) {
   case "1234":
      ...
   break;
   case "5678":
      ...
   break;
   default:
     ...
}

# definindo um valor inteiro para um AVP 
$avp(i:11) = 1;

# definindo um valor de texto (string) para um AVP
$avp(i:22) = "opensips";

# Definir o valor de $ruri para um avp
$avp(i:33) = $ruri;

# concatenando "sip:" + usuário no From + "@" + dominio no To na variável x
$var(x) = "sip:" + $fU +"@" + $td;


As transformações possuem o intuito de facilitar o acesso a diferentes atributos de variáveis, como o tamanho da string (strlen) , partes do valor, substring ou valores diferentes de variaveis (encoded em hexa, valor md5, escapar valores para operações em banco).


A transformação é representada entre '{' e '}' e segue o nome da variável. Quando utilizando transformação, o nome da variável e transformações devem estar dentro de parentesis '(' e ')' .

Exemplo:

# o tamanho do From URI ( $fu é uma pseudo-variável para From URI)

$(fu{s.len})

Muitas transformações podem ser aplicadas ao mesmo tempo na mesma variável.

# O tamanho do cabeçalho 'Test' (escapado) .

$(hdr(Test){s.escape.common}{s.len})

A transformação pode ser utilizada em qualquer lugar, sendo considerada parte das variáveis no script --- no xlog, avpops ou outros módulos, funções e parametros, a direita de expressões de atribuição ou em comparações.

Para aprender que variável pode ser utilizada com transformações veja [Variáveis Core]

Transformação de string

O nome destas trasnformações iniciam com 's.' , são utilizadas para aplicar operações de string nas variáveis.


Transformações disponiveis nesta classe:

{s.len}

Retorna o tamanho do valor de uma variável

$var(x) = "abc";
if($(var(x){s.len}) == 3)
{
   ...
}

{s.int}

Retorna o valor inteiro de uma string númerica.

$var(x) = "1234";
if($(var(x){s.int})==1234) {
  ...
}

{s.md5}

Retorna o md5 do valor da variável

xlog("MD4 over From username: $(fU{s.md5})");

{s.substr,offset,length}

Retornar o pedaço (substring) iniciando no valor de offset até o valor de length . Se offset é negativo, então a contagem começa no fim, onde -1 é o último caracter. Em caso de valor positivo, 0 é o primeiro valor, o tamanho (length) deve ser positivo, em caso de 0, a substring retornará até o fim do valor, offset e length podem ser variáveis também.


Example:

$var(x) = "abcd";
$(var(x){s.substr,1,0}) = "bcd"

{s.select,index,separator}

Retorna um campo do valor da variável. O campo é selecionado baseado no spearador (separator) e indice (index). O separador deve ser um caractere usado para identificar os campos. Indice (index) deve ser um valor inteiro ou uma variavel. Se o index for negativo a contagem de campos começa do fim do valor, -1 é o último campo, se o index é positivo, 0 é o primeiro campo.

Exemplo:

$var(x) = "12,34,56";
$(var(x){s.select,1,,}) => "34" ;

$var(x) = "12,34,56";
$(var(x){s.select,-2,,}) => "34"

{s.encode.hexa}

Retorna o valor da variável em hexa.


{s.decode.hexa}

Decodifica o valor hexa da variável.


{s.escape.common}

Retorna a string scapada do valor da variável. Caracteres escapados são ', ", e 0 , este recurso é util quando necessário realizar consultas em banco de dados ( deve se atentar quando utilizando caracteres que não fazem parte do LATIN )


{s.unescape.common}

Retorna o valor sem escape de uma variável, o inverso da transformação acima.


{s.escape.user}

Retorna o valor escapado da variavel, alterando para '%hexa' os caracteres nao permitidos na area SIP URI seguindos as recomendações da RFC.

{s.unescape.user}

Retorna o valor sem escape da variável, alterando de '%hexa' para caracter, o inverso da transformação acima.

{s.escape.param}

Retorna o valor escapado da variável, alterando para '%hexa' o caractere que não é permitido na area param da SIP URI seguindo as recomendações da RFC.


{s.unescape.param}

Retorna o valor sem escape da variavel alterando de '%hexa' para caractere, inverso da transformação acima.


{s.tolower}

Retorna a string em lower case (caixa baixa)


{s.toupper}

Retorna a string em upper case (caixa alta)


URI Transformations

O nome da transformação inicia-se com 'uri.'. O valor da variável é considerado ser parte da SIP URI. Esta transformação retorna partes da SIP URI (veja struct sip_uri). Se a parte estiver faltando o valor retornando será uma string vazia.

Transformações disponiveis nesta classe:


{uri.user}

Retorna o usuário no schema URI


{uri.host}

(mesmo que {uri.domain})

Retorna a parte do dominio no schema URI.

{uri.passwd}

Retorna a parte da senha no schema URI.


{uri.port}

Retorna a parte da porta no schema URI.


{uri.params}

Retorna todos os parametros da URI em uma única string.


{uri.param,name}

Retorna o valor do parametro da URI com nome de "name"


{uri.headers}

Retorna os cabeçalhos URI


{uri.transport}

Retorna o valor do parametro transport da URI.


{uri.ttl}

Retorna o valor do parametro TTL da URI.


{uri.uparam}

Retorna o valor do parametro user da URI.


{uri.maddr}

Retorna o valor do parametro maddr da URI.

{uri.method}

Retorna o valor do parametro metodo da URI.


!!!!{uri.lr}

Returns the value of lr URI parameter.

!!!!{uri.r2}

Returns the value of r2 URI parameter.

!!!VIA Transformations

These transformations parse Via headers and all starts with @@via.@@. The value of the variable is considered to be a SIP Via header. This transformation returns parts of the via header (see struct via_body). If the requested part is missing, the returned value is an empty string. Transformation will fail (with script error) if variable holding the Via header is empty. Unless otherwise specified in descriptions below, the result of transform is a string (not an integer).

Examples:

   $var(upstreamtransport) = $(hdr(Via)[1]{via.transport}{s.tolower});
   $var(upstreamip) = $(hdr(Via)[1]{via.param,received});
   $var(clientport) = $(hdr(Via)[-1]{via.param,rport});


Available transformations in this class:

!!!!{via.name}

Returns the @@protocol-name@@ (of RFC3261 BNF), generally @@SIP@@.

!!!!{via.version}

Returns the @@protocol-version@@ (of RFC3261 BNF), generally @@2.0@@.

!!!!{via.transport}

Returns the @@transport@@ (of RFC3261 BNF), e.g., @@UDP@@, @@TCP@@, @@TLS@@. This is the transport protocol used to send the request message.

!!!!{via.host}

(same as @@{via.domain}@@)

Returns the @@host@@ portion of the @@sent-by@@ (of RFC3261 BNF). Typically this is the IP address of the sender of the request message, and is the address to which the response will be sent.

!!!!{via.port}

Returns the @@port@@ portion of the @@sent-by@@ (of RFC3261 BNF). Typically this is the IP port of the sender of the request message, and is the address to which the response will be sent. Result of transform is valid as both integer and string.

!!!!{via.comment}

The comment associated with the via header. The @@struct via_body@@ contains this field, but it isn't clear that RFC3261 allows Via headers to have comments (see text at top of page 221, and the BNF doesn't explicit allow comment within Via). The comment is the text enclosed within parens.

!!!!{via.params}

Returns all the Via headers parameters (@@via-param@@ of RFC3261 BNF) as single string. Result can be processed using the @@{param.*}@@ transforms. This is essentially everything after the host and port.

!!!!{via.param,name}

Returns the value of Via header parameter with name @@name@@. Typical parameters include @@branch@@, @@rport@@ and @@received@@.

!!!!{via.branch}

Returns the value of the branch parameter in the VIA header.

!!!!{via.received}

Returns the value of the received parameter in the VIA header, if any.

!!!!{via.rport}

Returns the value of the rport parameter in the VIA header, if any.

!!!Parameters List Transformations

The name of the transformation starts with "param.". The value of the variable is considered to be a string like name1=value1;name2=value2;...". The transformations returns the value for a specific parameter, or the name of a parameter at a specific index.

Available transformations in this class:


!!!!{param.value,name}

Returns the value of parameter 'name'

Example: [@ "a=1;b=2;c=3"{param.value,c} = "3" @]

'name' can be a variable

!!!!{param.exist,name}

Returns 1 if the parameter @@name@@ exists (with or without value), else 0. Returned value is both string and integer. @@name@@ can be variable. This can be used to test existence of parameters that do not have values.

Example: [@ "a=0;b=2;ob;c=3"{param.exist,ob}; # returns 1 "a=0;b=2;ob;c=3"{param.exist,a}; # returns 1 "a=0;b=2;ob;c=3"{param.exist,foo}; # returns 0 @]

!!!!{param.valueat,index}

Returns the value of parameter at position give by 'index' (0-based index)

Example: [@ "a=1;b=2;c=3"{param.valueat,1} = "2" @]

'index' can be a variable

!!!!{param.name,index}

Returns the name of parameter at position 'index'.

Example: [@ "a=1;b=2;c=3"{param.name,1} = "b" @]


!!!!{param.count}

Returns the number of parameters in the list.

Example: [@ "a=1;b=2;c=3"{param.count} = 3 @]


!!!Name-address Transformations

The name of the transformation starts with 'nameaddr.'. The value of the variable is considered to be a string like '[display_name] uri'. The transformations returns the value for a specific field.

Available transformations in this class:


!!!!{nameaddr.name}

Returns the value of display name

Example: [@ '"test" <sip:test@opensips.org>' {nameaddr.name} = "test" @]

!!!!{nameaddr.uri}

Returns the value of URI

Example: [@ '"test" <sip:test@opensips.org>' {nameaddr.uri} = sip:test@opensips.org @]

!!!!{nameaddr.len}

Returns the length of the entire name-addr part from the value.


!!!!{nameaddr.param,param_name}

Returns the value of the parameter with name param_name. Example: [@ '"test" <sip:test@opensips.org>;tag=dat43h' {nameaddr.param,tag} = dat43h @]

!!!!{nameaddr.params}

Returns all the parameters and their corresponding values. Example: [@ '"test" <sip:test@opensips.org>;tag=dat43h;private=yes' {nameaddr.params} = "tag=dat43h;private=yes" @]

!!!IP Transformations

The name of the transformation starts with 'ip.'. Available transformations in this class:

!!!!{ip.pton}

Returns a binary representation of a string represented IP. Example: [@ "192.168.2.134" {ip.pton} returns a 4 byte binary representation of the IP provided @]

!!!!{ip.ntop}

Returns a string representation of the binary IP provided Example: [@ "192.168.2.134"{ip.pton}{ip.ntop} = "192.168.2.134" @]

!!!!{ip.isip}

Returns 1 or 0, if the string provided is a valid IP or not. Example: [@ "192.168.2.134" {ip.isip} = 1 "192.168.2.134.1" {ip.isip} = 0 @]

!!!!{ip.family} Returns INET or INET6 if the binary IP representation provided is IPv4 or IPv6. Example: [@ "192.168.2.134" {ip.pton}{ip.family} = "INET" @]

!!!!{ip.resolve} Returns the resolved IP address coresponding to the string domain provided. Transformation has no effect if a string IP is provided. Example: [@ "opensips.org" {ip.resolve} = "78.46.64.50" @]

!!!CSV Transformations

The name of the transformation starts with "csv.". The value of the variable is considered to be a string like "field1,field2,...". The transformations return the number of entries in the provided CSV, or the field at a specified position in the CSV.

Available transformations in this class:

!!!!{csv.count} Returns the number of entries in the provided CSV. Example: [@ "a,b,c" {csv.count} = 3 @]

!!!!{csv.value} Returns the entry at the specified positions. Indexing starts from 0. Example: [@ "a,b,c" {csv.value,2} = c @]

!!!SDP Transformations

The name of the transformation starts with "sdp.". The value of the variable is considered to be a valid SDP body. The transformation returns a specific line in the SDP body.

Available transformations in this class:

!!!!{sdp.line} Returns the specified line in the SDP body. The transformations also accepts a second parameter, that specifies the line number of the first parameter's type to get from the SDP body. Indexing starts from 0. If the second parameter is missing, it is assumed to be 0. Example: [@ if (is_method("INVITE"))

  {
     $var(aline) = $(rb{sdp.line,a,1});
     xlog("The second a line in the SDP body is $var(aline)\n");
  }

if (is_method("INVITE"))

  {
     $var(mline) = $(rb{sdp.line,m});
     xlog("The first m line in the SDP body is $var(mline)\n");
  }

@]

!!!Regular Expression Transformations

The name of the transformation starts with "re.". The input can be any string.

!!!!{re.subst,reg_exp}

The reg_exp parameter can either be a plain string or a variable. The format of the reg_exp is :

   /posix_match_expression/replacement_expression/flags

The flags can be

   i - match ignore case
   s - match within multi-lines strings
   g - replace all matches

Example: [@ $var(reg_input)="abc"; $var(reg) = "/a/A/g"; xlog("Applying reg exp $var(reg) to $var(reg_input) : $(var(reg_input){re.subst,$var(reg)})\n");

... ... xlog("Applying reg /b/B/g to $var(reg_input) : $(var(reg_input){re.subst,/b/B/g})\n"); @]


!!!Examples

Within a variable, many transformation can be applied, being executed from left to right.

  • The length of the value of parameter at postion 1 (remember 0 is first position, 1 is second position)

[@ $var(x) = "a=1;b=22;c=333"; $(var(x){param.value,$(var(x){param.name,1})}{s.len}) = 2 @]

  • Test if whether is un-registration or not

[@ if(is_method("REGISTER") && is_present_hf("Expires") && $(hdr(Expires){s.int})==0)

   xlog("This is an un-registrationn");

@]