Serving non-text files via http in C - c

I have a little web server in C which works fine when it has to serve html or css files. But when it comes to non-text files (image, compressed files, etc.), the data are corrupted when received by the client, which can't display them.
The response from the server is like this :
HTTP/1.1 200 OK
Date: Wed, 11 Jun 2014 11:24:27 GMT
Server: MacFly/0.1.1
Cache-Control: max-age=60
Expires: Wed, 11 Jun 2014 11:25:27 GMT
Last-Modified: Wed, 11 Jun 2014 06:13:38 GMT
ETag: "1041463782"
Content-Length: 36851
Content-Type: image/jpeg
���
The last line correspond to the corrupted data.
To generate the data, I use the following function which read the demanded file (any format : html, css, jpg, etc.) and save it in file_contents :
void get_content(const char * filename, char * file_contents) {
FILE * file;
int file_size;
file_size = get_file_size(filename);
if (file = fopen(filename, "rb")) {
fread(file_contents, sizeof(char), file_size-1, file);
fclose(file);
}
}

Related

Openssl library for interacting with POP3 local server inconsistency while retrieving response

Im working with on pop3 clinet using openSSL library. However I run to this incosistency problem, when reading from BIO socket, 4 times out of 5 there is "\r\n.\r\n" at the end, indicating end of multi-line response from server. But sometimes only "\r\n" is being returned for some reason, and the rest ".\r\n" appears in the next BIO_read. Buffer is not overflowing, it is set to 1024 length and this happens even in 604 characters long response.
Example:
+OK 555 octets
Return-Path: test1#mail.local
Received: from [127.0.0.1] (mail.local [127.0.0.1])
by LAPTOP-R30GIL79 with ESMTPA
; Wed, 20 Oct 2021 11:55:24 +0200
Message-ID: <dad24da8-dd91-62ed-3338-95fe46890c32#mail.local>
Date: Wed, 20 Oct 2021 11:55:24 +0200
MIME-Version: 1.0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.2.0
Content-Language: sk
To: test1#mail.local
From: test1 <test1#mail.local>
Subject: testing
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Text testovacej spravy.
.
calling it exactly same after that results in:
+OK 555 octets
Return-Path: test1#mail.local
Received: from [127.0.0.1] (mail.local [127.0.0.1])
by LAPTOP-R30GIL79 with ESMTPA
; Wed, 20 Oct 2021 11:55:24 +0200
Message-ID: <dad24da8-dd91-62ed-3338-95fe46890c32#mail.local>
Date: Wed, 20 Oct 2021 11:55:24 +0200
MIME-Version: 1.0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.2.0
Content-Language: sk
To: test1#mail.local
From: test1 <test1#mail.local>
Subject: testing
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Text testovacej spravy.
\r\n
As you can see ".\r\n" is missing for some reason. Octets does match but it disappear somehow. There are no memory leaks. This is function Im using for reading BIO socket
int readBIO(){
memset(buf, 0, strlen(buf));
int x = BIO_read(bio,buf,BUFF_SIZE);
if (x == 0 )
{
fprintf(stderr, "Error: Trying to read from closed connection.\n");
freeAll();
exit(1);
}else if(x < 0){
if (! BIO_should_retry(bio))
{
fprintf(stderr, "Error: Reading from bio socked has failed.\n");
freeAll();
exit(1);
}
}
if (checkResponse() != 0)
{
fprintf(stderr, "Error: Incorrect command / typo in command detected.\n Or wrong username / password has been entered.\n Server responded with -ERR.\n");
freeAll();
exit(1);
}
return 0;
}
Anyone might have an idea why this is happening?

email parsing by JavaMail , when mail contents is encoded by BASE64

Mail server: James.
Mail container: Maria DB
Mail parsing source is like below:
Return-Path: <monad#monad.com>
Delivered-To: yoonsang#bsecm.net
Received: from 192.168.10.159 ([192.168.10.159])
by WIN-55ERUE9ID5R (JAMES SMTP Server 2.3.2) with SMTP ID 374
for <monad#monad.net>;
Sat, 14 Nov 2015 16:08:06 +0900 (KST)
Received: from unknown (HELO cas01.bsecm.com) (192.168.10.14)
by 192.168.10.159 with ESMTP; 14 Nov 2015 16:07:48 +0900
X-Original-SENDERIP: 192.168.10.14
X-Original-MAILFROM: monad#monad.com
X-Original-RCPTTO: monad#monad.net
Resent-From: <monad#monad.com>
Received: from spam.bsecm.com (192.168.10.159) by cas01.bsecm.com
(192.168.10.14) with Microsoft SMTP Server (TLS) id 14.3.224.2; Sat, 14 Nov
2015 16:07:42 +0900
Received: from unknown (HELO ?219.255.136.51?) (219.255.136.51) by
192.168.10.159 with ESMTP; 14 Nov 2015 16:07:47 +0900
X-Original-SENDERIP: 219.255.136.51
X-Original-MAILFROM: allcredit#allcredit.co.kr
X-Original-RCPTTO: monad#monad.com
Date: Sat, 14 Nov 2015 16:07:56 +0900
Subject: =?euc-kr?B?W0tCxKu15Vdpc2VJbmZvIMfDt6+9ul3AscDnyKO01MDHIDExv/kgvcW/68Gkurizu7+qvK3A1LTPtNku?=
From: =?euc-kr?B?v8PFqbe5tfc=?= <allcredit#allcredit.co.kr>
To: <monad#monad.com>
Reply-To: <allcredit#allcredit.co.kr>
MIME-Version: 1.0
Content-Transfer-Encoding: BASE64
X-Mailer: Netpion Service Server v3.0.0
X-NetpionMsgID: 1447484876647.10284.1455.759978089,KB06,1006190838.1
Content-Type: multipart/mixed;
boundary="--Netpathy_Netpion.1447484876647.AA"
Message-ID: <11342c7a-220f-4538-9203-3610a6896f3e#CAS01.bsecm.com>
LS0tLU5ldHBhdGh5X05ldHBpb24uMTQ0NzQ4NDg3NjY0Ny5BQQ0KQ29udGVudC1UeXBlOiBtdWx0
aXBhcnQvYWx0ZXJuYXRpdmU7DQoJYm91bmRhcnk9Ii0tTmV0cGF0aHlfTmV0cGlvbi4xNDQ3NDg0
ODc2NjQ3LlpaIg0KDQotLS0tTmV0cGF0aHlfTmV0cGlvbi4xNDQ3NDg0ODc2NjQ3LlpaDQpDb250
NEthVzVwZENncE93bzgNCkwzTmpjbWx3ZEQ0PQ0KDQotLS0tTmV0cGF0aHlfTmV0cGlvbi4xNDQ3
NDg0ODc2NjQ3LkFBLS0NCg==
The contents is encoded by BASE64. At "Content-Transfer-Encoding: BASE64".
When I get contents Java tells me "Missing start boundary" exception.
byte[] messageBody = (byte[])("*FROM DB BLOB DATA*");
Message jamesMail = new MimeMessage(session, new ByteArrayInputStream(messageBody) );
Multipart mp = (Multipart)jamesMail.getContent();
int i = mp.getCount();
And now I decode mail contents.
This can parse mail contents to be readable.
java.io.InputStream is = jamesMail.getInputStream();
java.io.InputStream decodedIs = MimeUtility.decode(is, contentTransferEncoding);
mp = (Multipart)ms.getContent();
for(int m=0; m < mp.getCount(); m++){
// contents text processing
// attached file processing
}
But, mail contents has an attached file with encoded by BASE64.
And my code can not parse that attached file.
Question
-. How can I parsing pre-encoded mail contents using Javamail?
-. How can I parsing pre-encoded attachment file?
The message is incorrectly formatted. Multipart content MUST not be encoded, only "leaf" body parts may be encoded. "Netpion Service Server" is broken, please report the bug to the owner of that software.
You can work around this bug in the server by setting the "mail.mime.ignoremultipartencoding" System property to "false".
Temporary Solution)
I made a message [Header] + [ BASE64 Decoded Contents]
String headerLines = "";
String contentTransferEncoding = "";
while (headers.hasMoreElements()) {
Header h = (Header) headers.nextElement();
headerLines += String.format("%s: %s\r\n",h.getName(),h.getValue());
if(h.getName().equalsIgnoreCase("Content-Transfer-Encoding")){
contentTransferEncoding = (StringUtils.isEmpty(h.getValue()))?"":h.getValue();
}
}
InputStream hStream = new ByteArrayInputStream(headerLines.getBytes());
InputStream is = orgJamesMail.getInputStream();
InputStream decodedIs = MimeUtility.decode(is, contentTransferEncoding);
Message ms = new MimeMessage(session, mm);
mp = (Multipart)ms.getContent();
1. Get header information by String.
2. Convert header information of String to InputStream.
3. Concatenate "header inputstream" and "decoded contents inputstream"
4. And parse concatenated message stream.
Maybe this is need:
System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "false");

Azure upload blob 403

I'm trying to upload file on one of my Azure containers
this is one of my request send with ajax:
headers: Object
Authorization: "SharedKey MYACCOUNT:ENC_KEY"
Content-Type: "application/octet-stream"
data: File
x-ms-blob-type: "BlockBlob"
x-ms-date: "Mon, 19 Oct 2015 13:54:53 GMT"
x-ms-version: "2009-09-19"
type: "PUT"
url: "https://MYACCOUNT.blob.core.windows.net/data-test"
for the ENC_KEY I use :
authorizationHeader =
compute: (options, xhrOptions) ->
sig = #_computeSignature(options, xhrOptions)
result = 'SharedKey ' + options.storageAccount + ':' + sig
result
_computeSignature: (options, xhrOptions) ->
sigString = #_getSignatureString(options, xhrOptions)
key = CryptoJS.enc.Base64.parse(options.primaryKey)
hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key)
hmac.update sigString
hash = hmac.finalize()
result = hash.toString(CryptoJS.enc.Base64)
result
any ideas?
EDIT :
all code for authorizationHeader ->
https://gist.github.com/F4Ke/88debcede3b7e2312b11
2)
ERROR RESPONSE :
PUT https://MYACCOUNT.blob.core.windows.net/data-test 403 (Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.)
3)
#_getCanonicalizedHeadersString
itemcreation.coffee:232 x-ms-blob-type:BlockBlob
x-ms-date:Mon, 19 Oct 2015 14:33:15 GMT
x-ms-version:2009-09-19
#_getSignatureString
PUT
application/octet-stream
x-ms-blob-type:BlockBlob
x-ms-date:Mon, 19 Oct 2015 14:35:19 GMT
x-ms-version:2009-09-19
/MYACCOUNT/MYACCOUNT.blob.core.windows.net/data-test
The REST documentation describing how to sign a message can be found here. You can also take a look at the node shared key implementation hhere - might also help you...

Content-Type of Rest Api returning Null in salesforce

i am trying to call this rest api method
#HttpGet
global static String retrievingNotificationSettings(){
RestRequest req=RestContext.request;
RestResponse res=RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
if(req.headers.get('Content-Type').equals('application/xml'))
{
Map<String, SObjectField> fields = Notification_Settings__c.SObjectType.getDescribe().fields.getMap();
Schema.sObjectField T ;
Notification_Settings__c ss;
return 'hello World';
}
if(req.headers.get('Content-Type').equals('application/json'))
return System.JSON.serialize(note);
return null;
My request is
GET /services/apexrest/v.9/notifications/preferences/ritesh HTTP/1.1
X-HostCommonName:
ap1.salesforce.com
Authorization:
OAuth 00D90000000j9AW!AQkAQLba73cDzjXhQ4kkQ2PSru4XpFuJcwr5kg_W_MkZmQnm9vI653FBWeJaABwClQqtJZD_b6j7V0O_elkzvkh7IqRKSUop
X-PrettyPrint:
1
Host:ap1.salesforce.com
X-Target-URI:
https://ap1.salesforce.com
Content-Type: application/json
Connection:Keep-Alive
and the response i am getting is
HTTP/1.1 500 Internal Server Error
Date:
Fri, 25 Jan 2013 16:30:21 GMT
Content-Length:
203
Connection:
close
Content-Type:
application/json; charset=UTF-8
Server:
[
{
"message": "System.NullPointerException: Attempt to de-reference a null object\n\nClass.NotificationRestService.retrievingNotificationSettings: line 34, column 1",
"errorCode": "APEX_ERROR"
}
]
the line where i am getting error is
if(req.headers.get('Content-Type').equals('application/xml'))
i didn't understand why i am getting this error when in header i am passing value Content-Type as application/json ?? please tell me where i am making mistake
Can you System.debug(req.headers) to see if it was passed correctly?
To answer your null pointer question literally - use == instead of equals:
if(req.headers.get('Content-Type') == 'application/xml')
but that won't solve the real underlying problem.
You might want to try with different header (stupid, I know) or decide to add a GET parameter, something like &mode=json

WebDav And Exchange2007 HTTP1.1 404 Ressource not Found!

i have Exchange2007. and
i am using the url:
"https://exchange2007.exchange.server.com/Exchange/username/calendar";
'calendar', or 'mailbox'( in your language! example, "boite de reception" in french or "calendário" in portuguese)
with that url that i'm using i can list my ressources, but can't send a mail or write an appointement! why?!?
See that i get a response of the server 207multistatus and ok, but the return a
HTTP/1.1 404 Resource Not Found
i wish a 201 created!!! (for my appointement)
someone have better ideia ?
thx.
Console:
>>>>>>> to server ---------------------------------------------------
PROPPATCH /Exchange/marcelo/calend%C3%A1rio HTTP/1.1
Authorization: Basic bWFyY2Vsb0BleGNoYW5nZTptdXN0YWZhMSQ=
Content-Type: text/xml; charset=utf-8
User-Agent: Jakarta Commons-HttpClient/2.0final
Host: exchange2007.exchange.snap.com.br
Content-Length: 1407
<D:propertyupdate xmlns:D="DAV:">
<D:set>
<D:prop>
<mapi xmlns="xmlns">
http://schemas.microsoft.com/mapi/
</mapi>
<Cmd xmlns="urn:">
saveappt
</Cmd>
<dtEnd xmlns="urn:schemas:calendar">
2009-06-30T10:30:00.000Z
</dtEnd>
<contentclass xmlns="DAV">
urn:content-classes:Appointment
</contentclass>
<Subject xmlns="urn:schemas:httpmail">
Changed Test Appointment Subject
</Subject>
<Location xmlns="urn:schemas:calendar">
do
</Location>
<responserequested xmlns="urn:schemas:calendar">
0
</responserequested>
<saveappt xmlns="urn:schemas:calendar:cmd">
1
</saveappt>
<ressource xmlns="DAV">
https://exchange2007.exchange.snap.com.br/Exchange/marcelo/calendárioassuntoteste.EML
</ressource>
<alldayevent xmlns="urn:schemas:calendar">
0
</alldayevent>
<to xmlns="urn:schemas:header">
adrien
</to>
<dtStart xmlns="urn:schemas:calendar">
2009-06-30T10:00:00.000Z
</dtStart>
<isfolder xmlns="DAV">
0
</isfolder>
<cmd xmlns="Cmd">
saveappt
</cmd>
<HtmlDescription xmlns="urn:schemas:httpmail">
Let's meet here
</HtmlDescription>
<outlookmessageclass xmlns="http://schemas.microsoft.com/exchange/subject-utf8=Appointment">
IPM.Appointement
</outlookmessageclass>
<instancetype xmlns="urn:schemas:calendar">
0
</instancetype>
<meetingstatus xmlns="urn:schemas:calendar">
CONFIRMED
</meetingstatus>
<finvited xmlns="urn:schemas:mapi">
0
</finvited>
<BusyType xmlns="urn:schemas:calendar">
BUSY
</BusyType>
</D:prop>
</D:set>
</D:propertyupdate>
------------------------------------------------------------------------
<<<<<<< from server ---------------------------------------------------
HTTP/1.1 207 Multi-Status
Date: Thu, 16 Jul 2009 20:29:40 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
MS-Exchange-Permanent-URL: https://exchange2007.exchange.snap.com.br/Exchange/marcelo/-FlatUrlSpace-/b3ee92320938254c828a96e2e269a417-a6271d
Repl-UID: <rid:b3ee92320938254c828a96e2e269a417000000a6282e>
Content-Type: text/xml
Content-Length: 825
ResourceTag: <rt:b3ee92320938254c828a96e2e269a417000000a6282eb3ee92320938254c828a96e2e269a41700545bb4844c>
MS-WebStorage: 08.01.10240
<a:multistatus
xmlns:a="DAV:"
xmlns:b="xmlns"
xmlns:c="urn:"
xmlns:d="urn:schemas:calendar"
xmlns:e="DAV"
xmlns:f="urn:schemas:httpmail"
xmlns:g="urn:schemas:calendar:cmd"
xmlns:h="urn:schemas:header"
xmlns:i="Cmd"
xmlns:j="http://schemas.microsoft.com/exchange/subject-utf8=Appointment"
xmlns:k="urn:schemas:mapi">
<a:response>
<a:href>
https://exchange2007.exchange.snap.com.br/Exchange/marcelo/Calend%C3%A1rio
</a:href>
<a:propstat>
<a:status>
HTTP/1.1 200 OK
</a:status>
<a:prop>
<b:mapi>
</b:mapi>
<c:Cmd>
</c:Cmd>
<d:dtEnd>
</d:dtEnd>
<e:contentclass>
</e:contentclass>
<f:Subject>
</f:Subject>
<d:Location>
</d:Location>
<d:responserequested>
</d:responserequested>
<g:saveappt>
</g:saveappt>
<e:ressource>
</e:ressource>
<d:alldayevent>
</d:alldayevent>
<h:to>
</h:to>
<d:dtStart>
</d:dtStart>
<e:isfolder>
</e:isfolder>
<i:cmd>
</i:cmd>
<f:HtmlDescription>
</f:HtmlDescription>
<j:outlookmessageclass>
</j:outlookmessageclass>
<d:instancetype>
</d:instancetype>
<d:meetingstatus>
</d:meetingstatus>
<k:finvited>
</k:finvited>
<d:BusyType>
</d:BusyType>
</a:prop>
</a:propstat>
</a:response>
</a:multistatus>
------------------------------------------------------------------------
>>>>>>> to server ---------------------------------------------------
PROPFIND /Exchange/marcelo/calend%C3%A1rio HTTP/1.1
Authorization: Basic bWFyY2Vsb0BleGNoYW5nZTptdXN0YWZhMSQ=
Content-Type: text/xml; charset=utf-8
User-Agent: Jakarta Commons-HttpClient/2.0final
Host: exchange2007.exchange.snap.com.br
Content-Length: 207
Depth: 0
<D:propfind xmlns:D="DAV:">
<D:prop>
<D:displayname>
</D:displayname>
<D:getcontentlength>
</D:getcontentlength>
<D:getcontenttype>
</D:getcontenttype>
<D:resourcetype>
</D:resourcetype>
<D:getlastmodified>
</D:getlastmodified>
<D:lockdiscovery>
</D:lockdiscovery>
</D:prop>
</D:propfind>
------------------------------------------------------------------------
<<<<<<< from server ---------------------------------------------------
HTTP/1.1 207 Multi-Status
Date: Thu, 16 Jul 2009 20:29:40 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Content-Type: text/xml
Accept-Ranges: rows
MS-WebStorage: 08.01.10240
Transfer-Encoding: chunked
<a:multistatus
xmlns:a="DAV:"
xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/"
xmlns:c="xml:">
<a:response>
<a:href>
https://exchange2007.exchange.snap.com.br/Exchange/marcelo/Calend%C3%A1rio/
</a:href>
<a:propstat>
<a:status>
HTTP/1.1 200 OK
</a:status>
<a:prop>
<a:displayname>
Calendário
</a:displayname>
<a:getcontentlength b:dt="int">
0
</a:getcontentlength>
<a:resourcetype>
<a:collection>
</a:collection>
</a:resourcetype>
<a:getlastmodified b:dt="dateTime.tz">
2009-07-16T20:29:40.098Z
</a:getlastmodified>
<lockdiscovery xmlns="DAV:">
</lockdiscovery>
</a:prop>
</a:propstat>
<a:propstat>
<a:status>
HTTP/1.1 404 Resource Not Found
</a:status>
<a:prop>
<a:getcontenttype>
</a:getcontenttype>
</a:prop>
</a:propstat>
</a:response>
</a:multistatus>
I don't know anything about Exchange, but here are two WebDAV related comments.
1) Your property "mapi" in the namespace "xmlns" looks fishy. Not even Microsoft comes up with a namespace name that bad (I hope).
2) In the second server response, you are getting a status of 200 OK for most properties, except for getcontenttype (which is indeed 404).
Other than that: are you sure you it's the right thing to PROPPATCH against a calendar URL to do what you want?

Resources