воскресенье, 20 ноября 2016 г.

Using Makefile with MSVC on example of libsqlite3_unicode

Cygwin Makefile can be used for building C programs with Visual Studio C compiler in simple regular way without .sln files.

Here I have an examaple on GitHub: https://github.com/Zensey/sqlite3_unicode
It is an minimized extension w/o external dependencies, which adds support of Unicode to sqlite3 used for search and sort operations with non-latin strings.

To build this extension under Windows platform simply run make in Cygwin terminal or run mk.cmd. Below you can see how this Makefile is arranged. Note, that variable M is used to set target architecture of executable object.


вторник, 8 ноября 2016 г.

Setup Syncthing as a service on Windows

To setup and start Syncthing as a service:
- download Syncthing, unpack
- download nssm.exe and put it into directory of syncthing
- put syncthing-svc-setup-win32.bat script into directory of syncthing
- run syncthing-svc-setup-win32.bat as Administrator

понедельник, 3 октября 2016 г.

How to enumerate serial ports using Setup API (win32)

For me using setupapi is the most strait-forward method to retrieve a list of serial ports on Windows.
I should note, that this code works well on XP and higher.



Example of output:

I'm going to offer this code to guys of node-serialport, because current method doesn't work well on some setups with antivir.


Update: The patch is ready https://github.com/Zensey/node-serialport/commit/b4c8e830d248c4f7e3be0fd0d2cd56a18159f2d9


References:
1. https://social.msdn.microsoft.com/Forums/vstudio/en-US/2555943e-0c69-4357-a85b-d6540bcaaf84/using-setupapi-to-return-all-guiddevclassdisplay?forum=vcgeneral
2. http://stackoverflow.com/a/3439805
3. https://gist.github.com/Zensey/7bd7781a28d6be306be5cdd70539dc65

SSH over TLS/SSL

This method is appliable to situation when you are at restricted network where connection to external ssh is not allowed. In addition to interactive ssh connect to server you can setup persistent reverse tunnel to server in order to login from server to client.

On server:

Install stunnel:

$ sudo apt-get install stunnel4

$ openssl genrsa 1024 > stunnel.key
$ openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt
$ cat stunnel.crt stunnel.key > stunnel.pem

$ sudo mv stunnel.pem /etc/stunnel/


Edit stunnel config file: /etc/stunnel/stunnel.conf

^where 1.1.1.1 -- is your server external ip.

Also edit /etc/default/stunnel4. Set param Enabled=1
Then start stunnel4 service.

On client:

Install socat:
$ sudo apt-get install socat

Add to file .ssh/config


Connect to your server:
$ ssh user@1.1.1.1

Reverse tunnel with AutoSSH:

First of all add user without shell:

$ sudo useradd -m -s /bin/false autossh

Now login, make a new key and copy it to the server:

$ sudo su -s /bin/bash autossh
autossh@pc:...$ cd ~
autossh@pc:~$ ssh-keygen
autossh@pc:~$ ssh-copy-id -i .ssh/id_rsa.pub remote@1.1.1.1

Also add this to .ssh/config of user autossh:


To start reverse tunnel execute:
To auto-start reverse tunnel during system start add to /etc/rc.local:

Now you can test your reverse tunnel from server:
$ ssh -p 5001 user@localhost


пятница, 5 августа 2016 г.

GOST 28147-89 cypher in JavaScript

I'd like to indroduce you my implementation of GOST 28147-89 cypher also known as Magma in JavaScript.

This cypher is used in "Carrdex IMS", an Access Contol System produced by Carddex LLC, to verify and protect identification data of MIFARE proximity cards.

My implementation is pretty small in size, but has support of Cipher Feedback Mode. Its overall 100 lines of source code and has no dependencies.

Below follows an example of how you can use it.


среда, 21 октября 2015 г.

О совместимости веб-сервисов JAX-WS и 1С


Преамбула

Существует давно известная проблема совместимости 1С с веб-сервисами на Java и не только.
После обзора материалов в интернете по практике использования веб-сервисов на платформе Java Enterprise Edition (JAX-WS) из платформы 1С к сожалению пришлось признать, что ни одной успешной попытки не зафиксировано.

Вот два показательных примера:
http://www.sql.ru/forum/1038337/web-servis-java-1s-klient-problema-peredachi-strokovogo-parametra
http://www.forum.mista.ru/topic.php?id=538212

Через два дня я сообразил в чем собственно проблема.

Суть проблемы.

В определении типов указывается явное определение пространств имен по умолчанию:

xs:schema:attributeFormDefault="unqualified"
xs:schema:elementFormDefault="qualified"


Суть проблемы заключается в том что 1С при разборе WSDL, в частности схемы данных, не обращает внимания на атрибут elementFormatDefault. Она полагает что его значение всегда равно "qualified".


По умолчанию все элементы тела SOAP-пакета имеют form="unqualified".
Это позволяет клиентам читать вложенные элементы без явного указания их неймспейса.

Вот например ответа сервиса на запрос getObjectGroup в режиме Document/Literal без явного указания неймспейсов для атрибутов сущности Object:

Как видно, неймспейс выходного документа метода getObjectGroupResponse равен http://example.ru/WebService, что является действием атрибута targetNamespace -- см. [1],
а вложенные объекты как видно без неймспейса.


Вот определение элемента <xsd:element> из книги "Справочник по XML-схемам (XSD)" с сайта MSDN [2].

 form
    Форма для элемента . Значением по умолчанию является значение атрибута elementFormDefault элемента schema, содержащего этот атрибут. Значение должно быть одной из следующих строк: «qualified» или «unqualified».
    Если значение не квалифицировано, элемент не обязательно квалифицировать с помощью префикса пространства имен.
    Если значение квалифицировано, элемент нужно квалифицировать с помощью префикса пространства имен.
    Необязательный.

А вот пример из книги [3]

These attributes both have default values of their own, which are: elementFormDefault="unqualified" and attributeFormDefault="unqualified". These values are appropriate to the case in which only the document element uses a namespace:
Since global elements and attributes must be qualified, defining this schema as a single schema requires that all the elements and attributes are locally defined.

Как утверждается, это вполне законный способ представления сущности.

Следйющий пример из [2] характерен для 1С.


Another combination, elementFormDefault="qualified" and attributeFormDefault="unqualified" matches the common case in which a namespace is attached to the root element as the default namespace that will, by definition apply to the included elements but not to the attributes. (Per the Namespaces Recommendation, the default namespace does not apply to attributes.)




Значит 1С исходит из предположения, что в XML-схеме интерфейса xs:elementFormDefault равен "qualified",
что не соответствует действительности.

Эксперимент с ручной модификацией WSDL-ки показал, что 1С-ка безразлична к параметру xs:element:form=qualified/unqualified.
следовательно реализация парсера 1С не поддерживает спецификацию XMLSchema полностью.


Симметричная проблема возникает и при разборе пакетов, сформированными 1С.
Пример из WSDL:
getObjectGroup принадлежит tns (targetNamespace="http://mycompany.ru/MyCompanySyncWebService")

Как видно,
элемент <xs:element name="type" type="xs:int"/> не принадлежит tns, он принадлежит xs (xmlns:xs="http://www.w3.org/2001/XMLSchema").
Однако 1C при этом формирует пакет следующего вида:

Что не соответствует XML-схеме и явно является багом.

Решение

Перевести JAX-WS в режим elementFormDefault="qualified" без ручного указания неймспейсов, чтобы сервис работал в стиле 1C.


В пакете веб-сервиса, допустим это "ru.company.ws", создать файл package-info.java
следующего содержания:


тогда WSDL приобрет вид :

Как видно, elementFormDefault стал равен "qualified".

Теперь сервис будет производить ответ следующего вида:

Такой вариант работы с неймспейсами на ура воспринимается 1С, ответ приходит в виде в каком 1с-ка его и рассчитывает увидеть :


Источники

1. Задание целевого пространства имен с помощью атрибута targetNamespace /
    http://msdn.microsoft.com/ru-ru/library/ms172720.aspx

2. Справочник по XML-схемам (XSD) /
   http://msdn.microsoft.com/ru-ru/library/ms256118%28v=vs.110%29.aspx

3. Xml Schema, Eric van der Vlist, глава 10.3 (To Qualify Or Not to Qualify?) /
   http://docstore.mik.ua/orelly/xml/schema/ch10_03.htm

4. http://www.sql.ru/forum/actualutils.aspx?action=gotomsg&tid=1038337&msg=16612010



log4js. how to set default logging levels for channels