Author: Oriol Rius

Benvingut Roc (17/2/16)

Reading time: < 1 minute Hi ha moments en els que sobren les paraules.

Porto un mes intentant saber com descriure aquest moment per compartir-lo amb tots vosaltres però no he estat capaç de saber com fer-ho ni tan sols d’escollir quina foto compartir. Així doncs, compartiré un petit experiment amb 1s de video dels primers dies de vida del Roc.

BENVINGUT!!!

X files: mouse pointer starts moving by itself

Reading time: 2 – 3 minutes

It seems a jog but it’s true, after buying my Toshiba Portégé Z30-A-180 PT243 I was so proud about the performance and laptop features. By default it was running a Windows 7 and after some months of using mouse pointer started moving drawing a diagonal in the screen there wasn’t a stela just a diagonal movement and during that automatic movement there were no way to get mouse control. New Toshiba laptops has a touchpad and a trackpoint a none of them was responding while that happened. Because that only happens time to time I didn’t pay attention to the problem.

Toshiba Portégé - Trackpoint and Touchpad

Last Christmas holidays I updated the laptop to Windows 10, and I was very happy to see how 99.9% of applications and configurations was maintained and running perfectly. But after some weeks mouse pointer movements return to my life, some times very often and some times less usual. But one afternoon I was totally desperate with that issue and I decided to look it up on Google. I found a thread on Toshiba support forum where more people was talking about the same issue. Proposed solutions are not perfect but helpful for me, they talk about a static electricity problem that affects trackpoint and the best option is disable it to forget the problem. Luckly I don’t use trackpoint because for me touchpad is more confortable and disable trackpoint is good enough solution in my case.

So if you have automatic mouse movements in Toshiba Portégé Z30 disable the trackpoint, don’t forget that Toshiba refers to that device as a Accupoint. Below you have a capture of the instructions to do that:

Disable Accupoint II

Disable Accupoint

I hope this blog entry has been so helpful as it has been for me.

El meu 2015

Reading time: 8 – 12 minutes

Re-editant l’article que vaig escriure per tancar l’any passat aquest any també he volgut fer un resum del que ha donat de si el 2015. Per desgràcia els compromisos personals i familiars no m’han permès publicar-lo fins a principis del 2016, tot i que jo sóc dels que pensa que més val tard que mai. He tancat un nou any on he fet més coses de les que hem pensava i quan m’he posat a rellegir les meves notes diaries, setmanals, mensuals, semestrals i anuals he al·lucinat.

A nivell personal i familiar, de nou he tingut moltíssimes oportunitats pel creixement personal. Moltíssimes ocasions on m’he hagut de sobreposar per aixecar-me i tornar a creixer un cop rera d’un altre. La millor notícia de l’any és que estem esperant el Roc. El que ha de ser el germà del Pol i que ha de neixer durant el mes de Febrer. Aquesta boníssima notícia eclipsa qualsevol altre tema i ha fet de pal de paller al voltant del qual s’han desenvolupat moltíssimes decisions durant l’any.

L’any 2015 va començar amb una bona notícia el mes de febrer perquè tornavem a estar embarassats. Però a finals de març un avortament ens va fer tornar a canviar els plans i la il·lusió es va tornar a esvaïr. Per tal de trencar una mica amb aquest amarg event ens varem escapar durant una setmaneta cap a terres del sur. Varem visitar “Puerto Banús” (Marbella), Puerto de la Duquesa, Tarifa i Gibraltar. Després d’haver passat per la història del Pol això no era res, però de nou apel·lava a la nostre fortalesa emocional. En moments com aquest és quan hem sento infinitament orgullós d’estar amb una persona tan excepcional com l’Estefania. No només ens varem aixecar sinó que ara com ús dic estem apunt de donar la benvinguda al germanet del Pol, en Roc.

Per aquestes mateixes dates la meva avia de Sant Sadurní, la Carmeta, també ens va dir adéu. Era l’últim avi que hem quedava viu. Per desgràcia ja feia una colla de mesos que anava perdent la serenitat. Per si no fos poc la meva mare i el meu germà també durant els primers 5 mesos de l’any van haver de superar temes de salut rellevants. Per sort, en ambdós casos només van ser ensurts. Curiosament per aquestes dates és sempre quan es concentren esdeveniments emocionalment més importants per la família. Coincidint a més amb l’aniversari de la mort del meu pare, la història del Pol, els 12 anys del meu accident de cotxe, el tercer aniversari del nostre casament i la cel·lebració dels meus 38 anys.

També per aquestes dates varem fer una nova escapada amb els “cunyis” (Sarai i Àlex); aquest cop a la costa brava. Concretament a Calella de Palafrugell. Un d’aquests racons que per molts cops que visitis mai et canses de tornar a visitar. No ens oblidem tampoc la caminada que varem fer l’Estefania i jo per celebrar el seu aniversari, junt amb la romeria de Torrelavit, l’Anna i el Carles ens varem arribar fins a Montserrat a peu. Tot un desafiament per nosaltres.

Per desgràcia aquest any no he pogut disfrutar tan del tennis com és habitual en mi els últims anys. Una epicondilitis m’ha tingut uns quatre mesos patint sense poder disfrutar d’aquest esport que tan m’agrada. Per sort he pogut seguir amb l’spinning i també he començat a anar a la pisicina. A finals d’any degut a compromisos professionals i també els personals que ja coneixeu he hagut de deixar l’spinning aprofitant que ja podia tornar a jugar a tennis. Així doncs, s’ha acabat l’any amb alguns quilets extres que cauran ben aviat a la que reprengui la meva activitat esportiva i professional.

De nou hem continuat invertint en la casa, no tan fort com l’any passat perquè ens haviem de recuperar una miqueta però si que hem instal·lat un descalcificador a la casa, un grup d’osmosis a la cuina, hem fet una nova habitació a l’estudi, hem renovat l’WC del pis de d’alt, hem posat una nova pergola pel cotxe i nova teulada a la caseta de fusta del jardí. El millor de tot plegat és que personalment he participat força en l’execució d’aquestes d’algunes d’aquestes tasques.

Degut a l’embaraç del Roc aquest any les vacances han estat força diferents de l’habitual. Primer de tot varem fer una petita escapadeta a Puigcerdà durant un cap de setmana i després una setmaneta a Roses, bàsicament per descansar i disfrutar de la platja a més de poder estar junts com a parella. Ja que degut a la feina he passat un estiu força ocupat. Aprofitant les vacances a Roses també ens varem acostar fins a Empuria Brava per provar el Windoor que m’havia regalat l’Estefania per l’aniversari.

A nivell de creixement personal, aquest any hem tingut un creixement important a M2M Cloud Factory i ens hem començat a consolidar com a empresa, producte i amb grans i bons clients; tot això m’ha fet evolucionar moltíssim perquè l’excés de feina i l’altíssima demanda que ha tingut la feina sobre la meva energia ha estat esgotador. A més grans persones de l’empresa ens han deixat; com ara el Marc i el Pau i això encara ha augmentat més l’exigència. Però al final tot passa per algo i sempre hi ha lectures positives a tots els esdeveniments.

Tot i amb això he pogut incorporar tres noves formacions al meu currículum, un parell de cursos de comptabilitat. Un d’introducció i l’altre d’anàlisis de balanços. Però el que realment m’ha fet creixer personalment ha estat el de Management 3.0. Un curs increible, on no només se m’han obert les portes a una nova forma de fer les coses sinó també uns contactes boníssims i la possibilitat de col·laborar dins del meu departament amb un advisor excepcional, el Gabri.

Les meves rutines matutines, fent meditació a primera hora del matí; les preguntes per enfocar el dia i després fer-ne balanç i molts d’altres exercicis que heredo de la PNL, el mindfulness i d’altres disciplines m’han anat acompanyant durant tot l’any. Estic molt content del nivell de fidelitat que tinc amb totes aquestes pràctiques i sovint n’agraeixo els beneficis.

Gràcies a l’Horizon 2020 que varem guanyar l’any passat a M2MCF ens hem pogut centrar en crear un nou producte el MIIMETIQ LITE que veurà la llum ben aviat, a més d’haver creat una nova solució basada en les Smart Glasses. Mentre treiem noves versions del “framework”. Tot plegat ha tingut força repercusió a la prensa. Personalment hem van fer una entrevista al diari Ara referent a aquests temes: L’Internet de les coses: un futur a la punta dels dits.

Professionalment també he pogut tancar finalment el projecte Empowering. Més de dos anys de projecte al costat del Xavi i la gent del BEE group (CIMNE). Finalment el meu contracte va espirar el mes de setembre i vaig poder posar punt i final a aquest projecte de Big Data tan interessant i al que li desitjo el millor. A més com a consultor de l’empresa IUL, conjuntament amb l’Adrià com a part de l’equip de Nakima també hem pogut crear un parell de productes en un temps rècord i amb una orientació tecnològica molt ben enfocada cap al IoT.

Tot plegat m’ha permès tocar força tecnologies tot i que moltes d’elles ja les coneixia. Voldria destacar-ne algunes: OpenWRT, Raspbery PI, Rancher, Ambari, NodeJS, NodeRED, ESP8266, IrDA, RF, etc. Finalment també he aprofitat per canviar de portàtil i he jubilat el Mac Book Air que tenia. Tot i ser un i7 amb 4G de RAM i 256GB de SSD, el seu rendiment és ridicul al costat del Toshiba Portégé que amb el i7 de dos cossos, 16GB de RAM i 500GB d’SSD vola. Comentar que li vaig canviar el disc mSATA que portava de serie perquè no podia ser de més de 256GB. A més aquest nou portàtil té tots els ports que hem calen integrats, fins hi tot un mòdem 4G. Cosa que hem permet no haver d’anar pel món amb la maleta plena de cables.

Abans de tancar aquest resum anual afegir que aquest any he donat tres conferències. L’Àlex i la gent de la UPC van tornar a confiar amb mi perquè a inicis d’any fes de nou una conferència per la gent del FIB Alumni, aquest cop sobre la meva SmartHome. Arran d’aquesta conferència en Marc organitzador del IoT meetup de Barcelona em va demanar que la repetís en anglès per la gent del meetup. Finalment a la Garrotxa Camp també van voler que la tornés a fer.

També gràcies al Josep Maria la gent de l’Ara van voler fer-me una entrevista a tota pàgina que va sortir el dia de la diada. Sincerament hem va agradar força com van resumir la meva vida professional sense entrar en detalls. Obviament es van deixar mil coses però fer un article sobre la meva vida professional no és senzill i crec que ho van aconseguir prou bé. A més arran d’aquest article al butlletí de la gent gran de Torrelavit també hem van voler entrevistar, cosa que hem va fer molta il·lusió.

Un altre any plè de grans events, oportunitats i emocions profundes viscudes a flor de pell. Un any que varem acomiadar amb l’Àlex i Sarai (els “cunyis”) a Benifaió amb un sopar excel·lent i de forma relaxada. Abraçant aquest 2016 plè d’esperances, il·lusió i amb moltíssimes ganes de viure i estimar. Des del cor i els braços oberts de nou: GRÀCIES!!!

Having docker in mind

Reading time: < 1 minute     Starting new year with innovation ideas in mind 🙂 [gallery size="medium" columns="2" ids="8738,8743,8744,8745"]  

Raspberry PI and OpenWRT flash partition proposal and rescue boot support for embedded systems

Reading time: 8 – 14 minutes

Introduction

Main target of this post is describe how to organize flash partitions and how to modify default OpenWRT boot sequence to support a flexible and powerful rescue mode for Raspberry PI based projects. Just to clarify the explaination. When OpenWRT is build on a flash card for Raspberry, there are only two partitions.

The first one is vFat partition with kernel, firmware and other configuration files; the second one is a ext4 partition with root filesystem. Boot sequence loads the kernel and then mount root partition and run the init script. If ext4 filesystem is corrupted or could not be mounted boot sequence is stoped and there is no solution without extracting the flash card.

Features

In this blog entry I’m going to describe a partition table and boot sequence strategy to avoid this kind of problems. Of course, there are other solutions to get similar results but I think this one is simple and powerful at the same time.

Summarizing features of this solution:

  • reduce risk when using intensive writing app
  • reduce damage risk on flash memories
  • fail-safe mode pressing a button
  • support application upgrades using opkg packages
  • support operative system upgrades using opkg packages

This solution proposal assume:

  • wear leveling protection solved by flash card
  • button connected to GPIO pins

The idea

Raspberry PI requires a vfat partition as its first flash partition where there are several required files for booting process, this is a bootloader substitution. For example, in that partition there are files like: start*.elf and bootcode.bin which are the GPU firmware and bootloaders. Another key file is kernel.img; this is the kernel used for booting. Bootloader parameters for kernel booting are in a file called cmdline.txt and firmware parameters are set in config.txt.

At this point the most important think to take into account is kernel.img file and cmdline parameters. Because kernel is loaded and executed by default with cmdline parameters set. When kernel boot process finishes root filesystem and init process sequence will be figured out from cmdline parameters.

At this point take a look on proposed partition table could be useful: (spaces are just as a reference, use what you need)

p1 - vfat (~50MB)
p2 - ext4 - operative system base (read-only) (~150MB)
p3 - ext4 - operative system (read-write) (~250MB)
p4 - logical partition
  p4.1 - ext4 - your_application files (usually read-only)
  p4.2 - ext4 - your_application data (usually read-write)

Fail-safe boot process key is partition p2 where a minimal OpenWRT installation with a modified init sequence is found. Main idea here is detect if a GPIO shortcut is done, usually this is done just pressing a physical button and you can interact with the user emitting some beep, for example, you can tell the user when you are waiting for button press using a beep and then emit two beeps when button press is detected or nothing if no button is pressed in 3 seconds. Finally the idea is detect if you need a regular boot or a fail-safe boot.

My suggestion for minimal OpenWRT is a small footprint installation of OpenWRT without kernel modules, just the monolitic kernel loaded. Then reduce init sequence to the minimum and add fail-safe logic (GPIO button capture); if button is pressed stop boot sequence and give a shell to the user. Regular way will be invoke init file of the rootfs (p3 in the partition table).

I think the idea is simple and the complexity is reduced in two parts both of them are the init file. To be more precise the p2 partition table has its own init file and p3 the other one. p2 init file load the minimum hardware to control button and give rescue environment when it’s needed. And p3 init file mounts read-write partition and the regular filesystem with regular boot processes and all kind of stuff that you need.

Final notes

I know this is not a very practical post, but my intention is only share some ideas that I have in mind. I spend most of my time designing architectures and I think this is a very powerful architecture of a boot sequence for some professional projects based on Raspberry PI and OpenWRT.

The best way to do what I describe in this post is putting p2 in a initrd file which is referenced in kernel parameters. Because then all read-only system is a RAM partition and rootfs init file has the PID 1 dropping dual-init file complexity. But I decided to modify this part because in the past I had some problems creating initrd files specially when required space for that partition is bigger than RAM. Anyway it’s important to take in account that initrd files has the same purpose as the proposed p2 partition.

Useful links

Small recap of web shell applications

Reading time: 2 – 2 minutes

Lately I found some useful web applications that publish a terminal application. This is very useful when you are traveling or you have a remote server which you want to maintain or access from anywhere. Also another interesting use of this kind of applications is as a terminal for embedded devices.

I tried to use them as my default applications but all of them have the same problem: keyboard shortcuts conflict with the browser. I’m very used to use a lot of shortcuts to manage my terminal application and remote shell and this is a problem because most of the shortcuts are redefined by your browser. May be it’s possible to disable browser shortcuts when you are using this kind of web applications but I didn’t find how.

I hope this small list is as much useful for you as it is for me:

  • Wetty = Web + tty (the best one IMHO)

wetty

ajaxterm

anyterm

gateone

Entrevista en el “Ara”, la película “The Shift” y meditación contemplativa (budismo Kadampa)

Reading time: 6 – 9 minutes

Un "Geek" de pura raça

En realidad esta entrada será un poco un cajón desastre de cositas que creo que son interesantes para compartir. Lo escribo en castellano porqué quiero clasificarlo en la sección de crecimiento personal y ahí en general escribo en esta lengua.


Para empezar quería compartir una entrevista que me hicieron en el periódoco “Ara” y que salió publicada por “La Diada”. Aquí tengo que agradecer a Josep María que me recomendara para ser entrevistado en el especial “La Catalunya que empeny”.  La verdad es que estas cosas no tienen ninguna, o muy poca, trascendencía pero hacen ilusión. Es como un reconocimiento al trabajo hecho y eso es de agradecer. Tanto al periódico como a Josep María. Si a alguien le interesa hay que decir que esta en catalán y aquí teneis un enlace en PDF.

También comentar que hace un tiempo me hicieron otra entrevista en este mismo periódoco. En este caso la entrevista era relativa a un tema de mi trabajo. Como en su momento no compartí este artículo con vosotros aprovecho esta ocasión para hacerlo. Para leerlo mejor os recomiendo clicar encima de la imagen.

Internet de les coses un futur a la punta dels dits

Seguidamente quiero compartir con vosotros una película llamada “El Cambio” (The Shift, en inglés [IMDB]). Creo que es una gran película para reflexionar y hacer un examen de conciencia. A menudo nuestra vida es una carrera sin sentido. Digo esto porqué nos descubrimos habiendo renunciado a muchas de nuestras ilusiones y ni tan sólo nos hemos dado cuenta. Creo que el día a día se convierte en nuestro enemigo y esto es justo lo que personalmente hace unos 5 años que estoy trabajando muy profundamente. En mi próxima entrada os explicaré como lo hago para mantener el foco hacia mis objetivos, seguir mejornado cada día como persona y proyectarme hacia el futuro tal y como me gustaría ser. Evidentemente para leer mis articulos no hace falta hacer ningún tipo de tarea previa pero haber visto esta película creo que puede ayudar y mucho.

En la película el doctor Wayne Dyer se dedica a narrar cuales son las lecciones de vida que ha ido adquiriendo al hacerse mayor. Famoso por ser un escritor de “best sellers” relacionados con el desarrollo personal; el doctor nos recuerda lecciones tan importantes como el cambio de valores que sufrimos al hacernos mayores. Creo que es una gran película para plantearse el proposito de nuestra vida. Bajo mi punto de vista esta es una de esas películas que debería ver todo el mundo. Para que la película sea más comprensible y menos densa la narrativa se mezcla con diferentes historías que comparten un escenario común pero que no llegan a mezclarse. Creo que las historias son ideales para amenizar las 2h de película y entender de forma más profunda lo que nos esta explicando el doctor.

Finalmente para cerrar esta entrada quería comentaros que este mismo Viernes fui a una clase de meditación que se celebró en Vilafranca. Hace mucho tiempo que estoy alerta de este tipo de eventos porqué me gustaría ampliar mis horizontes en este tema. Hace ya unos tres años que practico a diario la meditación pero me gustaría compartir esto con más personas cercanas. Pues bien, quería explicaros que la meditación realizada fue de tipo contemplativa. No es la primera vez que practico meditación de este tipo aunque la que practico más a menudo es el Mindfulness. Lo que si que es la primera vez que me pasa es que es recibir doctrinas budistas durante la clase. Concretamente de budismo Kadampa rama que tiene como guía espiritual el Geshe Kelsang Gyatso.

La verdad es que no me sentí del todo cómodo con el tipo de enseñanzas que se trasmiten. Primeramente el profesor tenía una forma de compartir el contenido muy caótica y a pesar de verse claramente que era una persona muy comprometida y profundamente agradable; tenía la mala costumbre de mirar sólo a una de las personas de la clase. Tanto es así que había momentos en que se refería sólo a ella obviamento el resto de alumnos. Además nos hablaba con una serie de prejuicios sobre nuestros comportamientos asumiendo ciertos hechos que llegaban a ser molestos.  Creo que es bueno preguntar cuando tienes un grupo muy reducido para saber cual es el nivel de los presentes para así poder adaptar el mensaje al público. Estoy convencido que todos llevábamos tiempo experimentando con la meditación pero él asumía una y otra vez que nadie había hecho absolutamente nada antes y que no sabiamos nada del budismo ni de meditación.

kmc-bcn-meditacion

Entrando en los contenidos del budismo Kadampa, por lo menos como yo los recibí el Viernes, tengo que decir que no fueron muy integradores. Es decir, siempre se me ha presentado el budismo como algo muy diferente a las religiones occidentales, de hecho, a menudo los profesores que he tenido me han dicho que es una filosofía y no una religión. Como tal hasta ahora se me habían presentado areas y espacios de meditación que siempre eran integradoras y abiertas para adaptarse de forma amable. Dicho de otra forma nunca había tenido profesores que me transmitieran que el budismo prohibía hacer, escuchar, decir, … ciertas cosas. Me ahorraré los detalles porqué no quiero abrir ningún debate y obviamente tengo la capacidad de respetar todos los puntos de vista. Otra cosa es que esto me anime a seguir escuchando puntos de vista que no les importa escuchar el de los demás.

Quiero dejar claro que no fue una experiencia negativa. Disfruté de la meditación y salí en un estado de relajación y aceptación que me permitieron conectar con mi paz interior. Pero no me sentí con ánimos de volver otro día. Seguramente le de otra oportunidad a esta rama del budismo pero intetaré ver otro punta de vista; quizá el de algún profesor más experimentado o con una oratoria que me haga sentir más cómodo.

Cursos de Management 3.0 y Workout

Reading time: 3 – 5 minutes

Management 3.0

Esta semana he disfrutado de dos curso que os quería recomendar. Basados en los libros de Jurgen Appelo el curso Management 3.0 y el Workout. Los cursos son mucho más que un resumen de los libros. He tenido la suerte de tener tres profesores Angel Medinilla, Angel Diaz-Maroto y Gabriel Prat; los tres con una amplia experiencia en el mundo del management y especialmente el mundo ágil. Su forma de dar el curso es muy dinámica y participativa, llena de historias y ejemplos. Esto ayuda a convertir el curso en una experiencia que como seguro sabeis es la mejor forma de aprender. Se nota en muchísimos casos un amplio background en técnicas innovadoras como coaching y programación neurolingüística. El curso me ha encatado especialmente porqué no sólo la forma lo lleva al mejor nivel de otros muchos cursos que he hecho; también el contenido en este caso encaja perfectamente a los retos a los que me enfrento día a día. Además los compañeros tienían muchísimos escenarios afines a los mios y esto ayuda a tener intereses alineados.

Es espectacular ver como la dirección de equipos tiene que ver cada vez más con la auto-gestión acompañada de un buen liderazgo. Aparcando el autoritarismo y las soluciones simplistas a un lado. Usando los procesos en su justa medida, es decir como una herramienta no como un fin. Además de hacer un modelado que por fin tiene en cuenta la realidad, me refiero a entender a los equipos como sistemas complejos. Sistemas que no se pueden solucionar con simples formulas de causa-efecto o pretender conseguir cosas complejas con incentivos simples, la típica paradoja de la zanaoria. Es realmente fantástico descubrir que hay otra dimensión, tal y como se comentaba en el curso los equipos tienen tres dimensiones y su compleijidad es infinita por lo tanto sólo desde la complejidad seremos capaces de alinear objetivos con la empresa.

Pretender hacer un resumen del curso en esta pequeña recomendación creo que es una tontería así que me conformo con recomendar a todos los gestores de equipos, técnicos y no técnicos que se permitan explorar este fantástico mundo del Management 3.0 para ser capaces de descubrir que se puede crecer más allá de la era de los procesos y las certificaciones. Estamos viviendo la revolución del conocimiento los métodos usados para dirigir las anteriores revoluciones no funcionan en esta era. Hay que saber encontrar un punto de equilibrio que es mucho más complejo de alcanzar que los que se habían planteado anteriormente, ahora se trata de que los equipos de personas rindan y para esto no es suficiente con guiarnos únicamente con lo que dicen los indicadores. No olvidemos que hay que ir muy en cuidado al medir porqué podríamos encontrar lo que queremos. Esta es una de las muchas lecciones que no entiendes hasta que eres víctima de ella o tienes la suerte de que la integres gracias a un curso como este.

Para cerrar quiero añadir que el coste del curso ha sido una inversión buenísima, la experiencia y empatía que son capaces de transmitir estos tres profesores es increible. Así pues recomiendo a todo el mundo que tenga la necesidad de gestionar a un grupo de personas que inverta su energía en aprender estas técnicas, sinceramente se hace difícil pensar en innovación sin haber conocido este mundo antes y hacerlo a través de personas con una experiencia tan dilatada; creo que ha sido una suerte.

Secure download URLs with expiration time

Reading time: 23 – 38 minutes

Requirements

Imagine a HTTP server with those restrictions:

  • only specific files can be downloaded
  • with a limited time (expiration date)
  • an ID allows to trace who download files
  • with minimal maintenance and dependencies (no databases, or things like that)

the base of the solution that I designed is the URL format:

http://URL_HOST/<signature>/<customer_id>/<expire_date>/<path_n_file>
  • signature: is calculated with the next formula, given a “seed”
    • seed = “This is just a random text.”
    • str = customer_id + expire_date + path_n_file
    • signature = encode_base64( hmac_sha1( seed, str))
  • customer_id: just an arbitrary identifier when you want to distinguish who use the URL
  • expire_date: when the generated URL stops working
  • path_n_file: relative path in your private repository and the file to share

Understanding the ideas explained before I think it’s enough to understand what is the goal of the solution. I developed the solution using NGINX and LUA. But the NGINX version used is not the default version is a very patched version called Openresty. This version is specially famous because some important Chinese webs works with that, for instance, Taobao.com

Expiration URL solution Architecture schema

In the above schema there is a master who wants to share a file which is in the internal private repository, but the file has a time restriction and the URL is only for that customer. Then using the command line admin creates a unique URL with desired constrains (expiration date, customer to share and file to share). Next step is send the URL to the customer’s user. When the URL is requested NGINX server evaluates the URL and returns desired file only if the user has a valid URL. It means the URL is not expired, the file already exists, the customer identification is valid and the signature is not modified.

NGINX Configuration

server {
 server_name downloads.local;

 location ~ ^/(?<signature>[^/]+)/(?<customer_id>[^/]+)/(?<expire_date>[^/]+)/(?<path_n_file>.*)$ {
 content_by_lua_file "lua/get_file.lua";
 }

 location / {
 return 403;
 }
}

This is the server part of the NGINX configuration file, the rest of the file can as you want. Understanding this file is really simple, because the “server_name” works as always. Then only locations command are relevant. First “location” is just a regular expression which identifies the relevant variables of the URL and passes them to the LUA script. All other URLs that doesn’t match with the URI pattern fall in path “/” and the response is always “Forbiden” (HTTP 403 code). Then magics happen all in LUA code.

LUA scripts

There are some LUA files required:

  • create_secure_link.lua: creates secure URLs
  • get_file.lua: evaluates URLs and serves content of the required file
  • lib.lua: module developed to reuse code between other lua files
  • sha1.lua: SHA-1 secure hash computation, and HMAC-SHA1 signature computation in Lua (get from https://github.com/kikito/sha.lua)

It’s required to configure “lib.lua” file, at the beginning of the file are three variables to set up:

lib.secret = "This is just a long string to set a seed"
lib.base_url = "http://downloads.local/"
lib.base_dir = "/tmp/downloads/"

Create secure URLs is really simple, take look of the command parameters:

$ ./create_secure_link.lua 

 ./create_secure_link.lua <customer_id> <expiration_date> <relative_path/filename>

Create URLs with expiration date.

 customer_id: any string identifying the customer who wants the URL
 expiration_date: when URL has to expire, format: YYYY-MM-DDTHH:MM
 relative_path/filename: relative path to file to transfer, base path is: /tmp/downloads/

Run example:

$ mkdir -p /tmp/downloads/dir1
$ echo hello > /tmp/downloads/dir1/example1.txt
$ ./create_secure_link.lua acme 2015-08-15T20:30 dir1/example1.txt
http://downloads.local/YjZhNDAzZDY0/acme/2015-08-15T20:30/dir1/example1.txt
$ date
Wed Aug 12 20:27:14 CEST 2015
$ curl http://downloads.local:55080/YjZhNDAzZDY0/acme/2015-08-15T20:30/dir1/example1.txt
hello
$ date
Wed Aug 12 20:31:40 CEST 2015
$ curl http://downloads.local:55080/YjZhNDAzZDY0/acme/2015-08-15T20:30/dir1/example1.txt
Link expired

Little video demostration

Resources

Disclaimer and gratefulness

15 anys amb el blog online

Reading time: 1 – 2 minutes

Avui dia 31 de juliol fa 15 anys que vaig decidir-me a escriure el meu primer article al blog. Com passa el temps! cada cop que penso que el dia que vaig començar no sabia ni el que era un blog i que l’anomenava “digital diary”. Sovint escric tot dient que tinc l’agenda plena i que no sé d’on treure temps per escriure. Doncs bé, després d’un periode molt i molt llarg de temps on el meu vincle en diversos projectes m’impedia dedicar temps al blog puc dir que tot i tenir una llista de desitjos quasi infinita. Ja no tinc obligacions fortes en projectes fora dels horaris convencionals. Així doncs, en pocs mesos disposaré de temps per gestionar en els meus interessos personals cosa que fins ara no tenia.

15th-anniversary

De moment el meu proposit serà anar publicant alguns dels molts articles que tinc a mig fer i pendents de fer publics. Desitjo que aquest proper any la freqüència de publicacions al blog canviï dràsticament. Creuem els dits perquè pugui mantenir el desig.

Gràcies a tots els fidels seguidors que teniu la paciència d’anar-me seguint.

Scroll to Top