C Program for Form Processing - html

I have no idea how to achieve this, but I have a HTML form, with several different elements in it.
For testing, right now, all I would like to do is write a piece of C code that will take anything that is submitted and print this out on the screen.
I can write my own parsing code - I just cannot work out how to get the form data to print directly to the screen.
Thanks in advance.

Assuming you have a web server configured to allow you to do CGI, your HTML form needs to be written to either GET or POST the form data to the CGI script. You can then implement a CGI script in C to process the form data.
As a starter CGI script, you can simply echo whatever is provided in the input as the output.
int main () {
int c;
puts("Content-type: text/plain");
puts("Connection: close");
puts("");
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}

You need an HTTP server, with settings that let you run CGI scripts. This could be a server installed locally in your computer, using e.g. XAMPP, or it could be a web server that you have access to.
Then you will write a C program that uses CGI conventions for I/O. As output, it should write a complete HTML document with accompanying HTTP headers. You will need to compile the program into an executable, upload the executable on the HTTP server, and put the URL of the executable into the action attribute of the form.
For details etc., check out Getting Started with CGI Programming in C.

Here's an example of a form echoing script in C, which you might find helpful in terms of responding to both GET and POST methods, parsing the query string or input, etc:
http://www.paulgriffiths.net/program/c/formecho.php

Related

PUG with javascript

If I have the following piece of code
script.
function getProductParams(params) {
return JSON.parse(localStorage.getItem(params));
}
each product in products
-var getVariable = getProductParams("ids");
This piece of code doesn't work, I'm guessing that - is on server side, while script. is on clients?
How can I access a variable from localStorage in pug and use it for comparison with variables received from server.
I want to make something like this
script.
function getProductParams(params) {
return JSON.parse(localStorage.getItem(params));
}
each product in products
-var getVariable = getProductParams("ids");
-if (getVariable.includes(#{product._id}) {
// create the element in html
-} else {
- // call next product and compare if we have it
-}
The simple answer is that you can't do this. LocalStorage is exactly that - local. Your server can't directly access it unless you explicitly pass it back using some other format/method.
What your server can access easily is the cookie. If you store the data in the cookie and use cookie-parser then you can handle this list quickly. This use case is exactly why cookies exist.
Another option would be to pass the data to the server in the body of a POST request, but your question doesn't provide a lot of information as to what exactly you're doing and if this is an option or not.
It would also be much easier for you to accomplish all of the sorting and filtering in your route instead of the pug template. That way you have full request to the cookie, request body, etc. directly and you don't have to pass that down to the template too.
Then, when your template gets the list it's a really simple matter to render it:
each product in products
//create the element in html

Extracting the outputs/results from an executed .pexe file

My goal is to convert a C++ program in to a .pexe file in order to execute it later on a remote computer. The .pexe file will contain some mathematical formulas or functions to be calculated on a remote computer, so I’ll be basically using the computational power of the remote computer. For all this I’ll be using the nacl_sdk with the Pepper library and I will be grateful if someone could clarify some things for me:
Is it possible to save the outputs of the executed .pexe file on the remote computer in to a file, if it’s possible then how? Which file formats are supported?
Is it possible to send the outputs of the executed .pexe file on the remote computer automatically to the host computer, if it’s possible then how?
Do I have to install anything for that to work on the remote computer?
Any suggestion will be appreciated.
From what I've tried it seems like you can't capture the stuff that your pexe writes to stdout - it just goes to the stdout of the browser (it took me hours to realize that it does go somewhere - I followed a bad tutorial that had me believe the pexes stdout was going to be posted to the javascript side and was wondering why it "did nothing").
I currently work on porting my stuff to .pexe also, and it turned out to be quite simple, but that has to do with the way I write my programs:
I write my (C++) programs such that all code-parts read inputs only from an std::istream object and write their outputs to some std::ostream object. Then I just pass std::cin and std::cout to the top-level call and can use the program interactively in the shell. But then I can easily swap out the top-level call to use an std::ifstream and std::ofstream to use the program for batch-processing (without pipes from cat and redirecting to files, which can be troublesome under some circumstances).
Since I write my programs like that, I can just implement the message handler like
class foo : public pp::Instance {
... ctor, dtor,...
virtual void HandleMessage(const pp::Var& msg) override {
std::stringstream i, o;
i << msg.AsString();
toplevelCall(i,o);
PostMessage(o.str());
}
};
so the data I get from the browser is put into a stringstream, which the rest of the code can use for inputs. It gets another stringstream where the rest of the code can write its outputs to. And then I just send that output back to the browser. (Downside is you have to wait for the program to finish before you get to see the result - you could derive a class from ostream and have the << operator post to the browser directly... nacl should come with a class that does that - I don't know if it actually does...)
On the html/js side, you can then have a textarea and a pre (which I like to call stdin and stdout ;-) ) and a button which posts the content of the textarea to the pexe - And have an eventhandler that writes the messages from the pexe to the pre like this
<embed id='pnacl' type='application/x-pnacl' src='manifest.nmf' width='0' height='0'/>
<textarea id="stdin">Type your input here...</textarea>
<pre id='stdout' width='80' height='25'></pre>
<script>
var pnacl = document.getElementById('pnacl');
var stdout = document.getElementById('stdout');
var stdin = document.getElementById('stdin');
pnacl.addEventListener('message', function(ev){stdout.textContent += ev.data;});
</script>
<button onclick="pnacl.postMessage(stdin.value);">Submit</button>
Congratulations! Your program now runs in the browser!
I am not through with porting my compilers, but it seems like this would even work for stuff that uses flex & bison (you only have to copy FlexLexer.h to the include directory of the pnacl sdk and ignore the warnings about the "register" storage location specifier :-)
Are you using the .pexe in a browser? That's the usual case.
I recommend using nacl_io to emulate POSIX in the browser (also look at file_io. This will allow you to save files locally, retrieve them, in any format you fancy.
To send the output use the browser's usual capabilities such as XMLHttpRequest. You need PNaCl to talk to JavaScript for this, you may want to look at some of the examples.
A regular web server will do, it really depends on what you're doing.

Understanding JSON-RPC in Perl

I am trying to understand the concept of JSON RPC and it's Perl implementation. Though I can fin d a lot of examples for Python/Java, I find surprisingly little or no examples for it in Perl.
I am following this example but am not sure it is complete. The example I had in mind was to add 2 integers. Now I have a very basic HTML page set up, like so:
<html>
<body>
<input type="text" name="num1"><br>
<input type="text" name="num2"><br>
<button>Add</button>
</body>
</html>
Next, based on the example above, I have 3 files:
test1.pl
# Daemon version
use JSON::RPC::Server::Daemon;
# see documentation at:
# https://metacpan.org/pod/distribution/JSON-RPC/lib/JSON/RPC/Legacy.pm
my $server = JSON::RPC::Server::Daemon->new(LocalPort => 8080);
$server -> dispatch({'/test' => 'myApp'});
$server -> handle();
test2.pl
#!/usr/bin/perl
use JSON::RPC::Client;
my $client = new JSON::RPC::Client;
my $uri = 'http://localhost:8080/test';
my $obj = {
method => 'sum', # or 'MyApp.sum'
params => [10, 20],
};
my $res = $client->call( $uri, $obj );
if($res){
if ($res->is_error) {
print "Error : ", $res->error_message;
} else {
print $res->result;
}
} else {
print $client->status_line;
}
myApp.pl
package myApp;
#optionally, you can also
use base qw(JSON::RPC::Procedure); # for :Public and :Private attributes
sub sum : Public(a:num, b:num) {
my ($s, $obj) = #_;
return $obj->{a} + $obj->{b};
}
1;
While I understand what these files individually do, I am at a complete loss when it comes to combining them and making them work together.
My questions are as follows:
Does the button in the HTML page come inside a tag (like we would normally do in a CGI-based program)? If yes, what file does that call? If no, then how do I pass the values to be added?
What is the order of execution of the 3 Perl files? Which one calls which one? How is the flow of execution?
When I tried to run the perl files from the CLI, i.e using $./test2.pl, I got the following error: Error 301 Moved Permanently. What moved permanently? which file was it trying to access? I tried running the files from withing /var/www/html and /var/www/html/test.
Some help in understanding the nuances of this would really be appreciated. Thanks in advance
Does the button in the HTML page come inside a tag (like we would
*normally do in a CGI-based program)? If yes, what file does that call?*
If no, then how do I pass the values to be added?
HTML has nothing at all to do with JSON-RPC. While the RPC call is done via an HTTP POST request, if you're doing that from the browser, you'll need to use XMLHttpRequest (i.e: AJAX). Unlink an HTML form post the Content-encoding: header will need to be something specific to JSON-RPC (e.g: application/json or similar), and you'll need to encode your form data via JSON.stringify and correctly construct the JSON-RPC "envelope", including the id, jsonrpc, method and params properties.
Rather than doing this by hand you might use a purpose-build JSON-RPC JavaScript client like the jQuery-JSONRP plugin (there are many others) -- although the protocol is so simple that implementations usually are less than 20 lines of code.
From the jQuery-RPC documentation, you'd set up the connection like this:
$.jsonRPC.setup({
endPoint: '/ENDPOINT-ROUTE-GOES-HERE'
});
and you'd call the server-side method like this:
$.jsonRPC.request('sum', {
params: [YOURNUMBERINPUTELEMENT1.value, YOURNUMBERINPUT2.value],
success: function(result) {
/* Do something with the result here */
},
error: function(result) {
/* Result is an RPC 2.0 compatible response object */
}
});
What is the order of execution of the 3 Perl files? Which one calls
*which one? How is the flow of execution?*
You'll likely only need test2.pl for testing. It's an example implementation of a JSON-RPC client. You likely want your client to run in your web-browser (as described above). The client JavaScript will make an HTTP POST request to wherever test1.pl is serving content. (e.g: http://localhost:8080).
Or, if you want to keep your code as HTML<-->CGI, then you'll need to make JSON-RPC client calls from within your Perl CGI server-side code (which seems silly if it's on the same machine).
When test1.pl calls dispatch, the MyApp module will be loaded.
Then, when test1.pl calls handle, the sum function in the MyApp package will be called.
The JSON::RPC::Server module takes care of marshalling from JSON-RPC to perl datastructures and back again around the call to handle. die()ing in sum should result in a JSON-RPC exception being transmitted to the calling client, rather than death of the test1.pl script.
When I tried to run the perl files from the CLI, i.e using
*$./test2.pl, I got the following error: Error 301 Moved Permanently.*
What moved permanently? which file was it trying to access? I tried
*running the files from withing /var/www/html and /var/www/html/test.*
This largely depends the configuration of your machine. There's nothing obvious (in your code) to suggest that a 301 Moved Permanently would be issued in response to a valid JSON-RPC request.

Get JSON from Google Apps Script URL via Erlang

Good Evening!
I've been looking into the possibility of using GAS(Google Apps Script) to host a small bit of javascript that lets me use the new Google finance apps api. The intention being that I'll be using the stock information for a project which involves the use of stock data. I know that there are a few ways to get stock information from Google, but the data that the finanace app returns is more in-line with other sources we are using. (One constraint on this project is that we have multiple sources).
I've written the javascript and I can call a httpc:request to the URL for the script given to me from Google. In the browser the JS returns the json object as I want it, however when the call is made from Erlang I'm getting it in a list of ascii. From checking the values it appears to be a document starting like:
Below is the javascript and the url to see the json:
https://script.google.com/macros/s/AKfycbzEvuuQl4jkrbPCz7hf9Zv4nvIOzqAkBxL1ixslLBxmSEhksQM/exec
function doGet() {
var stock = FinanceApp.getStockInfo('LON:TSCO');
return ContentService.createTextOutput(JSON.stringify(stock))
.setMimeType(ContentService.MimeType.JSON);
}
For the erlang, it's a simple request but I've not been doing erlang long, so perhaps I've messed something up here (The URL being the one mentioned above). I've got crypto / ssl / inets when I'm testing this on the command line.
{ok, {Version, Headers, Body}} = httpc:request(get, URL, []}, [], []).
I think it's also worth mentioning that when i curl it from Cygwin, I get a massive load of HTML also, I've included it below, but if you see it you'll thank me for not posting it in here! http://pastebin.com/UtJHXjRm
I've been updating the script as I go with the new versions but I'm at a bit of a loss as to why it's not returning correctly.
If anyone can give me any pointers I'd be very grateful! I get the feeling that it's not intended to be used this way, perhaps only within other Google products and such.
Cheers!
It would be necessary to review how are you deploying the Web App, specifically the Who has access to the app, to access without authentication should be configured as shown in the image:
See Deploying Your Script as a Web App from the documentation.
In my test, by running:
curl -L https://script.google.com/macros/s/************/exec
Get the following result:
{
"priceopen":358,
"change":2.199981689453125,
"high52":388.04998779296875,
"tradetime":"2013-10-11T15:35:18.000Z",
"currency":"GBX",
"timezone":"Europe/London",
"low52":307,
"quote":357.8999938964844,
"name":"Tesco PLC",
"exchange":"LON",
"marketcap":28929273763,
"symbol":"TSCO",
"volumedelay":0,
"shares":8083060703,
"pe":23.4719295501709,
"eps":0.15248000621795654,
"price":357.8999938964844,
"has_stock_data":true,
"volumeavg":14196534,
"volume":8885809,
"changepct":0.6184935569763184,
"high":359.5,
"datadelay":0,
"low":355.8999938964844,
"closeyest":355.70001220703125
}
Possibly your GET is not following the REDIRECT that happens when you use contentService. Look at the html returned there is a redirect in there.

Last Modified Date of a file on a web site

Is there a way to get the Last-Modified-Date of a file on a Web Site?
i.e. Here is an example file I have out there:
http://www.ymcadetroit.org/atf/cf/%7B2101903E-A11A-4532-A64D-9D823368A605%7D/Birmingham_Youth_Sports_Parent_Manual.pdf
Go to the website you want to know about, wait for it to fully load, then go to the address bar and write this:
javascript:alert(document.lastModified)
You'll get a popup that says when it was last modified.
The HTTP intends the Last-Modified header field to declare the last modification date. But the server needs to know that date.
On static files whose content is sent directly to the client and not interpreted otherwise by the server (e.g. .html, .css, .js) it uses the last modified date of that file. But on files that generated content dynamically (PHP, Python, etc.) the script needs to specify that information itself. But unfortunatly many scripts don’t to that.
So if a Last-Modified header field is present, you can use that information. But if not, you cannot determin the last modification date.
Here is some C# code to do it:
public DateTime GetLastModifyTime(string url)
{
WebRequest request = WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
request.Method = "HEAD";
using (WebResponse response = request.GetResponse())
{
string lastModifyString = response.Headers.Get("Last-Modified");
DateTime remoteTime;
if (DateTime.TryParse(lastModifyString, out remoteTime))
{
return remoteTime;
}
return DateTime.MinValue;
}
}
I realize this question is 4 years old, but a search of the web proved that satisfactory answers remain rare. Peter's answer is part of the solution. When I had the same problem to solve, that got me started. But the rest of the solution...
As he said, the web server must be configured to send the last-modified date ... so how do you configure the web server?
Assuming you have the necessary level of control, you first need to enable server side includes. There are several ways to do this - one of which is the "xbithack". A good reference is http://httpd.apache.org/docs/current/howto/ssi.html.
Assuming you've done this, you need to set the execute bit on any html file that needs to have server-side includes parsed. This can be done at the command line of a UNIX-like system: chmod u+x file.html or on the Mac using get-info (command-I) on the file.
This leaves the snippet to actually put in your file, which looks like this:
This document last modified <!--#flastmod file="index.html" -->
Since I found many, many recommendations that didn't include this, and simply used the javascript document.lastModified, I suspect that some servers give you what you want with the javascript version, whereas some (including the one hosting our stuff) don't.
To obtain the last modified date from client side, you can access the HTML DOM using the lastModified property using JavaScript.
The lastModified property grabs the information from the head portion sent with all web requests. The value can be manually set by developers on the web-server side of things so it may not reflect the actual last modified date of the file responsible for delivering the content.
Example
<!DOCTYPE html>
<html>
<body>
<b>document.lastModified : </b>
<script>document.write( document.lastModified );</script>
</body>
</html>
The specific command in JavaScript that retrieves this is document.lastModified and can easily be converted into a Date object as follows :
var x = new Date(document.lastModified);
More information can be found on the site I used as a reference w3 schools : HTML DOM lastModified Property
I believe the web server must be configured to send the last-modified date in an HTTP-header, this is certainly one way. Check out section 14.29 Last-Modified of this document:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
You can do the following to get Last-Modified:
https://superuser.com/a/991895
Using curl:
curl -s -v -X HEAD http://foo.com/bar/baz.pdf 2>&1 | grep '^< Last-Modified:'
Using wget:
wget --server-response --spider http://example.com/bar/example.pdf 2>&1 | grep -i Last-Modified
With just plain HTML, no you cannot.
You can with PHP, or ASP, or any other server side language.
I'm not an expert in headers, but believe you are looking for this:
There is a way to check the date when a file was modified:
View HTTP headers in Google Chrome?
Check in there (Chrome's Developer Tools / Network / Selected File / Headers) the "If-Modified-Since" variable.
Until now this has helped me to achieve what you are asking, get a file's modification date.
In php:
print getlastmod();
print gmdate('D, d M Y H:i:s', getlastmod());