How to print frontslash in C? - html

Hi i'm having issues printing frontslash '/' on my html files, i need to collect data from a select input and send the values to my .cgi files but when i select a value like "/home" it prints "%2Fhome" how i can fix this? thank for ur answers..
Shell: <select name=shell>
<option value="/bin/bash">/bin/bash</option>
<option value="/bin/sh">/bin/sh</option>
<option value="/usr/bin/csh">/usr/bin/csh</option>
<option value="/bin/false">/bin/false</option>
</select><br>

The code below read and print to terminal the passed file. Tested with your text.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fd;
if (argc < 2)
{
return EXIT_FAILURE;
}
// Open requested file
fd = fopen(argv[1], "rb");
// Check file opened
if ( fd == NULL )
{
// Couldn't open file
return EXIT_FAILURE;
}
// Step through the file until EOF occurs
int c;
while ((c = fgetc(fd)) != EOF) {
printf("%c", c);
}
// Close file
fclose(fd);
return EXIT_SUCCESS;
}
Compile it with command: gcc -o test test.c -Wall -std=c99
Then call it as: ./test test.txt

Related

Trying to get an image to show up on an HTML file in a C web server

I'm trying to get more familiar with C by writing a web server, and I managed to get a method to create HTTP headers for html files yesterday but I have been unable to get images within that html file to load.
Right now I generate my header by opening the html file, and creating a file stream to write the start of the header, the size of it, and then I loop through the file to send each character to the stream. I them send that stream as a char pointer back to the main method which sends it as a response over the socket.
I'm imagining that there is some more work I need to do here, but I haven't been able to find a good solution or anything too helpful to point me in the right direction of how exactly to get it to display. I appreciate any responses/insight.
test.html
<!DOCTYPE html>
<html>
<head>
<title>Nick's test website</title>
</head>
<body>
<h1>Welcome to my website programmed from scratch in C</h1>
<p>I'm doing this project to practice C</p>
<table>
<tr>
<td>test1</td>
<td>test2</td>
<td>test2</td>
</tr>
</table>
<img src="pic.jpg"/>
</body>
</html>
headermaker.c
char * headermaker(char * file_name){
char ch;
FILE * fp;
fp = fopen(file_name, "r");
if(fp == NULL){
perror("Error while opening file.\n");
exit(-1);
}
//print/save size of file
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("File size is %d\n", size);
//create filestream
FILE * stream;
char * buf;
size_t len;
stream = open_memstream(&buf, &len);
//start header
fprintf(stream, "HTTP/1.1 200 OK\\nDate: Sun, 28 Aug 2022 01:07:00 GMT\\nServer: Apache/2.2.14 (Win32)\\nLast-Modified: Sun, 28 Aug 2022 19:15:56 GMT\\nContent-Length: ");
fprintf(stream, "%d\n", size);
fprintf(stream, "Content-Type: text/html\n\n");
//loop through each character
while((ch = fgetc(fp)) != EOF)
fprintf(stream, "%c", ch);
fclose(stream);
fclose(fp);
return buf;
}
Using a modified version of provided code to setup a web server using netcat and needed to see explanation of how to send jpeg using netcat
./one | nc -l 45231 ; { ./two && cat pic.jpeg; } | nc -l 45231;
Chrome browser can open http://localhost:45231 and will show the web page with an image. Also, can observe the network request - response sequence using "View->Developer->Developer Tools".
The code was built like this:
gcc -DONE -o one main.c && gcc -DTWO -o two main.c
The modified code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char * headermaker(char * file_name, char * content_type ){
char ch;
FILE * fp;
fp = fopen(file_name, "r");
if(fp == NULL){
perror("Error while opening file.\n");
exit(-1);
}
//print/save size of file
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
//printf("File size is %d\n", size);
//create filestream
FILE * stream;
char * buf;
size_t len;
stream = open_memstream(&buf, &len);
//start header
fprintf(stream, "HTTP/1.1 200 OK\n");
fprintf(stream, "Server: netcat!\n");
fprintf(stream, "Content-Type: %s\n",content_type);
fprintf(stream, "Content-Length: %d\n", size);
fprintf(stream, "\n");
//loop through each character
#ifdef ONE
while((ch = fgetc(fp)) != EOF)
fprintf(stream, "%c", ch);
#endif //#ifdef ONE
fclose(stream);
fclose(fp);
return buf;
}
int main( )
{
#ifdef ONE
char *buf = headermaker( "test.html", "text/html" );
printf( "%s", buf );
free(buf);
#endif //#ifdef ONE
#ifdef TWO
char *buf = headermaker( "pic.jpeg", "image/jpeg" );
printf( "%s", buf );
free(buf);
#endif //#ifdef TWO
return 0;
}
Another helpful debug tool was curl:
curl -vvv localhost:45231 > page.html
curl -vvv localhost:45231 > image.jpeg

Running AFL-Fuzzer buffer overflow

I am trying to learn about AFL-fuzzer and I have some questions:
I saw a video shows that if for instance there are two inputs in the code, so in the test case each line is for each input. Is that correct? Since I want put a full message (for example HTTP request) into one variable, so how do I do it?
I don't understand when to put ##.
For example I am trying to fuzz this code:
void Check_buffer(char* data)
{
char buffer[5];
strcpy(buffer, data);
}
int main(int argc, char* argv[])
{
char tmp_data = argv[1];
Check_buffer(argv[1]);
return 0;
}
I have created the in and out folders. In the in folder I have created a txt file with this content: "AAA".
The command line I have executed is:afl-clang -fno-stack-protector -z execstack 4.c -o vul4
Then I run:afl-fuzz -m none -i in/ -o out/ ./vul4 ##
I get the following error:perform_dry_run(), afl-fuzz.c:2852
If I run the command like this:afl-fuzz -m none -i in/ -o out/ ./vul4 AA
it runs good but it does not find any new path and does not find crashes.
As well as, I am trying to understand the concepts of this. If I want to inject code in specific location, how do I do it?
You are trying to get data from command line arguments, but the AFL does not work with argv[] (unless your program reads files like ./prog file.txt ).
Instead use something like
#define INPUTSIZE 100
char input[INPUTSIZE] = {0};
read (STDIN_FILENO, input, INPUTSIZE)
If you are still interested in getting data from argv[], you can use the experimental method from the AFL repository afl argv experimental
## is used when your program accepts a file via the command line
this means that the fuzzer will take the file, mutate it, and substitute it into the program instead ##
p.s.
#include <stdio.h>
#include <unistd.h>
#define INPUTSIZE 100
void Check_buffer(char* data)
{
char buffer[5];
strcpy(buffer, data);
}
int main(int argc, char* argv[])
{
char input[INPUTSIZE] = {0};
read (STDIN_FILENO, input, INPUTSIZE);
Check_buffer(input);
return 0;
}
AFL result image

texinfo include HTML header from file

I am writing a Texinfo manual, and for its HTML I need to include the contents of another file into the <head> ... </head> section of the HTML output. To be more specific, I want to add mathjax capability to the HTML version of the output to show equations nicely. But I can't seem to find how I can add its <script>...</script> to the header!
Since I couldn't find an answer and doing the job my self didn't seem to hard, I wrote a tiny C program to do the job for me. It did the job perfectly in my case!
Ofcourse, if there is an option in Texinfo that does the job, that would be a proper answer, this is just a remedy to get things temporarily going for my self.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ADDTOHEADER " \n\
<script type=\"text/javascript\" \n\
src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\">\n\
</head>"
void
addtexttohtml(char *filename)
{
char toadd[]=ADDTOHEADER;
size_t len=0;
ssize_t read;
FILE *in, *out;
char tmpname[]="tmp457204598345.html", *line=NULL;
in=fopen(filename, "r");
out=fopen(tmpname, "w");
if (in == NULL) exit(EXIT_FAILURE);
if (out == NULL) exit(EXIT_FAILURE);
while ((read = getline(&line, &len, in)) != -1)
{
if(strcmp(line, "</head>\n")==0) break;
fprintf(out, "%s", line);
}
fprintf(out, "%s", toadd);
while ((read = getline(&line, &len, in)) != -1)
fprintf(out, "%s", line);
if(line)
free(line);
fclose(in);
fclose(out);
rename(tmpname, filename);
}
int
main(int argc, char *argv[])
{
int i;
for(i=1;i<argc;i++)
addtexttohtml(argv[i]);
return 0;
}
This program can easily be compiled with $ gcc addtoheader.c.
Then we can easily put the compiled program (by default it should be called a.out) with the HTML files and run:
$ a.out *.html
You can just change the macro for any text you want.

How do I open a URL from C++?

how can I open a URL from my C++ program?
In ruby you can do
%x(open https://google.com)
What's the equivalent in C++? I wonder if there's a platform-independent solution. But if there isn't, I'd like the Unix/Mac better :)
Here's my code:
#include <stdio.h>
#include <string.h>
#include <fstream>
int main (int argc, char *argv[])
{
char url[1000] = "https://www.google.com";
std::fstream fs;
fs.open(url);
fs.close();
return 0;
}
Your question may mean two different things:
1.) Open a web page with a browser.
#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );
This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.
2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read this or/and this.
I hope it's at least a little helpful.
EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.
Use libcurl, here is a simple example.
EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system on a POSIX system:
system("<mybrowser> http://google.com");
By replacing <mybrowser> with the browser you want to launch.
Here's an example in windows code using winsock.
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
string website_HTML;
locale local;
void get_Website(char *url );
int main ()
{
//open website
get_Website("www.google.com" );
//format website HTML
for (size_t i=0; i<website_HTML.length(); ++i)
website_HTML[i]= tolower(website_HTML[i],local);
//display HTML
cout <<website_HTML;
cout<<"\n\n";
return 0;
}
//***************************
void get_Website(char *url )
{
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
char *get_http= new char[256];
memset(get_http,' ', sizeof(get_http) );
strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
strcat(get_http,url);
strcat(get_http,"\r\nConnection: close\r\n\r\n");
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(url);
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting to "<< url<<" ...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
{
cout << "Could not connect";
system("pause");
//return 1;
}
cout << "Connected.\n";
send(Socket,get_http, strlen(get_http),0 );
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
{
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')
{
website_HTML+=buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
delete[] get_http;
}
I was having the exact same problem in Windows.
I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:
'open' is not recognized as an internal or external command
After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.
Linux: xdg-open <URL>
Windows: start <URL>
For those of you that are using Windows, as I am, you can use the following:
std::string op = std::string("start ").append(url);
system(op.c_str());
I've had MUCH better luck using ShellExecuteA(). I've heard that there are a lot of security risks when you use "system()". This is what I came up with for my own code.
void SearchWeb( string word )
{
string base_URL = "http://www.bing.com/search?q=";
string search_URL = "dummy";
search_URL = base_URL + word;
cout << "Searching for: \"" << word << "\"\n";
ShellExecuteA(NULL, "open", search_URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
p.s. Its using WinAPI if i'm correct. So its not multiplatform solution.
There're already answers for windows. In linux, I noticed open https://www.google.com always launch browser from shell, so you can try:
system("open https://your.domain/uri");
that's say
system(("open "s + url).c_str()); // c++
https://linux.die.net/man/1/open
C isn't as high-level as the scripting language you mention. But if you want to stay away from socket-based programming, try Curl. Curl is a great C library and has many features. I have used it for years and always recommend it. It also includes some stand alone programs for testing or shell use.
For linux environments, you can use xdg-open. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.
$ xdg-open https://google.com
$ xdg-open steam://run/10
Of course you can wrap this in a system() call.
Create a function and copy the code using winsock which is mentioned already by Software_Developer.
For Instance:
#ifdef _WIN32
// this is required only for windows
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
//...
}
#endif
winsock code here
#ifdef _WIN32
WSACleanup();
#endif

How to use tcl apis in a c code

I want to use some of the functionalities(APIs) of my tcl code in another "c" code file. But i am not getting how to do that especiallly how to link them. For that i have taken a very simple tcl code which contains one API which adds two numbers and prints the sum. Can anybody tell me how can i call this tcl code to get the sum. How can i write a c wrapper that will call this tcl code. Below is my sample tcl program that i am using :
#!/usr/bin/env tclsh8.5
proc add_two_nos { } {
set a 10
set b 20
set c [expr { $a + $b } ]
puts " c is $c ......."
}
To evaluate a script from C code, use Tcl_Eval() or one of its close relatives. In order to use that API, you need to link in the Tcl library, initialize the Tcl library and create an interpreter to hold the execution context. Plus you really ought to do some work to retrieve the result and print it out (printing script errors out is particularly important, as that helps a lot with debugging!)
Thus, you get something like this:
#include <tcl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source myscript.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}
I think i have sloved it out. You were correct. The problem was with the include method that i was using. I have the files tcl.h, tclDecls.h and tclPlatDecls.h included in the c code but these files were not existing in the path /usr/include so i was copying these files to that directory, may be it was not a proper way to do. Finally i have not copied those files to /usr/include and gave the include path while compiling. I have created executable and it is givingthe proper result on terminal. Thanks for your help.
Here is the exact c code i am using :
#include <tcl.h>
#include <tclDecls.h>
#include <tclPlatDecls.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
printf("inside main function \n");
// Tcl_InitStubs(interp, "8.5", 0);
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source simple_addition.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}
And to compile this code and to generate executable file i am using below command :
gcc simple_addition_wrapper_new.c -I/usr/include/tcl8.5/ -ltcl8.5 -o simple_addition_op
I have executed the file simple_addition_op and got below result which was proper
inside main function
c is 30 .......
My special thanks to Donal Fellows and Johannes