System V MQ Text Length Issue - message-queue

I'm trying to write simple chat app with system v mqs but I am having a problem with my mtext value in the struct.
struct join_buf {
long mtype;
char mtext[8];
};
when I sent a message with this struct inserted. I is written in server sometimes correct and sometimes wrong. What I see is that; the number of the chars is fullfilled to 8.
What could you recommend me to read the mtext correctly ?

I think I found the mistake I am doing.
for (i = 0; i < nameLength; i++) {
joinbuf.mtext[i]=argv[1][i];
}
joinbuf.mtext[i]='\0';
without the last line the end of string is the length of the char array. adding that I am telling the runtime that this is it! Not one bit more!

Related

Accesing Json data after 'loading' it

With a lot of help from people in this site, I managed to get some Json data from an amazon page. The data, for example, looks like this.
https://jsoneditoronline.org/?id=9ea92643044f4ac88bcc3e76d98425fc
First I have a list of strings which is converted to a string.
script = response.xpath('//script/text()').extract()
#For example, I need the variationValues data
variationValues = re.findall(r'variationValues\" : ({.*?})', ' '.join(script))[0]
Then, in my code, I have this (not a great name, will be changed later)
variationValuesJson = json.loads(variationValues)
variationValuesJson is in fact a dictionary, so doing something like this
variationValues["size_name"][3]
Should return "5.5 M US"
My issue is that, when running the program, I get the string indices must be integers error. Anyone knows whats wrong?
Note: I have tried using 'size_name' instead of "size_name", same error
variationValues["size_name"][3] #this is the raw string which you have converted to variationValuesjson
I think this is not what you actually want.
Your code should be this.
variationValuesJson['size_name'][3] #use variationValuesjson ;)

Handling POST data sent by html form in CGI C

So, as I said a few days ago, I'm trying to make a login script using CGI-C on a Apache server.
My form is submitting two variables to Test.cgi: username and password (pattern 2 to 40 characters only) using the POST method.
here is my code so far:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *lengthy;
int figures;
char somelimit[512];
lengthy = getenv("CONTENT_LENGTH");
figures = atoi(lengthy);
fgets(somelimit, figures, stdin);
printf("Content-type: text/html\n\n");
printf("%s\n", somelimit);
return 0;
}
Q. How do I extract username and password values from stdin? A normal return I'm getting in the above case is "username=xyz&password=xyz12" how do I process this?
Q.I want to limit what I read from CONTENT_LENGTH header, in-case of a malformed CONTENT-LENGTH header.
what type of Data is this header returning? I know it is supposed to return a "Decimal no of Octets". Valid values are 0 or more. I want to take 1 to X, where X is the upper limit, considering I have two variables, username/password, both limited to 40 characters each in html form.
I tried int[] and char[], instead of the pointer. Why can't I convert it directly with something like:
int some[1024];
some = atoi(gentenv("CONTENT_LENGTH"));
why is atoi considered unsafe?
Q. How do I take only the stdin to contain only US-ASCII characters, to avoid malformed message-body.
I'm a C Newbie, so please go easy :)
PS: Please don't recommend any frameworks/web-servers, etc.
Edit:I just realized that perhaps I asked too many questions. Sorry about that. I'm going to fix this post to make it cohesive and well bounded. Please stand by.
Edit2: This is the final question, no more edits. I will accept an answer which at least answers 2 out of 3 questions above.
A lot of things going on here, and a lot of questions.
First, I recommend that you not output your HTTP header until you're about to output the rest. It's more logical that way, and allows you to output a Redirect header instead if something in your program requires it.
Second, use strtoul() instead of atoi(), since the latter has no error-checking.
You only need one buffer, not two; and I recommend you allocate it dynamically based off the content length. Use malloc() and don't forget to check the return value. Do NOT try to anticipate the upper bounds of your content length.
You'll have to decode the argument string to get any values out. What you do with them is up to you, but handling user names and passwords is a wholly separate topic that could take days to cover. But suffice it to say, never EVER store a password in plain text in a file.
CONTENT_LENGTH is text passed by stdin. That text includes the number of bytes of content. You will have to convert the text to an integer type, probably size_t, before it is useful to you. That's what your atoi() function is doing (which, again, you should replace with strtoul())
Use HTTPS.
Stop emitting your Content-type header prematurely. Then, if you decide you need to redirect, you can emit a Redirect header instead.
getenv() returns a pointer to a static text block that you cannot change. If you copy the pointer, you cannot change the text in the string. If you copy the string to a new array, you would be able to change the text in the string; however, I cannot think of a reason why you'd want to do that.
In your current code, you do not allocate any memory off the heap so you do not need to call free(). However, I recommend you rethink this aspect of your design.

$eval validate if inserted variable doesnt exists/incorrect

In my app i need to allow the user to add their own math formulas, can use operators and call variables. There is anyway to validate if a user write wrong a variable or a unknown variable to show an error?
I have and example here, you have some scope variables in the top of the controller. A minor difference, if I insert an invalid variable in the example it shows null, but in my code appears in blank.
Any suggestions?
Well honestly, if you weren't lazily throwing this stuff in eval, you could easily parse it yourself I recon.
How about removing all whitespaces, and interating over every single character?
I mean as long as there are no variables like aa or ab, you can just check like.
for (var i = 0; i < answer.length ; i++) {
if (!isvalidParamOrOperator(answer[i])) {
//can show error at position i+1;
return false;
}
}
with isValidParamOrOperator being something like
function(str) {
return "1234567890ab".indexOf(str);
}
Of course it becomes a little bit more complicated at longer params, but you'd be able to create something that splits on all operators like + - spaces & numbers. And then you'll have a list of all params which you can check. which should probably be checked on an array instead of my current suggestion, but this shouldn't be hard after you implement something like this.

PHP4: Json_encode method which accepts multi byte chars

in my company we have a webservice zu send data from very old projects to pretty new ones. The old projects run PHP4.4 which has natively no json_encode method. So we used the PEAR class Service_JSON instead. http://www.abeautifulsite.net/using-json-encode-and-json-decode-in-php4/
Today, I found out, that this class can not deal with multi byte chars because it extensively uses ord() in order to get charcodes from the string and replace the chars. There is no mb_ord() implementation, not even in newer PHP versions. It also uses $string{$index} to access the char at a index, I'm not completely sure if this supports multi byte chars.
//Excerpt from encode() method
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = $this->strlen8($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
//Here comes a switch which replaces chars according o their hex code and writes them to $ascii
we call
$Service_Json = new Service_JSON();
$data = $Service_Json->encode('Marktplatz, Hauptstraße, Endingen');
echo $data; //prints "Marktplatz, Hauptstra\u00dfe, Endinge". The n is missing
We solved this problem by setting up another webservice which receives serialised arrays and returns a json_encoded string. This service runs on a modern mahine, so it uses PHP5.4. But this "solutions is pretty awkward and I should look for a better one. Does anyone have an idea?
Problem description
German umlauts are replaced properly. BUT then the string is cut of at the end because ord returns the wrong chars. . mb_strlen() does not change anything, it gives the same length as strlen in this case.
Input string was "Marktplatz, Hauptstraße, Endingen", the n at the end was cut off. The ß was correctly encoded to \u00df. For every Umlaut it cuts of one more char at the end.
It's also possible the reason is our old database encoding, but the replacement itself works correctly so I guess it's the ord() method.
A colleague found out that
mb_strlen($var, 'ASCII');
solves the problem. We had an older lib version in use which used simple mb_strlen. This fix seems to do the same as your mb_convert_encoding();
Problem is solved now. Thank you very much for your help!

ref keyword with C++/CLI code interface

I'm writing code for the Windows Phone 8, and I'm trying to learn the ins and outs of crossing the C#/C++ code barrier.
Let's say I have two float[] arrays on the C# side, we'll call them data1 and data2. I want to perform an element-by-element addition on them. As this is in a realtime system, (audio processing) I don't want to risk doing allocations and deallocations inside my audio processing routines, so I'll want something along the lines of data1[i] += data2[i]. Since I'm explicitly learning how to call C++ from C# though, I won't just write the for loop in C#, I will write it in C++, like so:
void LibFilter::mixIn( Platform::Array<float>^ * data1, const Platform::Array<float>^ data2 ) {
auto outArray = (*data1);
// Don't do anything if we don't have matching lengths
if( data2->Length != outArray->Length )
return;
// Sum data2 into outArray (which is just a dereferenced data1)
for( unsigned int i=0; i<outArray->Length; ++i ) {
outArray[i] += data2[i];
}
}
This seems like it should work to me, but then again, I'm a C++ programmer, not a C# programmer, and apparently this should be used with the out keyword in C#, which means that data1 is a null pointer, no matter the value passed in. I believe I want to use the ref keyword instead, but I can't figure out how to do that using the Windows Phone 8 SDK.
Suggestions on how to use the ref keyword here, or how best to architect this would be much appreciated, as I am still learning best practices with C#. Thank you all!
EDIT: Error information
If I just try to use libfilter.mixIn( ref data1, data2 ); from my C# code, I get the following:
error CS1502: The best overloaded method match for 'libfilter.LibFilter.mixIn(out float[], float[])' has some invalid arguments
error CS1620: Argument 1 must be passed with the 'out' keyword
Based on your edit, it seems that the metadata that the C++/CX compiler generates for the method uses the out keyword, not the ref keyword.
Anyway, I don't see why you need to pass by reference at all. Platform::Array is mutable, so you can just modify it even if it's passed by value. The following MSDN article has an example similar to your code (see the section "Fill arrays"):
http://msdn.microsoft.com/en-us/library/windows/apps/hh700131.aspx