Getting Bus error: 10 when I run my C code - c

I'm writing a function in C to make my web server display the directory listing as an HTML document. When I run make, everything seems to compile fine, but when I run the file, I keep getting bus error:10. Thank you for all of your help!
This is the HTML template that I want to write into the socket id to display when I run my file on localhost:3000 (or localhost:8000):
<ul>
<li><a href='./'>.</a></li>
<li><a href='../'>..</a></li>
<li><a href='.DS_Store'>.DS_Store</a></li>
<li><a href='resume/'>resume</a></li>
<li><a href='lolcode.html'>lolcode.html</a></li>
<li><a href='ybruf.pid'>ybruf.pid</a></li>
</ul>
This is my code for this function:
static bool process_dir(int sock_id, char *doc)
{
// Open the directory for reading
DIR *dir = opendir(doc);
/* if the dir failed to open */
if (dir == NULL)
{
syslog(LOG_ERR, "opendir(): %s", strerror(errno));
write_http_header(sock_id, PROTO "404 File Not Found",
"File Not Found");
return false;
}
// Write the header - we seem to be ok
// Technically, this is not correct. We must first fully read the direct
/* successfull open the dir */
write_http_header(sock_id, PROTO "200 OK", NULL);
// Define the template
struct dirent *dirp;
dirp = readdir(dir);
char dirp_name[1024]; // if it is a diretory then dirp_name will have /
char *ul_open = "<ul>\n";
char *ul_close = "</ul>";
write(sock_id, ul_open, strlen(ul_open));
char *li_open = "<li><a href='";
char *li_middle = "'>";
char *li_close = "</a></li>\n";
while (dirp != NULL)
{
// if it's a file, then just need to get the name
// for example: resume.html
strcpy(dirp_name, dirp->d_name);
if (dirp->d_type == DT_DIR)
{
// if it's a directory then need to have / at the end
// for example: resume/
strcat(dirp_name, "/");
}
// for example: <li><a href='resume/'>resume</a></ li>
write(sock_id, li_open, strlen(li_open));
write(sock_id, dirp_name, strlen(dirp_name));
write(sock_id, li_middle, strlen(li_middle));
write(sock_id, dirp->d_name, dirp->d_namlen);
write(sock_id, li_close, strlen(li_close));
dirp = readdir(dir);
}
write(sock_id, ul_close, strlen(ul_close));
errno = 0; // Assume no errors
closedir(dir);
if (errno)
{
// Too late to complain!
syslog(LOG_ERR, "%s", strerror(errno));
}
return errno == 0;
}

Related

I am creating an embedded web server using Mongoose. How can I get the parameters in the URL(looking for something like req.getparameter() in Java)

void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data)
{
if (ev == MG_EV_HTTP_MSG)
{
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_http_match_uri(hm, "/api/hello")) // On /api/hello requests,
{
char html[1000];
strcpy(html, "<!DOCTYPE html>"
"<html>"
"<head>"
"</head>"
"<body>"
"<form action=\"sum\" method = \"GET\">"
"<label> Number 1</label>"
"<input type=\"text\" name=\"number1\"> <br>"
"<label> Number 2</label>"
"<input type=\"text\" name=\"number2\"><br>"
"<input type=\"submit\" value=\"Add\">"
"</form>"
"</body>"
"</html>");
mg_http_reply(c, 200, "Content-Type: text/html\r\n", html);
}
else if(mg_http_match_uri(hm, "/api/sum"))
{
struct mg_str params = hm->body;
double num1, num2;
if(mg_json_get_num(params, "$[0]", &num1) &&
mg_json_get_num(params,"$[1]", &num2))
{
mg_http_reply(c, 200, "Content-Type: text/plain\r\n", "result:%g\n", num1 + num2);
}
else
{
mg_http_reply(c, 500, "NULL", "%s","Parameters Missing");
}
}
else // For all other URIs,
{
mg_http_reply(c, 200, "Content-Type: text/plain\r\n", "%s\n", "Static Content");
}
}
}
void task1(void)
{
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Init manager
mg_http_listen(&mgr, "http://10.0.0.6:8000", fn, &mgr); // Setup listener
for (;;) mg_mgr_poll(&mgr, 1000); // Event loop
}
In the code main.c calls task1(). When I type the URL "http://10.0.0.6:8000/api/hello" I am getting the html form. But on submitting the form I am not able to go to "http://10.0.0.6:8000/api/sum".
Tried
else if(mg_http_match_uri(hm, "/api/sum"))
{
mg_http_reply(c, 200, "Content-Type: text/plain\r\n", "%s\n", "Static Content");
}
and is working fine. I suspect the problem is in getting parameter values. In Java we have request.getparameter() for getting required parameters, Do we have something like that in mongoose.
So please tell me the correct way to get parameter values in a URL.
The problem is that you're submitting a form via GET, e.g. parameters are passed in the query string (in the URL). And you're getting parameters from the body.
There are two ways to fix your code.
Submit parameters in the HTTP body. To do that, change your form's method from GET to POST.
OR, get parameters from the query string. To do that, change struct mg_str params = hm->body; to struct mg_str params = hm->query;
Hope that helps.

How can I read the request posted file in IIS module?

I wrote an IIS module and it's working fine.
I want to get the posted file from request.
In below code, I could get sent form data and view the file in header:
IHttpRequest * pHttpRequest = pHttpContext->GetRequest();
if (pHttpRequest != NULL)
{
LPCSTR body;
DWORD cbBytesReceived = 1024;
void * pvRequestBody = pHttpContext->AllocateRequestMemory(cbBytesReceived);
if (NULL == pvRequestBody)
{
pProvider->SetErrorStatus(hr);
return RQ_NOTIFICATION_FINISH_REQUEST;
}
if (pHttpRequest->GetRemainingEntityBytes() > 0)
{
while (pHttpRequest->GetRemainingEntityBytes() != 0)
{
hr = pHttpRequest->ReadEntityBody(
pvRequestBody, cbBytesReceived, false, &cbBytesReceived, NULL);
if (FAILED(hr))
{
if (ERROR_HANDLE_EOF != (hr & 0x0000FFFF))
{
pProvider->SetErrorStatus(hr);
return RQ_NOTIFICATION_FINISH_REQUEST;
}
}
body = (LPCSTR)pvRequestBody;
pszResult = pszResult + body;
}
}
}
The result is:
-----------------------5r707ac9a9687yu
Content-Disposition: form-data; name="file"; filename="1.zip"
Content-Type: application/octet-stream
PKþóÐMš`_ÿív(X[úM/­xvœ5a¢~¯²²ÊÆÎÈá"}å
lIœì*7·®-W§Xþn¹DçvÃŒØÀ>ÊHñ\N-kÂ¥ûºÂm'ŒäõÚÌŸÏŽ)ããSqŽT3ÕïDñ?ËWÇKy«zAÉ÷øŒ¿ÂÇ
I tried to cast file part(PKþóÐMš`_ÿív ...) to binary and write file, but file is curropted because the header contains all info (all posted files,content denposition,...) and not the clear binary file.
How can I write the sent files on disk(binary/text)?

Sending log schema to kaa server from RPI3 with optional fields

I am trying to send a log schema from raspberry pi C application, to back end kaa server.
Here is the schema
{
"type" : "record",
"name" : "RemoteSensorLog",
"namespace" : "org.kaa.iot.log.sensor",
"fields" : [ {
"name" : "deviceId",
"type" : {
"type" : "string",
"avro.java.string" : "String"
}
}, {
"name" : "temperature",
"type" : [ "double", "null" ]
}, {
"name" : "humidity",
"type" : [ "long", "null" ]
}, {
"name" : "batteryLevel",
"type" : [ "int", "null" ]
} ],
"version" : 1,
"dependencies" : [ ],
"displayName" : "RemoteSensorLog",
"description" : "This is the log sent by remote sensors"
}
Some of the items in the log schema are optional, Here is the initialization function
void kaaLogInitializing(void *context)
{
void *log_storage_context = NULL;
void *log_upload_strategy_context = NULL;
printf("Initializing the Kaa log\n");
kaa_client_t * kaa_client_context = context;
if (context == NULL) {
return;
}
/* Log delivery listener callbacks. Each callback called whenever something happen with a log bucket. */
kaa_log_delivery_listener_t log_listener = {
.on_success = success_log_delivery_callback, /* Called if log delivered successfully */
.on_failed = failed_log_delivery_callback, /* Called if delivery failed */
.on_timeout = timeout_log_delivery_callback, /* Called if timeout occurs */
.ctx = kaa_client_context, /* Optional context */
};
/* The internal memory log storage distributed with Kaa SDK */
kaa_error_t error_code = ext_unlimited_log_storage_create(&log_storage_context,
kaa_client_get_context(
kaa_client_context
)->logger
);
if (error_code) {
printf("Failed to create Kaa log storage %d\r\n", error_code);
return;
}
error_code = ext_log_upload_strategy_create(kaa_client_get_context(
kaa_client_context),
&log_upload_strategy_context, KAA_LOG_UPLOAD_VOLUME_STRATEGY);
if (error_code) {
printf("Failed to create log upload strategy, error code %d\r\n", error_code);
return;
}
error_code = ext_log_upload_strategy_set_threshold_count(log_upload_strategy_context,
LOG_UPLOAD_THRESHOLD);
if (error_code) {
printf("Failed to set threshold log record count, error code %d\r\n", error_code);
return;
}
error_code = kaa_logging_set_strategy(kaa_client_get_context(kaa_client_context)->log_collector,
log_upload_strategy_context);
if (error_code) {
printf("Failed to set log upload strategy, error code %d\r\n", error_code);
return;
}
/* Specify log bucket size constraints */
kaa_log_bucket_constraints_t bucket_sizes = {
.max_bucket_size = MAX_LOG_BUCKET_SIZE, /* Bucket size in bytes */
.max_bucket_log_count = MAX_LOG_COUNT, /* Maximum log count in one bucket */
};
/* Initialize the log storage and strategy (by default it is not set) */
error_code = kaa_logging_init(kaa_client_get_context(
kaa_client_context)->log_collector
, log_storage_context
, log_upload_strategy_context
, &bucket_sizes);
if (error_code) {
printf("Failed to initialize Kaa log %d\r\n", error_code);
return;
}
/* Add listeners to a log collector */
kaa_logging_set_listeners(kaa_client_get_context(
kaa_client_context)->log_collector,
&log_listener);
}
Here is the function I use to send log
void sendLog(void *context)
{
kaa_client_t * kaa_client_context = context;
float temperature = 25.5;
if (context == NULL) {
return;
}
logDelivered = LOG_DELIVERY_DELIVERING;
printf("Start attempt to send Log\n");
kaa_logging_remote_sensor_log_t *log_record = kaa_logging_remote_sensor_log_create();
log_record->device_id = kaa_string_copy_create("Dev1");
log_record->temperature = kaa_logging_union_double_or_null_branch_0_create();
log_record->temperature->data = &temperature; /* create subobject */
log_record->humidity = kaa_logging_union_long_or_null_branch_1_create();
log_record->battery_level = kaa_logging_union_int_or_null_branch_1_create();
printf("Log record created\n");
/* Log information. Populated when log is added via kaa_logging_add_record() */
kaa_log_record_info_t log_info;
kaa_error_t error = kaa_logging_add_record(
kaa_client_get_context(kaa_client_context)->log_collector,
log_record, &log_info);
if (error) {
printf("Failed to add log record, error code\r\n");
kaa_client_stop(kaa_client_context);
return;
}
//log_record->destroy(log_record);
}
I have 2 problems
Problem1 #### : if I uncomment the last line in sendLog function log_record->destroy(log_record); I got this error double free or corruption (out): 0x7efe05
Problem2 #### : after commenting the mentioned line and running the application I never get any error or the server get the log nothing seems to happen neither I receive log was sent successfully or failure or timeout.
You need to manually allocate memory to store the temperature value. It will be freed in thelog_record->destroy(log_record).
So, you need to do something like this:
double *p_temperature = KAA_MALLOC(sizeof(double));
if (!p_temperature) {
// error handling
}
*p_temperature = 25.5;
log_record->temperature->data = p_temperature;

Anyone know how to proper use the nsIFilePicker ?

I am trying to copy a text file from one folder to another. Issue is once you select the folder to save to what is the proper code to get the file to copy to that folder? I and using NSI Filepicker modeOpen and modeSave and can't find any code on how to save file properly. the MDN is lacking code.
var dispdir = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
var nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["#mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
fp.init(window, "Select a File", nsIFilePicker.modeOpen);
fp.appendFilters(nsIFilePicker.filterText);
fp.displayDirectory = dispdir;
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnCancel) {
var file = fp.file;
var path = fp.file.path;
}
var savedir = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
savedir.append("Test Folder");
if( !savedir.exists() || !savedir.isDirectory() ) {
// if it doesn't exist,create
savedir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
alert(savedir.path + "\n" + "Folder was made");
}
var fp2 = Components.classes["#mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
fp2.init(window, "Save file to?", nsIFilePicker.modeSave);
fp2.appendFilters(nsIFilePicker.filterText);
fp2.displayDirectory = savedir;
fp2.defaultString = fp.file.leafName;
var rv = fp2.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
}
var aDir = Components.classes["#mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
aDir.append(fp2.file.parent.path);
alert(fp2.file.parent.path)
fp.file.copyTo(aDir, null);
copyFile(fp.file.path);
alert(fp2.file.path + "\n" + "File copied successfuly!")
Use fp.file to create a stream, see
https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Synchronous
I have a question for you though, where is 'window' from fp.init(window defined?

file upload cakephp

when uploading an image to the server using cakephp
$this->Model->Behaviors->attach('ImageUpload', Configure::read('photo.files'));
photo uploaded successfully, and the database fields also
but shows following error instead of returning to index page.
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 104]
Notice (8): Undefined index: class [CORE\cake\libs\model\behaviors\upload.php, line 107]
Warning (2): Cannot modify header information - headers already sent by (output started at E:\umoorthy_105act10\projects\dev1base\core\cake\basics.php:111) [CORE\cake\libs\controller\controller.php, line 614]
wat to do?
Cake has already wrote where to look for a problem
Configure::read('photo.files')
do following to check if everything is ok
pr(Configure::read('photo.files'))
public function uploadFilesIphone($folder, $formdata, $replace , $itemId = null) {
// setup dir names absolute and relative echo "<pre>"; print_r($formdata); exit;
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder; //echo
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($itemId) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$itemId;
// set new relative folder
$rel_url = $folder.'/'.$itemId;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png','application/octet-stream');
// loop through and deal with the files;
$key = array();
$value = array();
foreach($formdata as $key => $value)
{
if($key == is_array($value))
{
$filename = str_replace(".", $replace , $value['name']);
}
// replace spaces with underscores
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type)
{
if($key == is_array($value))
{
if($type == $value['type'])
{
$typeOK = true;
break;
}
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
if($key == is_array($value))
{
switch($value['error'])
{
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename))
{
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
else
{
// create unique filename and upload file
// ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.$filename;
if($key == is_array($value))
{
$success = move_uploaded_file($value['tmp_name'], $url);
}
}
// if upload was successful
if($success)
{
// save the url of the file
$result['urls'][] = $url;
}
else
{
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
}
elseif($value['error'] == 4)
{
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
}
else
{
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
}
return $result;
}

Resources