opa smtp server usage - smtp

I noticed the Opa API has a SMTPServer extension. I'm not entirely sure how this is to be used. Is what functions of email parsing built in and which have to be written in the handler? I'd appreciate a "hello world" style example for this extension.

This code snippet should help you. It is extracted from the code behing http://forum.opalang.org reply-by-email feature:
function convert_to_utf8(s, b) {
match (Iconv.convert_to_utf8(s, b)) {
case { some : s }: s
default: log_error("..."); ""
}
}
function raw_handler(to, content) {
...
message = Mime.parse(content);
match (message) {
case { some : content }:
content = Mime.get_text(content, convert_to_utf8);
....
default: void
...
}
function handler(string from, list(string) to, string raw_content) {
List.fold({
function(to, acc) _ = raw_handler(to, raw_content); acc
}, to, {success})
}
SmtpServer.start(0.0.0.0, 2525, {none}, handler)

Related

Use of possibly-uninitialized variable after returning

I have this function parse to parse a HTTP request string. I declare an uninitialized variable method then later on in the match statement, I assign it the value GET or I return from the function with an error.
I would think that upon returning Ok, the method field would be either populated or the function would return an error before that point, yet the compiler tells me that this is not the case:
error[E0381]: use of possibly-uninitialized variable: `method`
Ok(HttpRequest { s_addr: s_addr, method, scheme: RequestScheme::HTTP })
^^^^^^ use of possibly-uninitialized `method`
pub fn parse(request_string: String, s_addr: SocketAddr) -> Result<HttpRequest, HttpError> {
let mut method: HttpMethod;
for element in request_string.split(" ") {
method = match element {
"GET" => HttpMethod::GET,
_ => {
eprintln!("Couldn't parse word : {}", element);
return Err(HttpError::ParseError);
},
}
}
Ok(HttpRequest { s_addr: s_addr, method, scheme: RequestScheme::HTTP })
}
As #mkrieger1 points out:
What if the for loop has 0 iterations?
String's split function never returns an empty iterator, so consider using an Option<T>, then unwrapping the value.
let mut method: Option<HttpMethod> = None;
for element in request_string.split(" ") {
if element != "GET" {
eprintln!("Couldn't parse word : {}", element);
return Err(HttpError::ParseError);
}
method.insert(HttpMethod::Get);
}
Ok(HttpRequest { s_addr, method: method.unwrap(), scheme: RequestScheme::HTTP})
Or, in your case you can just avoid a variable all together.
for element in request_string.split(" ") {
if element != "GET" {
eprintln!("Couldn't parse word : {}", element);
return Err(HttpError::ParseError);
}
}
Ok(HttpRequest { s_addr, method: HttpMethod::Get, scheme: RequestScheme::HTTP})

Hook instagram apk using Frida

I wanted to hook some functions from instagram apk using frida, decompiled the apk with
jadx/JEB, one of the functions I wanted to hook was in this:
public static void A00(HGf arg8, I1Y arg9) {
arg8.A0P();
Boolean v0 = arg9.A0v;
if(v0 != null) {
arg8.A0l("about_your_account_bloks_entrypoint_enabled", v0.booleanValue());
}
//some other code here
}
Tried to hook the function with this frida script:
try {
//
let I1X = Java.use("X.I1X")
console.log("this is instance: ", I1X)
console.log(
"these are the methods:: ",
Java.use("X.I1X").class.getDeclaredMethods()
)
I1X.A00.overload().implemention = function (HGf, I1Y) {
console.log("A0l is called")
let ret = this.A0l(str, z)
console.log("A0l ret value is " + ret)
}
} catch (e) {
console.log("failed!" + e)
}
})
this script outputs:
this is instance: <class: X.I1X>
these are the methods::
failed!TypeError: not a function
apparently the A00 here is not a function, so back to jadx in the compiled code there is another class with the same name within same package but consisting of some other code, here it is:
/* renamed from: X.I1x reason: case insensitive filesystem */
/* loaded from: classes7.dex */
public final class C39227I1x {
public C39229I1z A00 = null;
}
apparently Frida is hooking this variable instance A00 In my opinion that is why
it is returning not a function here.
So my question, how can I hook like this situation?
Edit:
the two classes are somewhat different in jadx.

Handle exception for Scala Async and Future variable, error accessing variable name outside try block

#scala.throws[scala.Exception]
def processQuery(searchQuery : scala.Predef.String) : scala.concurrent.Future[io.circe.Json] = { /* compiled code */ }
How do I declare the searchResult variable at line 3 so that it can be initailized inside the try block and can be processed if it's successful after and outside the try block. Or, is there any other way to handle the exception? The file containing processQuery function is not editable to me, it's read-only.
def index = Action.async{ implicit request =>
val query = request.body.asText.get
var searchResult : scala.concurrent.Future[io.circe.Json] = Future[io.circe.Json] //line 3
var jsonVal = ""
try {
searchResult = search.processQuery(query)
} catch {
case e :Throwable => jsonVal = e.getMessage
}
searchResult onSuccess ({
case result => jsonVal = result.toString()
})
searchResult.map{ result =>
Ok(Json.parse(jsonVal))
}
}
if declared in the way it has been declared it's showing compilation error
Would using the recover method help you? I also suggest to avoid var and use a more functional approach if possible. In my world (and play Json library), I would hope to get to something like:
def index = Action.async { implicit request =>
processQuery(request.body.asText.get).map { json =>
Ok(Json.obj("success" -> true, "result" -> json))
}.recover {
case e: Throwable => Ok(Json.obj("success" -> false, "message" -> e.getMessage))
}
}
I guess it may be necessary to put the code in another whole try catch:
try {
processQuery....
...
} catch {
...
}
I have here a way to validate on the incoming JSON and fold on the result of the validation:
def returnToNormalPowerPlant(id: Int) = Action.async(parse.tolerantJson) { request =>
request.body.validate[ReturnToNormalCommand].fold(
errors => {
Future.successful{
BadRequest(
Json.obj("status" -> "error", "message" -> JsError.toJson(errors))
)
}
},
returnToNormalCommand => {
actorFor(id) flatMap {
case None =>
Future.successful {
NotFound(s"HTTP 404 :: PowerPlant with ID $id not found")
}
case Some(actorRef) =>
sendCommand(actorRef, id, returnToNormalCommand)
}
}
)
}

Writing an if statement in Ceylon

I have tasked myself with writing a file writer in Ceylon and in the process of doing so I have been hit by the crushing difficulty of writing an if statement in Ceylon, that will be allowed to pass when facing the mighty Wizard of Type Correctness on the narrow Bridge of Compilation in the far far land of Ceylon:
The error I get is "Error:(10, 1) ceylon: incorrect syntax: missing EOF at 'if'"
This is my if statement (the first line is line 10):
if (is Nil fileResource || is File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
EDIT:
this is my if statement updated according to Bastien Jansens recommendation. The error, however, remains the same :(
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
This is the full source code of my application:
import ceylon.http.server { newServer, startsWith, Endpoint, Request, Response }
import ceylon.io { SocketAddress }
import ceylon.file { Path, parsePath, File, createFileIfNil, FResource = Resource }
// let's create a file with "hello world":
Path folderPath = parsePath("""C:\Users\Jon\Auchitect\POSTtoFile""");
Path filePath = folderPath.childPath("BPset.json.txt");
FResource fileResource = filePath.resource;
if (is Nil|File fileResource) {
File file = createFileIfNil(fileResource);
value writer = file.Overwriter();
//writer.writeLine("Hello, World!");
} else {
print("hello");
}
shared void runServer() {
//create a HTTP server
value server = newServer {
//an endpoint, on the path /hello
Endpoint {
path = startsWith("/postBPset");
//handle requests to this path
function service(Request request, Response response) {
variable String logString;
variable String jsonString;
variable String contentType;
contentType = request.contentType
else "(not specified)";
logString = "Received " + request.method.string + " request \n"
+ "Content type: " + contentType + "\n"
+ "Request method: " + request.method.string + "\n";
jsonString = request.read();
print(logString);
return response;
}
}
};
//start the server on port 8080
server.start(SocketAddress("127.0.0.1",8080));
}
The || operator cannot be used in conjunction with if (is ...), the correct way to achieve what you want is using a union type:
if (is Nil|File fileResource) {
...
}
|| would be valid in the following syntax, but you would lose the refinement (it would only be a boolean expression, not a type refinement):
if (fileResource is Nil || fileResource is File ) {
...
}
The || operator only works on Boolean expressions (which foo is Bar is), whereas is Bar foo is a Boolean condition, which is a different construct. The same applies for exists conditions vs exists operators.
EDIT: oh, and of course you need to put that if statement in a function, toplevel elements can only be declarations (classes, functions or values, if statements are not allowed).

How to hide library source code in Google way?

For instance, I have a library and I would like to protect the source code to being viewed. The first method that comes to mind is to create public wrappers for private functions like the following
function executeMyCoolFunction(param1, param2, param3) {
return executeMyCoolFunction_(param1, param2, param3);
}
Only public part of the code will be visible in this way. It is fine, but all Google Service functions look like function abs() {/* */}. I am curious, is there an approach to hide library source code like Google does?
Edit 00: Do not "hide" a library code by using another library, i.e. the LibA with known project key uses the LibB with unknown project key. The public functions code of LibB is possible to get and even execute them. The code is
function exploreLib_(lib, libName) {
if (libName == null) {
for (var name in this) {
if (this[name] == lib) {
libName = name;
}
}
}
var res = [];
for (var entity in lib) {
var obj = lib[entity];
var code;
if (obj["toSource"] != null) {
code = obj.toSource();
}
else if (obj["toString"] != null) {
code = obj.toString();
}
else {
var nextLibCode = exploreLib_(obj, libName + "." + entity);
res = res.concat(nextLibCode);
}
if (code != null) {
res.push({ libraryName: libName, functionCode: code });
}
}
return res;
}
function explorerLibPublicFunctionsCode() {
var lstPublicFunctions = exploreLib_(LibA);
var password = LibA.LibB.getPassword();
}
I don't know what google does, but you could do something like this (not tested! just an idea):
function declarations:
var myApp = {
foo: function { /**/ },
bar: function { /**/ }
};
and then, in another place, an anonymous function writes foo() and bar():
(function(a) {
a['\u0066\u006F\u006F'] = function(){
// here code for foo
};
a['\u0062\u0061\u0072'] = function(){
// here code for bar
};
})(myApp);
You can pack or minify to obfuscate even more.
Edit: changed my answer to reflect the fact that an exception's stacktrace will contain the library project key.
In this example, MyLibraryB is a library included by MyLibraryA. Both are shared publicly to view (access controls) but only MyLibraryA's project key is made known. It appears it would be very difficult for an attacker to see the code in MyLibraryB:
//this function is in your MyLibraryA, and you share its project key
function executeMyCoolFunction(param1, param2, param3) {
for (var i = 0; i < 1000000; i++) {
debugger; //forces a breakpoint that the IDE cannot? step over
}
//... your code goes here
//don't share MyLibraryB project key
MyLibraryB.doSomething(args...);
}
but as per the #megabyte1024's comments, if you were to cause an exception in MyLibraryB.doSomething(), the stacktrace would contain the project key to MyLibraryB.