вторник, 10 октября 2017 г.

DevOps' tips & tricks for GNU/Linux developers

DevOps' tips & tricks for GNU/Linux developers
  1. Q: Ansi terminal for Windows
    A:
    1. download and install wsltty
    2. launch your program under mintty: mintty.exe program.exe

  2. Q: globally replace include path details in whole Golang project using sed
    A: 
    find . -name '*.go' -type f -execdir sed -i \
    "s#github.com/fiorix/go-smpp#github.com/Zensey/go-smpp#" \
    '{}' \;
    

    Changes from / to (example):
    include "github.com/fiorix/go-smpp"
    include "github.com/Zensey/go-smpp"

  3. Q: simulate client disconnect on GNU/Linux server
    A:
    # iptables -A INPUT -s 11.22.33.44 -j DROP; iptables -D INPUT -s 11.22.33.44 -j DROP
    where 11.22.33.44 is client's IP

  4. Q: How to set udev rule to grant access for usb termo-printer (for example Godex) ?
    A:
    Create and edit file /etc/udev/rules.d/99-printers.rules
    Set ATTRS{idVendor} and ATTRS{idProductto proper vendor/product id of your printer:
    ACTION=="add", SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="195f", ATTRS{idProduct}=="0001", ENV{ID_USB_INTERFACES}=="*:0701??:*", MODE="0666"
    

  5. Q: Git. merge changes from given tag
    A:
    git fetch --tags origin
    git merge tag_name


  6. Q: Git. Push a tag to origin
    A:
    After creating a tag in local branch do git push origin <tag_name> for  ex. git push origin v1.3.4
  7. Q: Git. merge changes from given tag
    A:
    git describe --tags --always

  8. Q: Esptool. Dump ESP's ROM (for 1 megabyte)
    A:
    ./esptool.py --port /dev/ttyUSB0 read_flash 0x00000 0x100000 ./dump_1.bin

  9. Q: Esptool. Erase ESP's ROM
    A:
    ./esptool.py --port /dev/ttyUSB0 erase_flash

  10. Q: Redmine. Get info about ticket using REST API
    A:
    wget https://Server/issues/12345.json?include=journals

  11. Q: Batch conversion mp4 -> mp3
    A:
    find -name "*.mp4" -type f -execdir ffmpeg -i '{}' -f mp3 '{}'.mp3 \;

  12. Q: How to share a folder using HTTP, for ex. to transfer files from PC to mobile ?
    A:

    Download webserver.go from https://gist.github.com/alexisrobert/982674
    Run:
    go run webserver.go

  13. Q: How to capture audio of conversation in Skype / Voip or any other program
    A:
    Use audio-recorder. To install it on Ubuntu use repository ppa:audio-recorder/ppa.

  14. Q: Test local syslog logging
    A:
    logger -t topic -p local0.debug TestMsg

  15. Q: Git. Spawning a branch from an empty state, before any commit has been made
    A:
    git checkout --orphan my_namespace/new_project/master

  16. Q: Git. How to merge the last commit with a previous one
    A:
    git reset HEAD~1
    git commit --amend
  17. Q: Git. How to merge the last commit with a previous one
    A:
    git reset HEAD~1
    git commit --amend

вторник, 22 августа 2017 г.

SMPP for Go developers and not only

FAQ about SMPP
  1. Q: How to get notification on subscriber availability using HLR

    A:
    An ESME may use the set_dpf parameter [in the submit_sm] to request the setting of a delivery pending flag (DPF) for certain delivery failure scenarios, such as MS [i.e. Mobile Station] unavailability (as indicated by the HLR). The MC [i.e. Message Center] should respond to such a request with an alert_notification PDU when it detects that the destination MS has become available. For more information see https://www.activexperts.com/sms-component/sms/smpptlv/
  2. Q: Каковы преимущества использования SMPP

    A: 
  3. - стандартный протокол (не придется переписывать бек-энд при смене SMS-шлюза)
    - асинхронность, высокая пропускная способность
    - отправка сообщений происходит практически мгновенно
    - оперативная доставка статуса доставки и ошибок и бОльшая информативность,
    точность времени доставки до минуты
    - возможность проверка номера и дислокации абонента при помощи HLR-запроса (напр. есть такие ошибки как "Абонент не существует", "Абонент не в сети", "Абонент заблокирован")

  4. Q: What are the advantages of SMPP

    A: 
  5. - This is a standard industrial protocol, no need to rewrite back-end if you move to another SMPP provider / ESME
    - Asynchrony, high throughput
    - Sending messages is almost instantaneous
    - Prompt delivery of delivery status, submit errors are more informative, delivery time accuracy up to a minute
    - The ability to check the number and location of the subscriber using HLR-request (eg there are such errors as "Subscriber does not exist", "Subscriber is offline", "Subscriber is blocked")

  6. Q: How to get ESME status of sent message immediately / SMPP implementaion by fiorix.

    A:
  7. sm, err = c.tx.Submit(m)
    if err == nil {
        log.Println("Send > ID:", sm.RespID())
    } else {
        log.Println("Send > err", c.err)
        if sm != nil {
            s:= uint32(sm.Resp().Header().Status)
            log.Println("Send > err #", s)
        }
    }

  8. Q: How to check if transmitter is bound ? / SMPP implementaion by fiorix
    I want to restrict Send() of message during reconnects. Because if Bind of Tranciever coincide with Submit_SM it causes Bind to fail -- SMSC does not answer on Bind.

      A: Solution:
      conn_st_ch := c.tx.Bind()
      go func() {
          for {
              select {
              case conn_st := <-conn_st_ch:
                  c.bound = conn_st.Status() == smpp.Connected
                  log.Println("bound>", c.bound, c.id)
              }
          }
      }()
      

      Note: It works because of the non-blocking nature of signal sent from client::notify
    1. Q: What software I can use for Tests / Debug / Simulation of SMPP gateway ?

      A:
      I recommend ActiveXPerts SMPP simulator. However it doesn't work under wine.
    2. Q: How to parse short message from deliver_sm_resp

      A: for JavaScript
      var re_key = /(\w+(\s\w+)?)/
      var re_val = /(\w+|[0-9a-f]+|null|\-)|(\s+|$)/
      re_key.compile(re_key);
      re_val.compile(re_val);
      
      // examples:
      //id:327 sub:001 dlvrd:001 submit date:1506272148 done date:1506272148 stat:DELIVRD err:null text:-'
      //id:c449ab9744f47b6af1879e49e75e4f40 sub:001 dlvrd:0 submit date:0610191018 done date:0610191018 stat:ACCEPTD err:0 text:This is an Acti
      //id:7220bb6bd0be98fa628de66590f80070 sub:001 dlvrd:1 submit date:0610190851 done date:0610190951 stat:DELIVRD err:0 text:This is an Acti
      //id:b756c4f97aa2e1e67377dffc5e2f7d9b sub:001 dlvrd:0 submit date:0610191211 done date:0610191211 stat:REJECTD err:1 text:This is an Acti
      //id:bd778cd76ae9e79da2ddc8188c68f8c1 sub:001 dlvrd:0 submit date:0610191533 done date:0610191539 stat:UNDELIV err:1 text:This is an Acti
      //
      //Field  Meaning
      //id  The message reference of the message.
      //    sub  Sub-ID, not used.
      //    dlvrd  Value '1' when the message has been delivered, if the message is still pending '0'.
      //    submit date  Submission date and time.
      //    done date  Date and time the status has changed, or message delivery time when stat is set to 'DELIVRD'.
      //    stat  Current status of the message.
      //    err  Additional error code, provider specific.
      //    text  Part of the original message text.
      
      module.exports.short_msg_parse = function(msg) {
          obj = {};
          var s = msg//.toLowerCase();
          for (;;) {
              var i = s.indexOf(':');
              if (i <= 0) break;
              var f = s.slice(0, i);
              if (k = f.match( re_key )) {
                  var key = k[1];
                  s = s.slice(i + 1);
                  if (v = s.match( re_val )) {
                      i = v[0].length;
                      s = s.slice(i);
                      obj[key] = v[1];
                  } else
                      break;
              } else
                  break;
          }
      
          // TODO: validate field names
      
      FIELDS = [ 'id', 'sub', 'dlvrd', 'submit date', 'done date', 'stat', 'err', 'text' ]; return obj; }



    3. Q: How to parse done date in short message from deliver_sm_resp

      A: for JavaScript
      // possible date formats:
      // yyMMddHHmm
      // yyMMddHHmmss
      // yyyyMMddHHmmss
      module.exports.smppDate_toLocalDate = function (str) {
          var _size = Math.ceil(str.length / 2),
              _ret  = new Array(_size),
              _offset;
      
          for (var _i=0; _i<_size; _i++) {
              _offset = _i * 2;
              _ret[_i] = Number(str.substring(_offset, _offset + 2));
          }
      
          _ret[0] += 2000;
          _ret[1] -= 1;
          return utils.applyToConstructor(Date, _ret);
      }
      

    4. Q: What routing restrictions do countries have ?

      A:
      USA -- Please use E.164 format, as 14087525280 , additionally apart from the fact that the number appears to be a landline, for USA traffic you need to follow the guidance in this article. To summarise for USA traffic: * For P2P traffic you will need to use a Nexmo virtual number as sender. * For A2P traffic you will need to use either a Short Code or a Toll Free number/

      China

      France -- When sending to France with alpha sender IDs you must include within the message "STOP SMS AU 36184".

    External links

    воскресенье, 30 июля 2017 г.

    Инспекция содержимого трафика мобильных приложений без прав рута

    Чтобы проверить какие данные отправляет мобильное приложение можно воспользоваться снифером, но обычно они требуют рута.

    Но есть приложения, способные перехватывать трафик, в том числе шифрованный, без прав рута. О таком приложении и пойдет речь -- это Packet Capture.


    Его принцип действия : запускается локальный vpn-сервер со встроенной функцией прозрачного http(s)-прокси и удостоверяющего центра, способного динамически выпускать сертификаты. После поднятия vpn меняется маршрут по умолчанию и весь трафик заворачивается на него.

    Обычное приложение, если в нем нет взаимной проверки сертификатов, даже не заметит что мы читаем наш трафик.

    Есть ограничения:
    - не поддерживается перехват ssl-трафика на нестандартных портах (отрапортовано автору)

    О том как реализовать перехват ssl-трафика стандартными средствами Linux читайте в статье  vlad805 по ссылке.

    Ссылки по теме:

    1. Packet Capture
    2. О том, как ВКонтакте собирает информацию о нас // Владислав Велюга (vlad805) July 29, 2017

    суббота, 15 июля 2017 г.

    Cloud Lockers

    Lockers with cloud synchronization of account data. Opens a door when you bring your card close to reader.
    https://t.co/SU5b5Ht5hn

    Connectivity: RS-485
    Server-side: Sqlite3 + Nodejs
    Client-side: AngularJS
    Type of access card: Em-Marine


    GUI of lockers management software
    Screenshots.





    FAQ Dreambox DM800 HD.


    Речь пойдет о Дримбоксе 800hd с прошивкой Gemini Enigma 5x, image 07.21.2010, kernel 2.16
    1. Q: Как удаленно войти в командную консоль консоль (SSH) ?
      A:
      ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 root@192.168.1.120

    2. Q: Как скопировать файлы на dreambox (по SSH) ?
      A: 
      scp -r -oKexAlgorithms=+diffie-hellman-group1-sha1 enigma2-plugin-wicardd\ 1.18-dm800hd\,se-gemini  root@192.168.1.120:/home/root

    3. Q: Как временно сменить адрес шлюза по умолчанию для получения интернета с резервного роутера?
      A:
      допустим есть резервный роутер с
       адресом 192.168.1.203, тогда выполним:
      ip route replace default via 192.168.1.203 dev wlan0
      для возврата к основному роутеру 203 надо заменить на 1 или др.

    4. Q: После перехода на плагин wicard происходят подвисания, приходится перезапускать плагин.
      A:
      - по возможности обновитесь до версии 1.19 [1]
      - в конфигурационном файле wicardd.conf в раздел настроек [reader] добавьте опции auto_update = 1, ecm_ttl = 5000, reconnect_delay = 20
      [reader]
      active = 1
      name = shara
      account = login:pass@server
      multiport = 5000
      type = newcamd525
      debug = 0
      auto_update = 1
      ecm_ttl = 5000
      reconnect_delay = 20
    5. Q: Как настроить запуск wicardd в качестве плагина графической оболочки Enigma?
      A:
      добавьте скрипт /usr/script/wicardd_cam.sh, см. файл в проекте [2].

    6. Q: Как распаковать пакет Cam-Wicardd-OpenPLI_1.19-RAED.ipk ?
      A:
      ar -xv Cam-Wicardd-OpenPLI_1.19-RAED.ipk

    7. Q: После выхода из стенд-бая пропал сигнал, не показывают даже каналы без кодировки.
      A: Возможные причины:
      - пыль, осевшая на дорожках платы -- снимите верхнюю крышку и аккуратно пропылесосьте
      - высохшие / вспучившиеся электролитические конденсаторы -- замените их.

    8. Q:  Как добавить в систему wiicard в виде плагина
      A:
      cat > /usr/script/wicardd_cam.sh << EOF
      #!/bin/sh
      CAMD_ID=7387
      CAMD_NAME="wicardd"
      CAMD_BIN=wicardd
      INFOFILE_A=ecm0.info
      INFOFILE_B=ecm1.info
      INFOFILE_C=ecm2.info
      INFOFILE_D=ecm3.info
      INFOFILE_E=ecm4.info
      INFOFILE_F=ecm5.info
      INFOFILE_LINES=1111111111000000
      REZAPP=0
      logger \$0 \$1
      echo \$0 \$1
      remove_tmp () {
      rm -rf /tmp/*.info* /tmp/*.tmp*
      }
      
      case "\$1" in
        start)
        remove_tmp
        /usr/bin/\$CAMD_BIN -d -c /etc/tuxbox/config/wicardd.conf
        ;;
        stop)
        killall -9 \$CAMD_BIN 2>/dev/null
        sleep 2
        remove_tmp
        ;;
        *)
        \$0 stop
        exit 0
        ;;
      esac
      
      exit 0
      EOF
      

    четверг, 22 июня 2017 г.

    How to debug https without root on Android

    One viable option -- use app called “Packet Capture”. This is vpn with embedded proxy & certificate authority, thanks to wich it’s capable to capture data in SSL.

    This app saved me a lot of time, and it requres no root.
    https://play.google.com/store/apps/detailsid=app.greyshirts.sslcapture&rdid=app.greyshirts.sslcapture

    At the moment still has one limitation: cannot capture SLL on non-standard port. Problem already reported to the author.