Azure upload blob 403 - angularjs

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...

Related

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");

Serving non-text files via http in 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);
}
}

Deleting websocket connections in JavaScript with NodeJS

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
var jConnections = new Array();
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
var jConnectionIdentity = new Date();
jConnections.push(new Array(connection,jConnectionIdentity) );
//console.log("datestamp"+jConnections[0][1]);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//connection.sendUTF(message.utf8Data);
for(var i=0;i<jConnections.length;i++)
{
var jConnection = jConnections[i][0];
jConnection.sendUTF(message.utf8Data);
}
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
//connection.sendBytes(message.binaryData);
for(var i=0;i<jConnections.length;i++)
{
var jConnection = jConnections[i][0];
jConnection.sendBytes(message.binaryData);
}
}
});
connection.on('close', function(reasonCode, description) {
for(var i=0;i<jConnections.length;i++)
{
if(jConnections[i][1] == jConnectionIdentity)
{
delete jConnections[i];
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
console.log(jConnections.length);
}
}
});
});
If I open 3 client connections and send a message from each client and then close the third client I am seeing that the output of "console.log(jConnections.length);" is still three. Upon closing the third client and sending a message from client two a crash of NodeJS occurs. My console output looks like this:
C:\Program Files\nodejs>node.exe workingexample3.js
Mon May 20 2013 16:30:14 GMT-0700 (Pacific Daylight Time) Server is listening on port 8080
Mon May 20 2013 16:30:18 GMT-0700 (Pacific Daylight Time) Connection accepted.
Mon May 20 2013 16:30:20 GMT-0700 (Pacific Daylight Time) Connection accepted.
Mon May 20 2013 16:30:22 GMT-0700 (Pacific Daylight Time) Connection accepted.
Received Message: client1
Received Message: client2
Received Message: client3
Mon May 20 2013 16:30:43 GMT-0700 (Pacific Daylight Time) Peer 127.0.0.1 disconnected.
3
Received Message: client2
C:\Program Files\nodejs\workingexample3.js:48
var jConnection = jConnections[i][0];
^
TypeError: Cannot read property '0' of undefined
at WebSocketConnection.<anonymous> (C:\Program Files\nodejs\workingexample3.js:48:38)
at WebSocketConnection.EventEmitter.emit (events.js:95:17)
at WebSocketConnection.processFrame (C:\Program Files\nodejs\node_modules\websocket\lib\WebSocketConnection.js:403:26)
at WebSocketConnection.handleSocketData (C:\Program Files\nodejs\node_modules\websocket\lib\WebSocketConnection.js:247:14)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:736:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
C:\Program Files\nodejs>
I was hoping that upon the delete statement the value of jConnections.length would be decreasing by one but that does not seem to be happening. Since all three of my clients are connecting from localhost 127.0.0.1 I had to come up with a plan to identify each connection by something other than the remoteAdress property. That's why I am pushing a Date in addition to the connection object. I am hoping to id each connection by the Date it was created on.
1) After you call delete your array looks like this -
[[1, 1], [2, 2], undefined]
The length is still 3 :)

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

Language Tracking with Server-Side Google Analytics

I've ported the google analytics server side code over into my Python GAE application. Everything is working great, except for language tracking. I'm wondering if anyone here who has used google analytics on the server side has had success tracking languages.
The relevant bit of code is:
utm_url = utm_gif_location + "?" + \
"utmwv=" + GA_VERSION + \
"&utmn=" + str(randint(0, 0x7fffffff)) + \
"&utmhn=" + urllib.quote(domain) + \
"&utmsr=" + '-' + \
"&utme=" + '-' + \
"&utmr=" + urllib.quote(document_referer) + \
"&utmp=" + path + \
"&utmac=" + GA_ACCOUNT + \
"&utmcc=__utma%3D999.999.999.999.999.1%3B" + \
"&utmvid=" + visitor_id + \
"&utmip=" + ip
headers = {
'User-Agent': req.get('ua'),
'Accept-Language': req.get('lang')
}
httpresp = urlfetch.fetch(
url = utm_url,
method = urlfetch.GET,
headers = headers
)
if httpresp.status_code == 200:
logging.info("GA success: %s(%s)\n%s" % (utm_url, headers, httpresp.headers) )
else:
logging.warning("GA fail: %s %d" % (utm_url, httpresp.status_code) )
And here is a little debugging output which shows that I'm sending the Accept-Language header:
GA success: http://www.google-analytics.com/__utm.gif?utmwv=4.4sh&utmn=1306014991&utmhn=XXXXXXXXXXXXX.com&utmsr=-&utme=-&utmr=-&utmp=XXXXXXXXXXXXXXXXXXXXXXXXXX&utmac=MO-XXXXX-XX&utmcc=__utma%3D999.999.999.999.999.1%3B&utmvid=XXXXXXXXXXXXXXXXXX&utmip=XXX.XXX.XX.XX({'Accept-Language': u'en-us', 'User-Agent': u'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9A405'})
{'content-length': '35', 'x-google-cache-control': 'remote-fetch', 'x-content-type-options': 'nosniff', 'age': '93451', 'expires': 'Wed, 19 Apr 2000 11:43:00 GMT', 'server': 'GFE/2.0', 'last-modified': 'Wed, 21 Jan 2004 19:51:30 GMT', 'via': 'HTTP/1.1 GWA', 'pragma': 'no-cache', 'cache-control': 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate', 'date': 'Wed, 22 Feb 2012 16:25:04 GMT', 'content-type': 'image/gif'}
(I've XXXX'd stuff to protect the innocent).
As I said, everything is working great (locations, hit count, user agent), except languages. They are all being counted as "not set".
Any ideas?
The language attribute that Google Analytics tracks isn't from headers.
Rather, it's passed directly in the URL request to __utm.gif as the utmul attribute.
So, my computer sets utmul=en-us, using the navigator.language or navigator.browserLanguage attributes (which it seems like it makes lower case.)
In your case, that means you just need to add this line to your __utm.gif constructions:
"&utmul=" + req.get('lang')

Resources