Why do I get an MSPL exception "ProxyRequest only valid for sipRequest" - sip

I'm writing a Lync MSPL application using a manifest and a windows service. In my manifest.am I have the following code:
<?xml version="1.0"?>
<r:applicationManifest
r:appUri="http://www.company.no/LyncServerFilter"
xmlns:r="http://schemas.microsoft.com/lcs/2006/05">
<r:requestFilter methodNames="ALL"
strictRoute="true"
domainSupported="false"/>
<r:responseFilter reasonCodes="ALL"/>
<r:proxyByDefault action="true" />
<r:allowRegistrationBeforeUserServices action="true" />
<r:splScript>
<![CDATA[
callId = GetHeaderValues("Call-ID");
cseq = GetHeaderValues("CSeq");
content = "";
sstate = GetHeaderValues("subscription-state");
xevent = GetHeaderValues("Event");
xdir = GetHeaderValues("Direction");
xexp = GetHeaderValues("Session-Expires");
referto = GetHeaderValues("Refer-To");
if (sipRequest)
{
if (sipRequest.Method == "INVITE") {
if (ContainsString(sipRequest.Content, "m=audio", true)) {
content = "audio";
}
else if (ContainsString(sipRequest.Content, "m=video", true)) {
content = "video";
}
else if (ContainsString(sipRequest.Content, "m=message", true)) {
content = "message";
}
else if (ContainsString(sipRequest.Content, "m=application", true)) {
content = "application";
}
else {
content = "unknown";
}
}
else if (sipRequest.Method == "NOTIFY" || sipRequest.Method == "BENOTIFY") {
content = sipRequest.Content;
}
DispatchNotification("OnRequest", sipRequest.Method, sipMessage.From, sipMessage.To, callId, cseq, content, xdir, xevent, sstate, xexp, referto);
if (sipRequest) {
ProxyRequest();
}
}
else if(sipResponse) {
DispatchNotification("OnResponse", sipResponse.StatusCode, sipResponse.StatusReasonPhrase, sipMessage.From, sipMessage.To, callId, cseq, content, xdir, xevent, sstate, xexp, referto);
ProxyResponse();
}
]]></r:splScript>
</r:applicationManifest>
I'm getting the following errormessage in Eventlog on Lync Front End server:
Lync Server application MSPL script execution aborted because of an error
Application Uri at 'http://www.company.no/LyncServerFilter', at line 60
Error: 0x80070057 - The parameter is incorrect
Additional information: ProxyRequest only valid for sipRequest
Line 60 is where I call ProxyRequest:
if (sipRequest) {
ProxyRequest();
}
Questions:
Why does the errormessage say that ProxyRequest is only valid for a sipRequest? I'm checking that it is a sipMessage right?
Can I remove my call to ProxyRequest() since I have set proxyByDefault=true? Does the DistpathNotification-method "handle" the method (swallow it), or will the message be proxied by default? The code "works" when I remove the call to ProxyRequest(), but I'm not sure what the consequences are...

The ProxyRequest method takes a argument of the uri, which is why you are getting the compile error message.
So you should be calling it like:
ProxyRequest(""); // send to the URI specified in the request itself
Removing it effectivity does the same thing as per your proxyByDefault setting being set to true:
If true, the server automatically proxies any messages that are not handled by the application. If false, the message is dropped and applications that follow this application in the application execution order will not receive it. The default value is true.
As a side-note, you can use compilespl.exe, which comes as part of the Lync Server SDK to verify that your MSPL script is correct before trying to start it on the lync server.
Check out this link in the 'Compile the MSPL application separately' section.

Related

Get image from a server in Unity 2018

I need to receive image from a simple server, using wgsi, in my client app in Unity3D. My code looks like this for now:
Server part:
if environ['REQUEST_METHOD'] == 'GET':
status = '200 OK'
headers = [('Content-type', 'image/png')]
start_response(status, headers)
return open("./static/uploads/04b32b3b6249487fbe042cadc97748b5.png", "rb").read()
Client:
UnityWebRequest www = UnityWebRequestTexture.GetTexture(uploadURL);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("gno");
this.GetComponent<RawImage>().texture = DownloadHandlerTexture.GetContent(www);
}
}
My doubt is that UnityWebRequestTexture.GetTexture() always takes an URL that points directly to an image, where in my case it doesn't, but the GET method directly returns an image to the client.
All the POST methods where the client sends images to the server work with no problems, while I get a Failed to receive data error in the Unity Editor.
The problem was simply that i wasn't putting the content length in the headers. So the server part should be:
if environ['REQUEST_METHOD'] == 'GET':
status = '200 OK'
headers = [('Content-type', 'image/png')]
img=open("./static/uploads/"+"imageName", "rb").read()
start_response(status,[
('Content-type', 'image/png'),
('Content-Length', str(len(img))),
])
return img

Is it possible to secure a ColdFusion 11 REST Service with HTTP BASIC Authentication?

I am setting up a simple REST Service in ColdFusion 11. The web server is IIS 8.5 on Windows Server 2012R2.
This REST Service needs to be secured to prevent unauthorized users from accessing/writing data. For the time being, there will be only one authorized user, so I want to keep authentication/authorization as simple as possible. My initial thought is to use HTTP BASIC Authentication.
Here's the setup for the REST Service:
Source Directory: C:\web\site1\remoteapi\
REST path: inventory
To implement this, I configured the source directory of the REST Service in IIS to authorize only one user, disable Anonymous authentication, and enable Basic authentication.
When I call the source directory directly in a browser (i.e. http://site1/remoteapi/inventory.cfc?method=read), I am presented with the Basic authentication dialog.
However, when I attempt to request the REST path (http://site1/rest/inventory/), I am not challenged at all.
How can I implement HTTP BASIC authentication on the REST path?
So, due to the need to get this done without much delay, I went ahead and using some principles from Ben Nadel's website, I wrote my own authentication into the onRequestStart() method of the REST Service's Application.cfc. Here is the basic code, though it uses hard-coded values in the VARIABLES scope to validate the username and password and also does not include any actual "authorization" setting:
public boolean function onRequestStart(required string targetPage) {
LOCAL.Response = SUPER.onRequestStart(ARGUMENTS.targetpage);
if (!StructKeyExists(GetHTTPRequestData().Headers, "Authorization")) {
cfheader(
name="WWW-Authenticate",
value="Basic realm=""REST API Access"""
);
LOCAL.RESTResponse = {
status = 401,
content = {Message = "Unauthorized"}
};
restSetResponse(LOCAL.RESTResponse);
}
else {
LOCAL.IsAuthenticated = true;
LOCAL.EncodedCredentials =
GetToken( GetHTTPRequestData().Headers.Authorization, 2, " " );
// Credential string is not Base64
if ( !ArrayLen(
REMatch(
"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$",
LOCAL.EncodedCredentials
)
)
) {
LOCAL.IsAuthenticated = false;
}
else {
// Convert Base64 to String
LOCAL.Credentials =
ToString(ToBinary( LOCAL.EncodedCredentials ));
LOCAL.Username = GetToken( LOCAL.Credentials, 1, ":" );
LOCAL.Password = GetToken( LOCAL.Credentials, 2, ":" );
if ( LOCAL.Username != VARIABLES.CREDENTIALS.Username
|| LOCAL.Password != VARIABLES.CREDENTIALS.Password
) {
LOCAL.IsAuthenticated = false;
}
}
if (!LOCAL.IsAuthenticated) {
LOCAL.Response = {
status = 403,
content = {Message = "Forbidden"}
};
restSetResponse(LOCAL.Response);
}
}
return LOCAL.Response;
}

AuthTicketsHelper.getTicket() returns null

My company uses Perforce for version control and I'm writing software that automates use of Perforce using p4java. I'm running into a problem where my code can't connect to the Perforce server even though I am passing in valid information to use the p4tickets file on my computer.
First, I logged on to perforce to get a p4ticket by running "p4 login", which created the ~/.p4tickets file. But when I run my program that uses p4java to connect using the p4ticket file, it returns null.
AuthTicket auth = AuthTicketsHelper.getTicket(username, serverAddr, p4TicketsFilePath);
// auth == null
I've double checked that the username I'm passing in matches the $P4USER environment variable I had when I used "p4 login", as well as that serverAddr matched the host name that was referenced by my $P4PORT. The p4TicketsFilePath also exists and is the correct path to the .p4tickets file which has my ticket, which is not expired. I'm looking for the reason why getTicket still returns null.
You can debug this issue by copying the source code from AuthTicketsHelper and insert print statements. here's my logger:
private static final Logger logger = LoggerFactory.getLogger(YourClass.class);
(if you don't have a logger, you can do System.out.println() with String.format("... %s ... %s") instead.) Then, copy in this code.
AuthTicket auth;
{
AuthTicket foundTicket = null;
String serverAddress = serverAddr;
String ticketsFilePath = p4TicketsFilePath;
String userName = username;
if (serverAddress != null) {
logger.info("P4TICKETS 1");
if (serverAddress.indexOf(':') == -1) {
serverAddress += "localhost:" + serverAddress;
logger.info("P4TICKETS 2");
}
for (AuthTicket ticket : AuthTicketsHelper.getTickets(ticketsFilePath)) {
logger.info("P4TICKETS 3 {} - {} - {} - {}", serverAddress, ticket.getServerAddress(), userName, ticket.getUserName());
if (serverAddress.equals(ticket.getServerAddress())
&& (userName == null || userName.equals(ticket
.getUserName()))) {
logger.info("P4TICKETS 4");
foundTicket = ticket;
break;
}
}
logger.info("P4TICKETS 5");
}
auth = foundTicket;
}
Follow the code path in the output to see what went wrong. In my case, the server name was a hostname in the code, but my .p4tickets file had an IP address for the server name.

Send email codeigniter function returns "Recipient address rejected: Domain not found" instead of false

I'm using codeigniter. I test to send an email to a wrong inexistant address like t#t.com.
My code is just a method of the controleur like that :
function test() {
$this->email->from('mymail#gmail.com');
$this->email->to(htmlentities("t#t.com"));
$this->email->subject('test');
$this->email->message("Just a test !");
$r = $this->email->send();
if (!$r)
echo "not sent, wrong email";
else
echo "sent";
}
Basically, the send() function returns true or false. But it doesn't work ! The error message I got is as following :
A PHP Error was encountered
Severity: Warning
Message: mail() [function.mail]: SMTP server response: 550 5.1.2 <t#t.com>: Recipient address rejected: Domain not found
Filename: libraries/Email.php
Line Number: 1540
not sent, wrong email
I have the message, so send() function replies false but I also have the error message, which I don't want !
It's a blocking point. Anyone has an idea why send() function doesn't return the true or false reply ?
thanks by advance !
a quick and dirty hack to get rid of the error is to prepend the mail function with '#':
$r = #$this->email->send();
I've tried it and it works as it should, I get: not sent, wrong email.
What version of CI are you using? make sure it's the last one.
Just in case, check the Email.php library under system/libraries in your CI folder
protected function _send_with_mail()
{
if ($this->_safe_mode == TRUE)
{
if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str))
{
return FALSE;
}
else
{
return TRUE;
}
}
else
{
// most documentation of sendmail using the "-f" flag lacks a space after it, however
// we've encountered servers that seem to require it to be in place.
if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))
{
return FALSE;
}
else
{
return TRUE;
}
}
}
Check that the function _send_with_mail() inside looks exactly like the one above

stream_socket_server: Client browser randomly aborting?

Below is partial code to an experimental http server app I'm building from scratch from a PHP CLI script (Why? Because I have too much time on my hands). The example below more closely matches PHP's manual page on this function. The problem I'm getting is when connecting to this server app via a browser (Firefox or IE8 from two separate systems tested so far), the browser sends an empty request payload to the server and aborts roughly every 1 in 6 page loads.
The server console displays the "Connected with [client info]" each time. However, about 1 in 6 connections will result in a "Client request is empty" error. No error is given telling the header/body response write to the socket failed. The browser will generally continue to read what I give it, but this isn't usable as I can't fulfill the client's intended request without knowing what it is.
<?php
$s_socket_uri = 'tcp://localhost:80';
// establish the server on the above socket
$s_socket = stream_socket_server($s_socket_uri, $errno, $errstr, 30) OR
trigger_error("Failed to create socket: $s_socket_uri, Err($errno) $errstr", E_USER_ERROR);
$s_name = stream_socket_get_name($s_socket, false) OR
trigger_error("Server established, yet has no name. Fail!", E_USER_ERROR);
if (!$s_socket || !$s_name) {return false;}
/*
Wait for connections, handle one client request at a time
Though to not clog up the tubes, maybe a process fork is
needed to handle each connection?
*/
while($conn = stream_socket_accept($s_socket, 60, $peer)) {
stream_set_blocking($conn, 0);
// Get the client's request headers, and all POSTed values if any
echo "Connected with $peer. Request info...\n";
$client_request = stream_get_contents($conn);
if (!$client_request) {
trigger_error("Client request is empty!");
}
echo $client_request."\n\n"; // just for debugging
/*
<Insert request handling and logging code here>
*/
// Build headers to send to client
$send_headers = "HTTP/1.0 200 OK\n"
."Server: mine\n"
."Content-Type: text/html\n"
."\n";
// Build the page for client view
$send_body = "<h1>hello world</h1>";
// Make sure the communication is still active
if ((int) fwrite($conn, $send_headers . $send_body) < 1) {
trigger_error("Write to socket failed!");
}
// Response headers and body sent, time to end this connection
stream_socket_shutdown($conn, STREAM_SHUT_WR);
}
?>
Any solution to bring down the number of unintended aborts down to 0, or any method to get more stable communication going? Is this solvable on my server's end, or just typical browser behavior?
I tested your code and it seems I got better results reading the socket with fread(). You also forgot the main loop(while(1), while(true) or for(;;).
Modifications to your code:
stream_socket_accept with #stream_socket_accept [sometimes you get warnings because "the connected party did not properly respond", which is, of course, the timeout of stream_socket_accept()]
Added the big while(1) { } loop
Changed the reading from the socket from $client_request = stream_get_contents($conn);
to while( !preg_match('/\r?\n\r?\n/', $client_request) ) { $client_request .= fread($conn, 1024); }
Check the source code below (I used 8080 port because I already had an Apache listening on 80):
<?php
$s_socket_uri = 'tcp://localhost:8080';
$s_socket = stream_socket_server($s_socket_uri, $errno, $errstr, 30) OR
trigger_error("Failed to create socket: $s_socket_uri, Err($errno) $errstr", E_USER_ERROR);
$s_name = stream_socket_get_name($s_socket, false) OR
trigger_error("Server established, yet has no name. Fail!", E_USER_ERROR);
if (!$s_socket || !$s_name) {return false;}
while(1)
{
while($conn = #stream_socket_accept($s_socket, 60, $peer))
{
stream_set_blocking($conn, 0);
echo "Connected with $peer. Request info...\n";
// $client_request = stream_get_contents($conn);
$client_request = "";
// Read until double \r
while( !preg_match('/\r?\n\r?\n/', $client_request) )
{
$client_request .= fread($conn, 1024);
}
if (!$client_request)
{
trigger_error("Client request is empty!");
}
echo $client_request."\n\n";
$headers = "HTTP/1.0 200 OK\n"
."Server: mine\n"
."Content-Type: text/html\n"
."\n";
$body = "<h1>hello world</h1><br><br>".$client_request;
if ((int) fwrite($conn, $headers . $body) < 1) {
trigger_error("Write to socket failed!");
}
stream_socket_shutdown($conn, STREAM_SHUT_WR);
}
}
Add sleep(1) after stream_set_blocking