How can I make an AJAX server side script in C? - c

I am looking into AJAX for the first time and I would like to know if it's possible to make the requests from a server side CGI application written in C?
Will the C application just use printf for the data, similar to this .asp example?

If I were you, I would stay away from C for server-side stuff. There are so many other languages that are better suited for this, but if you insist, you could use a library like cgic. Basically, you would just use the CGI handler from a server like Apache, but please, PLEASE use something other than C. It's very dangerous in the wrong hands, especially via CGI.
Use something like PHP or Perl to keep yourself sane. PHP is perfect for someone just starting out, and you won't have to futz around with compilation and making your CGI handler work/be secure.

ASP does some magic, such as outputting the appropriate response headers, but other than that it really is that simple. The server-side of AJAX is just responding to requests. Output the right data in the expected format and you're done. Stick with REST principles and this becomes easy.

You can do scripting using C.
Take a look at http://bellard.org/tcc/ - this is a small C99 compiler for Windows and UNIX.
It has a unique feature: "-run" option. With this option, tinycc compiles the code into memory and executes it without creating an intermediate binary. Thus all you need to do is to create your CGI files like this:
#!path-to-tinycc-executable -run
// your C code goes below
....
However, I have to agree with previous commenters that C is not great for server side CGI.

I am looking into AJAX for the first time and I would like to know if it's possible to make the requests from a server side CGI application written in C?
I'll hop on the bandwagon, and say that it's usually easier to just use another language. However, I also understand that sometimes you have to use C - i.e., for embedded servers with limited resources. If that's the strongly suggest you use cgic, or heck, maybe even a framework like klone. I'm a bit biased towards the latter, though. It provides a nice interface to getting request objects, almost like the scripting variety of frameworks.

Related

is there a way to integrate a c compiler in my angular/ionic app?

so i am working on this project that lets user write and compile c/c++ code on their mobile, but i am unable to find a way to compile the written c code to generate output.I am basically using angular with ionic framework for mobile app
i read about webassembly but it works by precompiling code and cannot be used under this scenario as per my understanding, i also read about ndk which could work in theory but is there any better way ? I also searched through github but could not find anything useful
If I understand your question correctly, you want to make something like this. Going off of that assumption, you have two ways to go about this problem:
1. Client-side compilation:
In order to do this, you'll have to get your hands on a WASM binary of a C compiler, that supports WASM output. AFAIK no one is distributing WASM binaries (yet), so you'll have to compile a WASM compiler with itself, and if you have to, you'll have to compile the compiler itself with another compiler. This might involve changing up the source code in the following ways:
Change up the main function take input from stdin and output the binary to stdout, so that JavaScript (Angluar) can access it.
Create an interface function, for example char* js_compile(char* source), which, as you can probably see, will take the source code, execute main with the appropriate arguments, and return the binary.
This method will be the best architecturally, since you won't need to host a server, and the client will be responsible for compiling his own code. However, as you can probably see, this is quite a difficult method, and doing it will probably take several years off of your life.
2. Server-side compilation:
With this method, you'll create a backend (it can be in any language/framework, but I prefer NodeJS/ExpressJS). Then, the backend will expose a HTTP post route (for example, /compile), that will read the body as source. Then, the server will run the code trough a compiler, installed on the server. Finally, the compiler will either respond with the WASM bytecode, the result of the compilation, or with the errors, that the compilers has raised during the compilation.
This of course is the easiest method, but you'll need to host (and probably pay) for a server. If you're OK with that, this is the method you should use.
3. Client-side C interpreter
Here, you'll need to get your hands on a C interpreter, written in JavaScript. Unfortunately, AFAIK, there aren't any COMPLETE C interpreters, but if you're ok with that, you can take a look at this thread. Another solution would be to write an interpreter yourself, but good luck with that.
TL; DR: Pretty complicated, either use a modified WASM compiler on the client, compiler on the server, or interpret the code.
P.S.: If you want me to elaborate on anything, make sure to comment on this post

What language should we use to let people extend our terminal/sniffer program?

We have a very versatile terminal/sniffer application which can do all sorts of things with TCP, UDP and serial connections.
We are looking to make it extensible -- i.e, allow people to write their own protocol parsers, highlighters, etc.
We created a C-like language for extending the product, and then discovered that for some coders, this presents a steep learning curve.
We are now pondering the question: Should we stick to C or go with something like Ruby or Lua?
C is beautiful for low-level stuff (like parsing binary data), because it supports pointers. But for exactly that reason, it can be tough to learn.
Ruby (etc) are easy to learn, but don't have pointers, so anything that has to do with parsing binary data gets ugly very fast.
What do you think? For extending a product that parses binary data -- Ruby/Lua or C/C++?
Would be great if you could give some background when you respond -- especially if you've done something similar.
Wireshark, the "world's foremost network protocol analyzer", is also a packet sniffer/analyzer, formerly also called Ethereal. It uses Lua to enable writing custom dissectors and taps, see the manual.
However, note that I have not used it, so I cannot tell how nice/effective/easy to learn the API is.
Like TCL, Lua was designed to be tightly integrated with an application. Personally, I find Lua's syntax and idioms to be much easier to deal with than TCL.
Lua is easy to integrate with an existing system, and easy to extend. It is also fairly easy to create safe sandboxes in which user-supplied code can run without full access to the innards of your product.
If you have an API written does it make a difference? The person using the C-like API would only have to understand the difference between passing by value or reference.
Your core does one thing very good, so fine. Let it be that way. I think you should create an API based on std in/out, just like the way of good unix design. Then anyone can extend it in any language of choice.
Tcl was designed with the goal to allow scripting for C programs, so it would be much easier to implement.
http://en.wikipedia.org/wiki/Tcl#Interfacing_with_other_languages
I second Johan's idea. Although in past when I had to do something like this I stuck to
C language APIs and people were restricted to use C language only. But now I look at it,
I realize that it would have been more efficient if we would have done the way Johan describes
PS: And by coincidence it was a protocol testing app using packet sniffer
perl, sed, awk, lex, antler, ... These are languages I'm somewhat familiar with that I'd like to write something like this in. It depends on the data flow, though.
It's really hard to say what the correct thing to use is. Something that I don't think anyone else has mentioned is to keep in mind that the scripts will have bugs. It's very easy to design something like this in such a way that bugs in the scripts (especially run time errors) either just show up a "error in script" or kill the whole system.
You should keep that the scripts should be unit testable and that failures should be reproducible.
I don't think it matters what you do as long as you do one thing, drop the in-house language. It sounds like you choose to make C into a scripting language. One issue I see with this is it will look familiar to C programmers, but not be the same. I can't imagine you have mimicked the semantics of C that would make existing C programmers comfortable. And as you have mentioned, others will find it hard to learn.
The company I am working at have developed their own language. It uses XML for structure so parsing is easy. The language grows "as needed." Meaning if a feature is missing then it will be added. I'm pretty sure it went from an XML database to something that needed control flow. But my point is that if you aren't thinking about building it as a language, then you'll be limiting what users can do with it unintentionally.
Personally I've been looking at how I can get the company to start taking advantage of Lua. And specifically Lua for several reasons. Lua was developed as an extension language that was general purpose. It easily interfaces with the language, including Python and Ruby. It is small and simple for use by non-programmers (not really needed in your case). It is simple enough to replace XML, INI... for configuration settings and powerful enough to replace the need for another programming language.
http://www.lua.org/spe.html

How can I best deploy a web application written in C?

Say I have fancy new algorithm written in C,
int addone(int a) {
return a + 1;
}
And I want to deploy as a web application, for example at
http://example.com/addone?a=5
which responds with,
Content-Type: text/plain
6
What is the best way to host something like this? I have an existing setup using Python mod_wsgi on Apache2, and for testing I've just built a binary from C and call as a subprocess using Python's os.popen2.
I want this to be very fast and not waste overhead (ie I don't need this other Python stuff at all). I can dedicate the whole server to it, re-compile anything needed, etc.
I'm thinking about looking into Apache C modules. Is that useful? Or I may build SWIG wrappers to call directly from Python, but again that seems wasteful if I'm not using Python at all. Any tips?
The easiest way should be to write this program as a CGI app (http://en.wikipedia.org/wiki/.cgi). It would run with any webserver that supports the Common Gateway Interface.
The output format needs to follow the CGI rules.
If you want to take full advantage of the web server capabilities then you can write an Apache module in C. That needs a bit more preparation but gives you full control.
Maybe this tiny dynamic webserver in C to be used with C language can help you.. it should be easy to use and self-contained.
Probably the fastest solution you can adopt according to the benchmarks shown on their homepage!
This article from yesterday has a good discussion on why not to use C as a web framework. I think an easy solution for you would be to use ctypes, it's certainly faster than starting a subprocess. You should make sure that your method is thread safe and that you check your input argument.
from ctypes import *
libcompute = CDLL("libcompute.so")
libcompute.addone(int(a))
I'm not convinced that you're existing general approach might not be the best one. I'm not saying that Apache/Python is necessarily the correct one but there is something compelling about separating the concerns in your architecture being composed of highly focused elements that are specialists in their functions within the overall system.
Having your C-based algorithm server being decoupled from the HTTP server may give you access to things like HTTP scalability and caching facilities that might otherwise have to be in-engineered (or reinvented) within your algorithm component if things are too tightly coupled.
I don't think performance concerns in of themselves are always the best or only reasons when designing an architecture. For example the a YAWS deployment with a C-based driver could be a very performant option.
I have just setup a web service using libmicrohttpd and have had amazing results. On a quad core I've been handling 20400 requests a second and the CPU is running only at 58%. This is probably going to be deployed on a server with 8 cores, so I'm expecting much better results. A very simple C service will be even faster!
I have tried GWAN, it is very good, but it's closed, and doesn't play well with virtual environments. I will give #Gil kudos being good at supporting it here though. We just had a few issues and found LibMicroHttpd works better for our needs.
If you go here, you may need to update your openssl if you're using CentOs from axivo
rpm -ivh --nosignature http://rpm.axivo.com/redhat/axivo-release-6-1.noarch.rpm
yum --disablerepo=* --enablerepo=axivo update openssl-devel
You can try Duda I/O, it only requires a Linux host: http://duda.io

Coding a website in C?

I was just reading the http://www.meebo.com/ About Us page, and read this line :
"plus, we're one of the few still around using C!"
Considering that meebo is an online chat client, how do they work with C? How can they use C for the backend? How does it interact with the frontend? For example, let's say a user creates a new account, and new directory is to be made, how does the information go from the front end to the back end?
I'm sorry if it's an invalid question.
Thank you
Edit 1: The Intro Tutorial to CGI was great. Any good books I can pick up from my library regarding this?
Thanks a lot for the quick response guys!
I don't know how meebo does it, but given that it's chat software they probably have a custom server written in C to handle the actual message traffic.
However, Apache and most other HTTP servers have always been able to call C programs just as they can call PHP, CGI and other languages for certain requests. Some websites are even written in Lisp.
The backend has to be compiled each time, unlike an interpreted language, but that happens at rollout and is part of the build/production scripts.
The permissions given and user account that the C program runs under must be carefully chosen, and of course a C website suffers from the same issues any other C program can fall for, such as buffer overrun, segfault, stackoverflow, etc. As long as you run it with reduced permissions you are better protected, and it's no worse than any other language/platform/architecture.
For servers, however, it's still used widely - the gold standard, I suppose. You can find plenty of servers written in Java, C++, and every other language, but C just seems to stick around.
-Adam
I've rolled non-blocking HTTP 1.1 servers in as little as 50 lines of code (sparse) or a few hundred (better), up to about 5k (safe). The servers would load dynamic shared objects as modules to handle specific kinds of requests.
The parent code would handle connection tracking, keep alives, GET/POST/HEAD requests and feed them off to handlers that were loaded on start up. I did this when I was working with VERY little elbow room on embedded devices that had to have some kind of web based control panel .. specifically a device that controlled power outlets.
The entry point to each DSO was defined by the URL and method used (i.e. /foo behaved differently depending on the type of request it was serving).
My little server did quite well, could handle about 150 clients without forks or threads and even had a nice little template system so the UI folks could modify pages without needing hand-holding.
I would most decidedly not use this kind of setup on any kind of production site, even your basic hello world home page with a guest book.
Now, if all I have to do is listen on port 80/443, accept requests with a small POST payload, sanitize them and forward them along to other clients ... its a little different.But that's a task specific server that pretends to be a web server, its not using C to generate dynamic pages.
Meebo uses a custom Lighttpd module called mod_meebo. It doesn't fully answer your question, but I thought you might be interested.
A lot of server-side programs can be done in C, not to mention CGI programming. They could also be Using C with MySQL, which is very possible. But without access to their source code, we have no way of knowing just how much C they are using.
Claiming that they are "one of the few around still using C" was probably just a joke. With stats like this at least I would hope so.
-John
You can see a good example of a web site in C with source code: fossil.
It uses SQLite for the back end.

Can you use Adobe's Alchemy to execute a batch file?

I was going to make an AIR application but I need to execute an external application and because of the security restrictions in Adobe AIR... I was thinking why not try and bypass it by writing some C code that does something like System("file to execute"); and then use Alchemy to change it into a swc and us that in my application... Anyone tried this sort, or think it could work?
What you need to understand about Alchemy is that it compiles C into the same bytecode as actionscript, and it runs under the same virtual machine (AVM2) as flash/flex as3 applications.
The reason Alchemy is able to be faster for some operations is that the compiled C (compiled to bytecode) is given access to raw "memory" (ApplicationDomain.domainMemory) via some optimised AVM2 instructions that were added in flash 10.
What I'm trying to get at is that because Alchemy simply runs on top of the AVM2, it is restricted in the same way as any other application. Alchemy in an AIR application can do more than Alchemy in the browser sandbox, but it is still restricted by that sandbox.
If you really need to execute an external application, you'll need to look into something like Shu or Zinc.
Sorry I couldn't be any more help.
This will not work - Alchemy is not really / really not suited for programs that interact with the outside world. I don't think it will support doing a system call, and even if Alchemy would support it the flash/air runtime will most certainly still block it.
If you don't need cross platform behavior you can look into creating an oldfashioned 'projector'. It is possible to launch programs from a projector exe using fscommand- just be aware the executable you want to launch has to be located in a folder named fscommand next to the binary. If that is not sufficient you could try a third party commercial tool like http://www.northcode.com/.
No, Richard Szalay's correct: Alchemy compiles C code into ActionScript bytecode, so the resulting SWF is still subject to the same sandbox restrictions as any other; the AIR restrictions may be looser, but using Alchemy provides no benefit in that respect.
However, you can still "call out" of the sandbox using a socket connection, provided you have an app listening for the connection; check out Merapi -- it might be able to help as a simple solution, if you were open to using Java, although you could certainly roll your own with something else, like C#.

Resources