Snippets / Gists

A snippet or a gist generally refers to a small piece or fragment of code, text, or information.

They are often used to demonstrate or illustrate a particular programming concept, syntax, or technique.
Their characteristic is of being small, self-contained pieces of code or information that can be easily shared or reused.

Why did I publish this page? Well, think of it as my digital attic – a curated collection of things I've decided I don't care about enough to keep to myself.

It's not a mess; it's avant-garde minimalism with a touch of 'selective enthusiasm'. Consider it a page-turner for the truly discerning audience who appreciates the art of not caring too much.
Welcome to the Chronicles of Nonchalance!

Elasticsearch Log Analysis

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/elastic/go-elasticsearch/v8"
	"github.com/oschwald/geoip2-golang"
)

type logline struct {
	IP              net.IP    `json:"ip"`
	Latitude        float64   `json:"latitude"`
	Longitude       float64   `json:"longitude"`
	Country         string    `json:"country"`
	ASN             int       `json:"asn"`
	ASNOrganization string    `json:"asn_organization"`
	Timestamp       time.Time `json:"timestamp"`
	Frontend        string    `json:"frontend"`
	Backend         string    `json:"backend"`
	Server          string    `json:"server"`
	ResponseCode    int       `json:"response_code"`
	Host            string    `json:"host"`
	URL             string    `json:"url"`
	UserAgent       string    `json:"user_agent"`
	Method          string    `json:"method"`
	Protocol        string    `json:"protocol"`
}

func main() {
	file, err := os.Open("haproxy.log")
	if err != nil {
		log.Println(err.Error())
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)

	dbasn, err := geoip2.Open("GeoLite2-ASN.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer dbasn.Close()

	dbcity, err := geoip2.Open("GeoLite2-City.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer dbcity.Close()

	es, err := elasticsearch.NewClient(elasticsearch.Config{
		Addresses: []string{
			"https://<host_1>",
			"https://<host_2>",
            "...",
			"https://<host_n>",
		},
	})
	if err != nil {
		log.Fatalf("Error creating the client: %s", err)
	}

	_, err = es.Ping()
	if err != nil {
		log.Fatalf("Error pinging the elasticsearch servers: %s", err)
	}

	es.Indices.Create("incident")

	for scanner.Scan() {
		log := scanner.Text()
		temp := strings.SplitN(log, ":", 4)
		if len(temp) < 4 {
			continue
		}
		log = strings.TrimLeft(temp[3], " ")

		// IP
		temp = strings.SplitN(log, ":", 2)
		if len(temp) < 2 {
			continue
		}
		ip := net.ParseIP(temp[0])
		temp2 := strings.SplitN(temp[1], "[", 2)
		if len(temp2) < 2 {
			continue
		}
		log = temp2[1]

		// Country, Latitude, Longitude
		record, err := dbcity.City(ip)
		if err != nil {
			fmt.Println(err.Error())
		}
		country := record.Country.IsoCode
		latitude := record.Location.Latitude
		longitude := record.Location.Longitude

		// Autonomous System Number, Autonomous System Organization
		recordASN, err := dbasn.ASN(ip)
		if err != nil {
			fmt.Println(err.Error())
		}
		asn := recordASN.AutonomousSystemNumber
		asnOrg := recordASN.AutonomousSystemOrganization

		// Timestamp
		temp = strings.SplitN(log, "]", 2)
		layout := "02/Jan/2006:15:04:05.000"
		timestamp, err := time.Parse(layout, temp[0])
		if err != nil {
			fmt.Println(err.Error())
		}
		log = strings.TrimLeft(temp[1], " ")

		// Frontend
		temp = strings.SplitN(log, " ", 2)
		frontend := strings.TrimRight(temp[0], "~")
		log = temp[1]

		// Backend/Server
		temp = strings.SplitN(log, " ", 3)
		temp2 = strings.SplitN(temp[0], "/", 2)
		if len(temp2) < 2 {
			continue
		}
		backend := temp2[0]
		server := temp2[1]
		log = temp[2]

		// Response Code
		temp = strings.SplitN(log, " ", 7)
		responseCode, err := strconv.Atoi(temp[0])
		if err != nil {
			continue
		}
		log = temp[6]

		// {Host|URL|UserAgent}
		temp = strings.SplitN(log, "{", 2)
		if len(temp) < 2 {
			continue
		}
		log = temp[1]
		temp = strings.SplitN(log, "}", 2)
		temp2 = strings.SplitN(temp[0], "|", 3)
		host := temp2[0]
		userAgent := temp2[2]
		log = strings.TrimLeft(temp[1], " ")

		// Method Url Protocol
		temp = strings.SplitN(log, " ", 3)
		if len(temp) < 3 {
			continue
		}
		method := strings.TrimLeft(temp[0], "\"")
		url := strings.TrimLeft(temp[1], "\"")
		protocol := strings.TrimRight(temp[2], "\"")

		logline := logline{
			IP:              ip,
			Latitude:        latitude,
			Longitude:       longitude,
			Country:         country,
			ASN:             int(asn),
			ASNOrganization: asnOrg,
			Timestamp:       timestamp,
			Frontend:        frontend,
			Backend:         backend,
			Server:          server,
			ResponseCode:    responseCode,
			Host:            host,
			URL:             url,
			UserAgent:       userAgent,
			Method:          method,
			Protocol:        protocol,
		}

		data, _ := json.Marshal(logline)
		es.Index("incident", strings.NewReader(string(data)))
	}

	if err := scanner.Err(); err != nil {
		log.Println(err.Error())
	}
}

mdadm Recovery

package main

import (
	"log"
	"os"
	"os/exec"
)

func main() {
	input := []string{
		"/dev/sda",
		"/dev/sdb1",
		"/dev/sdd",
		"/dev/sde",
		"/dev/sdf",
		"missing",
	}
	permutations := generatePermutations(input)

	for _, perm := range permutations {
		if perm[4] != "missing" {
			continue
		}

		cmd := exec.Command(
			"mdadm", "--create", "/dev/md0",
			"--level=6", "--raid-devices=6",
			perm[0], perm[1], perm[2], perm[3], perm[4], perm[5],
			"--assume-clean", "--readonly",
		)
		log.Println(cmd)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		if err != nil {
			if exitError, ok := err.(*exec.ExitError); ok {
				log.Printf("Command mdadm create finished with error (%d): \n\t%v\n", exitError.ExitCode(), exitError)
			} else {
				log.Println(err.Error())
			}
		}

		cmd = exec.Command(
			"mount", "/dev/md0", "/root/data",
		)
		log.Println(cmd)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err = cmd.Run()
		if err != nil {
			if exitError, ok := err.(*exec.ExitError); ok {
				log.Printf("Command mount finished with error (%d): \n\t%v\n", exitError.ExitCode(), exitError)
			} else {
				log.Println(err.Error())
			}
		} else {
			log.Println("WOW")
			log.Println(perm)
			return
		}

		cmd = exec.Command(
			"mdadm", "--stop", "/dev/md0",
		)
		log.Println(cmd)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err = cmd.Run()
		if err != nil {
			if exitError, ok := err.(*exec.ExitError); ok {
				log.Printf("Command mdadm stop finished with error (%d): \n\t%v\n", exitError.ExitCode(), exitError)
			} else {
				log.Println(err.Error())
			}
			return
		}
	}
}

func generatePermutations(arr []string) [][]string {
	var helper func([]string, int)
	res := [][]string{}

	helper = func(arr []string, n int) {
		if n == 1 {
			tmp := make([]string, len(arr))
			copy(tmp, arr)
			res = append(res, tmp)
		} else {
			for i := 0; i < n; i++ {
				helper(arr, n-1)
				if n%2 == 1 {
					tmp := arr[i]
					arr[i] = arr[n-1]
					arr[n-1] = tmp
				} else {
					tmp := arr[0]
					arr[0] = arr[n-1]
					arr[n-1] = tmp
				}
			}
		}
	}
	helper(arr, len(arr))
	return res
}

Haversine

<?php

declare(strict_types=1);

namespace Task_2\Exceptions;

use Exception;
use Throwable;

class OutOfRangeLatitude extends Exception
{
    private const MESSAGE = 'Latitude must be with the -90°,90° range';

    public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
    {
        $message = self::MESSAGE . ': ' . $message;
        parent::__construct($message, $code, $previous);
    }
}
<?php

declare(strict_types=1);

namespace Task_2\Exceptions;

use Exception;
use Throwable;

class OutOfRangeLongitude extends Exception
{
    private const MESSAGE = 'Longitude must be with the -180°,180° range';

    public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
    {
        $message = self::MESSAGE . ': ' . $message;
        parent::__construct($message, $code, $previous);
    }
}
<?php

declare(strict_types=1);

namespace Task_2;

use Task_2\Exceptions\OutOfRangeLatitude;
use Task_2\Exceptions\OutOfRangeLongitude;

class Haversine
{
    private const EARTH_RADIUS = 6371000;
    private const COVERAGE_LIMIT = 10000;

    public function __construct(
        private float $lat1,
        private float $lng1,
        private float $lat2,
        private float $lng2
    ) {
        $this->validatesInput();
        $this->convertsDegreesToRadiants();
    }

    private function validatesInput(): void {
        if ($this->lat1 < -90 || $this->lat1 > 90) {
            throw new OutOfRangeLatitude((string)$this->lat1);
        }
        if ($this->lat2 < -90 || $this->lat2 > 90) {
            throw new OutOfRangeLatitude((string)$this->lat2);
        }

        if ($this->lng1 < -180 || $this->lng1 > 180) {
            throw new OutOfRangeLongitude((string)$this->lng1);
        }
        if ($this->lng2 < -180 || $this->lng2 > 180) {
            throw new OutOfRangeLongitude((string)$this->lng2);
        }
    }

    private function convertsDegreesToRadiants(): void {
        $this->lat1 = deg2rad($this->lat1);
        $this->lat2 = deg2rad($this->lat2);
        $this->lng1 = deg2rad($this->lng1);
        $this->lng2 = deg2rad($this->lng2);
    }

    /**
     * Calculate the distance between the given coordinates using the Haversine formula.
     *
     * The formula is shamelessly stolen from wikipedia (https://en.wikipedia.org/wiki/Haversine_formula).
     * The resulting value might be right or not.
     * At first glance, nothing indicates something deeply wrong.
     *
     * Note of approximation: earth is not perfectly round,
     * at the 45th parallel (used in the test cases) corrective factors might be necessary.
     *
     * @return float
     */
    public function calculate(): float
    {
        $latitudeDelta = $this->lat2 - $this->lat1;
        $longitudeDelta = $this->lng2 - $this->lng1;

        $partial1 = pow(sin(($latitudeDelta) / 2), 2);
        $partial2 = cos($this->lat1) * cos($this->lat2) * pow(sin(($longitudeDelta) / 2), 2);

        return 2 * self::EARTH_RADIUS * asin(sqrt($partial1 + $partial2));
    }

    public function isCovered(): bool
    {
        return $this->calculate() <= self::COVERAGE_LIMIT;
    }
}
<?php

namespace Task_2;

use PHPUnit\Framework\TestCase;

class HaversineTest extends TestCase
{
    private array $locations = [
        ['id' => 1010, 'zip_code' => '37169', 'lat' => 45.35, 'lng' => 10.84],
        ['id' => 1011, 'zip_code' => '37221', 'lat' => 45.44, 'lng' => 10.99],
        ['id' => 1012, 'zip_code' => '37229', 'lat' => 45.44, 'lng' => 11.00],
        ['id' => 1013, 'zip_code' => '37233', 'lat' => 45.43, 'lng' => 11.02],
    ];

    private array $shoppers = [
        ['id' => 'X1', 'lat' => 45.46, 'lng' => 11.03, 'enabled' => true],
        ['id' => 'X2', 'lat' => 45.46, 'lng' => 10.12, 'enabled' => true],
        ['id' => 'X3', 'lat' => 45.34, 'lng' => 10.81, 'enabled' => true],
        ['id' => 'X4', 'lat' => 45.76, 'lng' => 10.57, 'enabled' => true],
        ['id' => 'X5', 'lat' => 45.34, 'lng' => 10.63, 'enabled' => true],
        ['id' => 'X6', 'lat' => 45.42, 'lng' => 10.81, 'enabled' => true],
        ['id' => 'X7', 'lat' => 45.34, 'lng' => 10.94, 'enabled' => true],
    ];

    public function testCalculate(): void
    {
        foreach ($this->locations as $location) {
            foreach ($this->shoppers as $shopper) {
                $haversine = new Haversine($location['lat'], $location['lng'], $shopper['lat'], $shopper['lng']);
                $this->assertIsFloat($haversine->calculate());
                $this->assertTrue($haversine->calculate() > 0);
            }
        }
    }

    public function testIsCovered(): void
    {
        $totalCovered = 0;
        $shopperPercentage = [];

        foreach ($this->shoppers as $shopper) {
            $shopperCount = 0;

            foreach ($this->locations as $location) {
                $haversine = new Haversine($location['lat'], $location['lng'], $shopper['lat'], $shopper['lng']);
                if ($haversine->isCovered()) {
                    $totalCovered++;
                    $shopperCount++;
                }
            }

            $shopperPercentage[] = [
                'shopper_id' => $shopper['id'],
                'coverage' => $shopperCount / count($this->locations) * 100,
            ];
        }

        usort($shopperPercentage, function ($shopperA, $shopperB) {
            if ($shopperA['coverage'] < $shopperB['coverage']) {
                return 1;
            } elseif ($shopperA['coverage'] > $shopperB['coverage']) {
                return -1;
            } else {
                return 0;
            }
        });

        print_r(json_encode($shopperPercentage, JSON_PRETTY_PRINT));
        ob_flush();

        $this->assertEquals(6, $totalCovered);
    }
}

Abstract Fs

<?php

declare(strict_types=1);

namespace Task_1\Exceptions;

use Exception;
use Throwable;

class IllegalNameException extends Exception
{
    private const MESSAGE = 'Directory names consist only of English alphabet letters';

    public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
    {
        $message = self::MESSAGE . ': ' . $message;
        parent::__construct($message, $code, $previous);
    }
}
<?php

declare(strict_types=1);

namespace Task_1\Exceptions;

use Exception;
use Throwable;

class InvalidRootException extends Exception
{
    private const MESSAGE = 'Root must be /';

    public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
    {
        $message = self::MESSAGE . ': ' . $message;
        parent::__construct($message, $code, $previous);
    }
}
<?php

declare(strict_types=1);

namespace Task_1;

interface FilesystemAdapter
{
    public function cd(string $path): void;

    public function getCurrentPath(): string;
}
<?php

declare(strict_types=1);

namespace Task_1;

use Task_1\Exceptions\IllegalNameException;
use Task_1\Exceptions\InvalidRootException;

class Path implements FilesystemAdapter
{
    private string $currentPath;
    private string $nextPath;

    public function __construct(string $path = '')
    {
        $this->cd($path);
    }

    /**
     * Change the current path of the class.
     *
     * Normalize the path in order to remove the "traverse to parent directory" characters.
     * Validates the given path for correctness (with basic regexes).
     *
     * @param string $path
     * @return void
     * @throws IllegalNameException
     * @throws InvalidRootException
     */
    public function cd(string $path): void
    {
        $this->nextPath = $this->getCurrentPath() . '/' . $this->normalizeSlashes($path);

        $this->validateNextPath();
        $this->normalizeNextPath();
        $this->validateNormalizedPath();

        $this->currentPath = $this->nextPath;
    }

    public function getCurrentPath(): string
    {
        return $this->currentPath ?? '';
    }

    private function validateNextPath(): void
    {
        if ($this->nextPath === '/') {
            return;
        }

        if (!str_starts_with($this->nextPath, '/')) {
            throw new InvalidRootException($this->nextPath);
        }

        if (preg_match('/^(\/([A-Za-z]+|\.\.))+\/?$/', $this->nextPath) !== 1) {
            throw new IllegalNameException($this->nextPath);
        }
    }

    private function validateNormalizedPath(): void
    {
        if ($this->nextPath === '/') {
            return;
        }

        if (!str_starts_with($this->nextPath, '/')) {
            throw new InvalidRootException($this->nextPath);
        }

        if (preg_match('/^(\/[A-Za-z]+)+$/', $this->nextPath) !== 1) {
            throw new IllegalNameException($this->nextPath);
        }
    }

    private function normalizeNextPath(): void
    {
        $count = 0;
        $this->nextPath = preg_replace('/\/[A-Za-z]+\/\.\./', '', $this->nextPath, 1, $count);

        if ($this->nextPath === '') {
            $this->nextPath = '/';
        }

        if ($count !== 0) {
            $this->normalizeNextPath();
        }
    }

    private function normalizeSlashes(string $path): string
    {
        return ltrim(rtrim($path, '/'), '/');
    }
}
<?php

namespace Task_1;

use PHPUnit\Framework\TestCase;

class PathTest extends TestCase
{

    public function testGiven(): void
    {
        $path = new Path('/a/b/c/d');
        $path->cd('../x');
        $this->assertEquals('/a/b/c/x', $path->getCurrentPath());
    }

    public function testRoot(): void
    {
        $path = new Path();
        $this->assertEquals('/', $path->getCurrentPath());

        $path = new Path('');
        $this->assertEquals('/', $path->getCurrentPath());

        $path = new Path('/');
        $this->assertEquals('/', $path->getCurrentPath());
    }

    public function testEscape(): void
    {
        $this->expectException('Task_1\Exceptions\IllegalNameException');
        new Path('/../../');
    }

    public function testMultipleTraversals(): void
    {
        $path = new Path('/aa/bb/../cc/');
        $path->cd('../xx/dd/');
        $this->assertEquals('/aa/xx/dd', $path->getCurrentPath());
    }
}

Vuln Server

#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>

#define IP_ADDRESS  ""
#define PORT_NUMBER 31337
#define BUF_SIZE    2048

void process(SOCKET);

void main(int argc, char *argv[]) {
	SOCKET sock;
	SOCKET new_sock;
	struct sockaddr_in sa;
	WSADATA wsaData;

	if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
		fprintf(stderr,"WSAStartup() failed");
		exit(1);
	}

	printf("Initializing the server...\n");
	memset(&sa, 0, sizeof(struct sockaddr_in));

	sa.sin_family = AF_INET;
    // bind to a specific address
	//sa.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    // bind to all addresses
	sa.sin_addr.s_addr = htonl(INADDR_ANY);
	sa.sin_port = htons(PORT_NUMBER);
	sock = socket(AF_INET, SOCK_STREAM, 0);

	if (sock < 0) {
		printf("Could not create socket server...\n");
		exit(1);
	}
		
	if (bind(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		closesocket(sock);
		printf("Could not bind socket...\n");
		exit(1);
	}

	printf("Listening for connections...\n");
	listen(sock, 10);
	while (1) {
		new_sock = accept(sock, NULL, NULL);
    	printf("Client connected\n");

		if (new_sock < 0) {
			printf("Error waiting for new connection!\n");
			exit(1);
		}
		
		process(new_sock);
		closesocket(new_sock);
	}
}

void process(SOCKET sock) {
    char* tmp;
	char buf[1024]; // whoops! should've used the defined BUF_SIZE here
    int i;
    
	memset(&buf, 0, sizeof(buf));
	tmp = malloc(BUF_SIZE);

    i = recv(sock, tmp, BUF_SIZE-1, 0);
    tmp[i+1] = '\x00';
    
    // this would be alright if buf and tmp were the same size
    strcpy(&buf, tmp);

    free(tmp);
	// print data
	printf("Got message:\n%s\n", buf);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>

#define IP_ADDRESS  "127.0.0.1"
#define PORT_NUMBER 31337
#define BUF_SIZE    2048

void process(int);

int main(int argc, char *argv[]) {
    int sock;
    int new_sock;
    int cli_len;
    struct sockaddr_in sa, ca;

    printf("Initializing the server...\n");
    memset(&sa, 0, sizeof(struct sockaddr_in));
    memset(&ca, 0, sizeof(struct sockaddr_in));

    sa.sin_family = AF_INET;
    // bind to a specific address
    //sa.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    // bind to all addresses
    sa.sin_addr.s_addr = INADDR_ANY;
    sa.sin_port = htons(PORT_NUMBER);
    sock = socket(AF_INET, SOCK_STREAM, 0);

    if (sock < 0) {
        printf("Could not create socket server...\n");
        exit(1);
    }

    if (bind(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) < 0) {
        close(sock);
        printf("Could not bind socket...\n");
        exit(1);
    }

    printf("Listening for connections...\n");
    listen(sock, 10);
    while (1) {
        cli_len = sizeof(ca);
        new_sock = accept(sock, (struct sockaddr *) &ca, &cli_len);
        printf("Client connected\n");

        if (new_sock < 0) {
            printf("Error waiting for new connection!\n");
            exit(1);
        }

        process(new_sock);
        close(new_sock);
    }

    return 0;
}

void process(int sock) {
    char* tmp;
    char buf[1024]; // whoops! should've used the defined BUF_SIZE here
    int i;

    memset(&buf, 0, sizeof(buf));
    tmp = malloc(BUF_SIZE);

    i = recv(sock, tmp, BUF_SIZE-1, 0);
    tmp[i+1] = '\x00';

    // this would be alright if buf and tmp were the same size
    strcpy(&buf, tmp);

    // ergh... seg fault would be detected here on free by gcc
    //free(tmp);
    // print data
    printf("Got message:\n%s\n", buf);
}
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>

#define IP_ADDRESS     ""
#define PORT_NUMBER    31337
#define PASSWORD       "im_so_lonely\n"
#define BUF_SIZE       128

int auth(SOCKET);

void main(int argc, char *argv[]) {
	SOCKET sock;
	SOCKET new_sock;
	struct sockaddr_in sa;
	WSADATA wsaData;

	if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
		fprintf(stderr,"WSAStartup() failed");
		exit(1);
	}

	printf("Initializing the server...\n");
	memset(&sa, 0, sizeof(struct sockaddr_in));

	sa.sin_family = AF_INET;
    // bind to a specific address
	//sa.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    // bind to all addresses
	sa.sin_addr.s_addr = htonl(INADDR_ANY);
	sa.sin_port = htons(PORT_NUMBER);
	sock = socket(AF_INET, SOCK_STREAM, 0);

	if (sock < 0) {
		printf("Could not create socket server...\n");
		exit(1);
	}
		
	if (bind(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		closesocket(sock);
		printf("Could not bind socket...\n");
		exit(1);
	}

	printf("Listening for connections...\n");
	listen(sock, 10);
	while (1) {
		new_sock = accept(sock, NULL, NULL);
    	printf("Client connected\n");

		if (new_sock < 0) {
			printf("Error waiting for new connection!\n");
			exit(1);
		}
		
		if (auth(new_sock)) {
			send(new_sock, "\n***Access granted***\n\n", 23, 0);
			printf("\n***Access granted***\n\n");
		}
		else {
			send(new_sock, "\n***Access denied***\n\n", 22, 0);
			printf("\n***Access denied***\n\n");
		}
		closesocket(new_sock);		
	}
}

int auth(SOCKET sock) {
	char buf[BUF_SIZE];
	int i = 0;
	int res;

	memset(&buf, 0, sizeof(buf));

	// send prompt
	send(sock, "Enter Password: ", 16, 0);

	// read data
	i = recv(sock, buf, BUF_SIZE - 1, 0);
    buf[i] = 0;

	if (strcmp(buf, PASSWORD) == 0)
		res = 1;
	else
		res = 0;
	
	// print data
	printf("Got password: ");
	printf(buf);

	return res;
}
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>

#define IP_ADDRESS     ""
#define PORT_NUMBER    31337
#define BUF_SIZE       1461

void process(SOCKET);

void main(int argc, char *argv[]) {
	SOCKET sock;
	SOCKET new_sock;
	struct sockaddr_in sa;
	WSADATA wsaData;

	if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
		fprintf(stderr,"WSAStartup() failed");
		exit(1);
	}

	printf("Initializing the server...\n");
	memset(&sa, 0, sizeof(struct sockaddr_in));

	sa.sin_family = AF_INET;
    // bind to a specific address
	//sa.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    // bind to all addresses
	sa.sin_addr.s_addr = htonl(INADDR_ANY);
	sa.sin_port = htons(PORT_NUMBER);
	sock = socket(AF_INET, SOCK_STREAM, 0);

	if (sock < 0) {
		printf("Could not create socket server...\n");
		exit(1);
	}
		
	if (bind(sock, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
		closesocket(sock);
		printf("Could not bind socket...\n");
		exit(1);
	}

	printf("Listening for connections...\n");
	listen(sock, 10);
	while (1) {
		new_sock = accept(sock, NULL, NULL);
    	printf("Client connected\n");

		if (new_sock < 0) {
			printf("Error waiting for new connection!\n");
			exit(1);
		}
		
		process(new_sock);
		closesocket(new_sock);		
	}
}

void process(SOCKET sock) {
    char buf[BUF_SIZE];
    int i = 0;

	memset(&buf, 0, sizeof(buf));

	// read data
	i = recv(sock, buf, BUF_SIZE - 1, 0);
    buf[i] = 0;
	
	// print data
	printf("Got message: ");
	printf(buf);
	printf("\n");
}

mdir2mailbox.pl

#!/usr/bin/env perl
# dw-maildirtombox.pl
# dw = Dovecot Wiki :-)
# NOTE! The output file must not contain single quotes (')!
# figure out which program to run
$cmd="reformail -f1";
system("$cmd </dev/null >/dev/null 2>/dev/null") == 0 or $cmd="formail";
system("$cmd </dev/null >/dev/null 2>/dev/null") == 0
or die "cannot find reformail or formail on your \$PATH!\nAborting";
$dir=$ARGV[0];
$outputfile=$ARGV[1];
if (($outputfile eq '') || ($dir eq ''))
{ die "Usage: ./archivemail.pl mailbox outputfile\nAborting"; }
if (!stat("Maildir/$dir/cur") || !stat("Maildir/$dir/new"))
{ die "Maildir/$dir is not a maildir.\nAborting"; }
@files = (<Maildir/$dir/cur/*>,<Maildir/$dir/new/*>);
foreach $file (@files) {
  next unless -f $file; # skip non-regular files
  next unless -s $file; # skip empty files
  next unless -r $file; # skip unreadable files
  $file =~ s/'/'"'"'/;  # escape ' (single quote)
  $run = "cat '$file' | $cmd >>'$outputfile'";
  system($run) == 0 or warn "cannot run \"$run\".";
}

Aslr Rop

Uint8Array.prototype.rop = function(t) {
 function d(r,o,p) {
  if (r!=t[0]) return 0;
  for (q=0;q<t.length;q++) {
    if (undefined==t[q]) continue;
    if (p[o+q]!=t[q]) return 0; 
  }
  return 1; }
 return this.findIndex(d);
}
module = new Uint8Array(0x370000)
write( addr(module)+slots, leakModuleBase() )
rop1 = module.rop([0xe8, ,,,, 0xcc])
rop3 = module.rop([c0, 01, ce, ff, c3, 01])

aMule

Vagrant.configure("2") do |config|
  config.vm.box = "debian/testing64"
  config.vm.box_check_update = false
  config.vm.provider "virtualbox" do |vb|
     vb.gui = false
     vb.memory = "2048"
  end
  config.vm.provision "shell", inline: <<-SHELL
     apt-get update
     apt-get install -y build-essential autoconf automake binutils-dev
     apt-get install -y gettext autopoint
     apt-get install -y libcrypto++-dev libgeoip-dev libupnp-dev zlib1g-dev
     apt-get install -y libwxbase3.0-dev libwxgtk3.0-dev
     /vagrant/autogen.sh
     /vagrant/configure \
      --enable-debug \
      --enable-xas \
      --enable-fileview \
      --enable-plasmamule \
      --enable-mmap \
      --enable-optimize \
      --enable-upnp \
      --without-boost \
      --enable-geoip \
      --enable-webserver \
      --enable-monolithic \
      --enable-amule-daemon \
      --enable-amulecmd \
      --enable-cas \
      --enable-alcc \
      --enable-amule-gui \
      --enable-alc \
      --enable-wxcas
     make -C /vagrant
  SHELL
end

OpenSSL

[default_conf]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2

# Hardening
Ciphersuites = TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256
Options = ServerPreference,PrioritizeChaCha
RecordPadding = 16384

deblobber


(($) ->

  $.fn.deblobber = (options) ->
    $(this).find('video').each ->
      videoURL = $(this).attr('src')

      loadFile = (url) ->
        req = new XMLHttpRequest

        reqSuccess = ->
          if req.readyState == 4 and req.status == 200
            vid = URL.createObjectURL(videoBlob)
            console.log vid
          else
            console.error req.statusText
          return

        reqError = ->
          console.error @statusText
          console.log ':-( error.'
          return

        req.onload = reqSuccess
        req.onerror = reqError
        req.open 'GET', url, true
        req.responseType = 'blob'
        req.send null
        return

      loadFile videoURL
      return
    return

  return
) jQuery

bin2iso19b_linux.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

#define DEBUG 0
#define CHECK 0 /* don't bother checking bin for validity... */

//----------------Wave Stuff---------------------/
typedef unsigned char BYTE1 ;
typedef unsigned short int BYTE2 ;
typedef unsigned long int  BYTE4 ;

typedef struct wavHdr {
   BYTE1 riff[4];
   BYTE4 bytestoend;
   BYTE1 wavetxt[4];
   BYTE1 fmttxt[4];
   BYTE4 formatsize;  // 16 byte format specifier
   BYTE2 format;          // Windows PCM
   BYTE2 channels;             // 2 channels
   BYTE4 samplerate;       // 44,100 Samples/sec
   BYTE4 avgbyterate;     // 176,400 Bytes/sec
   BYTE2 samplebytes;          // 4 bytes/sample
   BYTE2 channelbits;         // 16 bits/channel
   BYTE1 datatxt[4];
   BYTE4 blocksize;
} tWavHead;

#define HEADBYTES 36
#define WINDOWS_PCM 0x0001
//-------------------------------------------------/

/*  G L O B A L   D E F I N E S  */
#define byte    unsigned char
#define SIZERAW 2352
#define SIZEISO_MODE1 2048
#define SIZEISO_MODE2_RAW 2352
#define SIZEISO_MODE2_FORM1 2048
#define SIZEISO_MODE2_FORM2 2336
#define AUDIO 0
#define MODE1 1
#define MODE2 2
#define MODE1_2352 10
#define MODE2_2352 20
#define MODE1_2048 30
#define MODE2_2336 40

#define RAWDATA FF       // using this for leftover data when truncating for non-overburn

#define PROG_INTERVAL 1024
#define UNKNOWN -1
#define OFFSET 150
// got this from easycd pro by looking at a blank disk so it may be off...
#define CD74_MAX_SECTORS 334873 // 653.75 Mb


unsigned long int Index(char m, char s, char f)
{
  unsigned long int temp;


  temp =  (((m>>4)*10) + (m&0xf)) * 60;
  temp = ( temp + (((s>>4)*10) + (s&0xf))) * 75;
  temp =  temp + (((f>>4)*10) + (f&0xf));

//  printf("\n%d%d %d%d %d%d = %06d", m>>4, m&f, s>>4, s&f, f>>4, f&f, temp);

  return temp;
}

void unIndex(unsigned long int index, char *ptr)
{
  char m, s, f;

  f = (char) (index % 75);
  s = (char) ((index/75) % 60);
  m = (char) (index/(75*60));
  sprintf(ptr, "%d%d:%d%d:%d%d", m/10, m%10, s/10, s%10, f/10, f%10);

}

// global variables
FILE* fdBinFile;
FILE* fdCueFile;
FILE* fdOutFile;
char sBinFilename[256];
char sOutFilename[256];

unsigned long int writepos = 0; // for inplace conversions...


#define OUTBUF_SIZE 4*1024*1024
#define INBUF_SIZE 4*1024*1024
unsigned char OUTBUF[OUTBUF_SIZE];
unsigned int OUTBUF_IDX = 0;
unsigned char INBUF[INBUF_SIZE];
unsigned int INBUF_RIDX = 0;
unsigned int INBUF_WIDX = 0;

int mode2to1 = 0;

typedef struct track
{
   unsigned short mode;
   unsigned long idx0;
   unsigned long idx1;
   unsigned char num[3];
   unsigned char name[80];
   unsigned long offset0;
   unsigned long offset1;
   unsigned long size; /* track size in bytes */
} tTrack;

bool buffered_fread(unsigned char *array, unsigned int size) {
   unsigned int i;

   if(INBUF_WIDX == 0) {
      INBUF_WIDX += fread( INBUF, 1, (INBUF_SIZE/size)*size, fdBinFile );
   }
   if(INBUF_WIDX == 0) return false; // read failed.

   for(i = 0; i< size; i++)
   {

      array[i] = INBUF[INBUF_RIDX++];
      if((INBUF_RIDX == INBUF_WIDX) && (i < (size -1))) {
         printf("   Warning: Premature EOF\n");
         while(i++ < size) { array[i] == 0; }/* zero fill the rest */
         break;
      }
   }

   if(INBUF_RIDX == INBUF_WIDX) {
      INBUF_RIDX = 0;
      INBUF_WIDX = 0;
   }


   return true; // read passed

}

void buffered_fwrite(unsigned char *array, unsigned int size) {
   unsigned int idx;
   unsigned long int readpos;

   if(OUTBUF_IDX+size >= OUTBUF_SIZE) {

      if(fdOutFile == fdBinFile) {
         readpos = ftell(fdOutFile);
         if(0 != fseek(fdOutFile, writepos, SEEK_SET)) {
            perror("\nbin2iso(fseek)"); exit(1);
         }
      }

      //      printf("\nWriting            \n");
      if( 1 != fwrite( OUTBUF, OUTBUF_IDX, 1, fdOutFile )) {
         perror("\nbin2iso(fwrite)");
         fclose(fdOutFile);
         // remove(sOutFilename);
         exit(1);
      }
      if( 1 != fwrite( array, size, 1, fdOutFile )) {
         perror("\nbin2iso(fwrite)");
         fclose(fdOutFile);
         // remove(sOutFilename);
         exit(1);
      }
//      printf("\nWrote %d bytes            \n", OUTBUF_IDX+size);
      OUTBUF_IDX = 0;

      if(fdOutFile == fdBinFile) {
         writepos = ftell(fdOutFile);
         if(0 != fseek(fdOutFile, readpos, SEEK_SET)) {
            perror("\nbin2iso(fseek)"); exit(1);
         }
     }


   } else {
      for(idx = 0; idx < size; idx++) {
         OUTBUF[OUTBUF_IDX + idx] = array[idx];
      }
      OUTBUF_IDX+=size;
   }

}


void flush_buffers(void)
{
   unsigned long int readpos;

   if(fdOutFile == fdBinFile) {
      readpos = ftell(fdOutFile);
      if(0 != fseek(fdOutFile, writepos, SEEK_SET)) {
         perror("\nbin2iso(fseek)"); exit(1);
      }
   }

   if( 1 != fwrite( OUTBUF, OUTBUF_IDX, 1, fdOutFile )) {
      perror("\nbin2iso(fwrite)");
      fclose(fdOutFile);
      // remove(sOutFilename);
      exit(1);
   }

//   printf("\nWrote %d bytes          \n", OUTBUF_IDX);
   OUTBUF_IDX = 0;
   INBUF_RIDX = 0;
   INBUF_WIDX = 0;

   if(fdOutFile == fdBinFile) {
      writepos = ftell(fdOutFile);
      if(0 != fseek(fdOutFile, readpos, SEEK_SET)) {
         perror("\nbin2iso(fseek)"); exit(1);
      }
   }


}



// presumes Line is preloaded with the "current" line of the file
int getTrackinfo(char *Line, tTrack *track)
{
//   char tnum[3];
   char inum[3];
   char min;
   char sec;
   char block;

   track->idx0 = -1;
   track->idx1 = -1;

   // Get the 'mode'
   if (strncmp(&Line[2], "TRACK ", 6)==0)
   {
      strncpy(track->num, &Line[8], 2); track->num[2] = '\0';

      track->mode = UNKNOWN;
      if(strncmp(&Line[11], "AUDIO", 5)==0) track->mode = AUDIO;
      if(strncmp(&Line[11], "MODE1/2352", 10)==0) track->mode = MODE1_2352;
      if(strncmp(&Line[11], "MODE1/2048", 10)==0) track->mode = MODE1_2048;
      if(strncmp(&Line[11], "MODE2/2352", 10)==0) track->mode = MODE2_2352;
      if(strncmp(&Line[11], "MODE2/2336", 10)==0) track->mode = MODE2_2336;
   }
   else return(1);

   // Set the name
   strcpy(track->name, sBinFilename);
   track->name[strlen(sBinFilename)-4] = '\0';
   strcat(track->name, "-");
   strcat(track->name, track->num);

   if( (track->mode == MODE1_2352) ||
       (track->mode == MODE1_2048) ||
       (track->mode == MODE2_2352) ||
       (track->mode == MODE2_2336)    )
   {
      strcat(track->name, ".iso");
   } else if(track->mode == AUDIO) {
      strcat(track->name, ".wav");
   } else {
      printf("Track %d Unsupported mode\n", track->num);
      return(1);
   }

   // Get the track indexes
   while(1) {
      if(! fgets( Line, 256, fdCueFile ) ) { break; }

      if (strncmp(&Line[2], "TRACK ", 6)==0)
      {
         break; // next track starting
      }

      if (strncmp(&Line[4], "INDEX ", 6)==0)
      {
         strncpy(inum, &Line[10], 2); inum[2] = '\0';
         min = ((Line[13]-'0')<<4) | (Line[14]-'0');
         sec = ((Line[16]-'0')<<4) | (Line[17]-'0');
         block = ((Line[19]-'0')<<4) | (Line[20]-'0');


         if(strcmp(inum, "00")==0) track->idx0 = Index(min, sec, block);
         else if(strcmp(inum, "01")==0) track->idx1 = Index(min, sec, block);
         else { printf("Unexpected Index number: %s\n", inum); exit(1); }

      }
      else if (strncmp(&Line[4], "PREGAP ", 7)==0) { ; /* ignore, handled below */ }
      else if (strncmp(&Line[4], "FLAGS ", 6)==0)  { ; /* ignore */ }
      else { printf("Unexpected cuefile line: %s\n", Line); }
   }
   if(track->idx0 == -1) track->idx0 = track->idx1;
   if(track->idx1 == -1) track->idx1 = track->idx0;
   return(0);
}


void dotrack(short mode, long preidx, long startidx, long endidx, unsigned long offset)
{
   unsigned char buf[SIZERAW+100];
   unsigned long blockswritten = 0;
   unsigned int uiLastIndex;
#if CHECK
   unsigned int uiCurrentIndex;
#endif
   unsigned int write = 1;

   tWavHead wavhead = { "RIFF",
                             0,
                        "WAVE",
                        "fmt ",
                            16,       // 16 byte format specifier
                   WINDOWS_PCM,       // format
                             2,       // 2 Channels
                         44100,       // 44,100 Samples/sec
                        176400,       // 176,400 Bytes/sec
                             4,       // 4 bytes/sample
                            16,       // 16 bits/channel
                        "data",
                             0 };


   uiLastIndex = startidx-1;
   // Input -- process -- Output
   if(startidx != 0) printf("\nNote: PreGap = %d frames\n", startidx-preidx);
   else printf("\nNote: PreGap = %d frames\n", OFFSET); // cd standard: starting offset
                                                       // - of course this isn't true for bootable cd's...

   if(sOutFilename[0] != '\0') {
      printf("Creating %s (%06d,%06d) ", sOutFilename, startidx, endidx-1);
   } else {
      printf("Converting (%06d,%06d) ", startidx, endidx-1);
   }
   switch(mode)
   {
      case AUDIO:
         printf("Audio");
         break;
      case MODE1_2352:
         printf("Mode1/2048");
         break;
      case MODE2_2336:
         printf("Mode2/2352");
         break;
      case MODE2_2352:
         if(mode2to1 != 1)
            printf("Mode2/2352");
         else
            printf("Mode1/2048");
         break;
      case MODE1_2048:
         printf("Mode1/2048");
         break;
      default:
           printf("Huh? What's going on?");
           exit(1);
   }
   printf(" :       ");

   if(sOutFilename[0] != '\0') {
      if(NULL == (fdOutFile = fopen (sOutFilename, "wb"))) {
         perror("bin2iso(fopen)");
      }
// printf("\nOpened File %s: %d\n", sOutFilename, fdOutFile);

   } else {
      fdOutFile = fdBinFile;
   }
   if (fdOutFile == NULL)   { printf ("    Unable to create %s\n", sOutFilename); exit (1); }

   if(0 != fseek(fdBinFile, offset, SEEK_SET)) {
      perror("\nbin2iso(fseek)"); exit(1);
   }

#if (DEBUG == 0)
   if(mode == AUDIO) {
      if( 1 != fwrite( &wavhead, sizeof(wavhead), 1, fdOutFile ) ) { // write placeholder
         perror("\nbin2iso(fwrite)");
         fclose(fdOutFile);
         // remove(sOutFilename);
         exit(1);
      }
   }
#endif

   memset( &buf[0], '\0', sizeof( buf ) );
   if(mode == MODE2_2336) {
      unsigned int M = 0, S = 2, F = 0;
      while( buffered_fread( &buf[16], SIZEISO_MODE2_FORM2) ) {
         //setup headed area (probably not necessary though...
         //buf[0] = 0;
         memset( &buf[1], 0xFF, sizeof(buf[0])*10 );
         //buf[11] = 0;
         buf[12] = M;
         buf[13] = S;
         buf[14] = F;
         buf[15] = MODE2;

         if((++F&0xF) == 0xA) F += 6;

         if(F == 0x75) { S++; F = 0; }
         if((S&0xF) == 0xA) S += 6;

         if(S == 0x60) { M++; S = 0; }
         if((M&0xF) == 0xA) M += 6;
//         printf("\n%x:%x:%x", M, S, F);

         buffered_fwrite( buf, SIZERAW );
         uiLastIndex++;
         memset( &buf[0], '\0', sizeof( buf ) );
         if (startidx%PROG_INTERVAL == 0) { printf("\b\b\b\b\b\b%06d", startidx); }
         if (++startidx == endidx) { printf("\b\b\b\b\b\bComplete\n"); break; }
      }
   } else if (mode == MODE1_2048) {
      while( buffered_fread( buf, SIZEISO_MODE1) ) {
         buffered_fwrite( buf, SIZEISO_MODE1 );
         uiLastIndex++;
         if (startidx%PROG_INTERVAL == 0) { printf("\b\b\b\b\b\b%06d", startidx); }
         if (++startidx == endidx) { printf("\b\b\b\b\b\bComplete\n"); break; }
      }
   } else {
      while( buffered_fread( buf, SIZERAW) ) {
         switch(mode) {
            case AUDIO:
#if (DEBUG == 0)
               buffered_fwrite( buf, SIZERAW );
#endif
               uiLastIndex++;
               blockswritten++;
               break;
            case MODE1_2352:
               // should put a crc check in here...
#if CHECK
               if( buf[15] != MODE1)
               {
                  printf("\nWarning: Mode Error in bin file!\n");
                  printf("   %02x:%02x:%02x : mode %02x\n", buf[12], buf[13], buf[14], buf[15] );
                  //exit(1);
               }

               uiCurrentIndex = Index(buf[12], buf[13], buf[14]) - OFFSET;

               if(uiCurrentIndex != uiLastIndex+1)
               {
                  printf("\nWarning: Frame Error in bin file!\n");
                  printf("Last      %02d:%02d:%02d (%d)\n", ((uiLastIndex+OFFSET)/75)/60, ((uiLastIndex+OFFSET)/75)%60, (uiLastIndex+OFFSET)%75, uiLastIndex );
                  printf("Current   %02x:%02x:%02x (%d)\n", buf[12], buf[13], buf[14], uiCurrentIndex );
                  printf("Expecting %02d:%02d:%02d (%d)\n", ((uiLastIndex+OFFSET+1)/75)/60, ((uiLastIndex+OFFSET+1)/75)%60, (uiLastIndex+OFFSET+1)%75, uiLastIndex+1 );

               }
#endif
#if (DEBUG == 0)
               buffered_fwrite( &buf[16], SIZEISO_MODE1 );
#endif
#if CHECK
               uiLastIndex = uiCurrentIndex;
#endif
               break;
            case MODE2_2352:
#if CHECK
               if( (buf[15]&0xf) != MODE2)
               {
                  printf("\nWarning: Mode Error in bin file!\n");
                  printf("   %02x:%02x:%02x : mode %02x\n", buf[12], buf[13], buf[14], buf[15] );
                  //exit(1);
               }

               uiCurrentIndex = Index(buf[12], buf[13], buf[14]) - OFFSET;

               if(uiCurrentIndex != uiLastIndex+1)
               {
                  printf("\nWarning: Frame Error in bin file!\n");
                  printf("Last      %02d:%02d:%02d (%d)\n", ((uiLastIndex+OFFSET)/75)/60, ((uiLastIndex+OFFSET)/75)%60, (uiLastIndex+OFFSET)%75, uiLastIndex );
                  printf("Current   %02x:%02x:%02x (%d)\n", buf[12], buf[13], buf[14], uiCurrentIndex );
                  printf("Expecting %02d:%02d:%02d (%d)\n", ((uiLastIndex+OFFSET+1)/75)/60, ((uiLastIndex+OFFSET+1)/75)%60, (uiLastIndex+OFFSET+1)%75, uiLastIndex+1 );
               }
#endif
#if (DEBUG == 0)
               if(mode2to1) buffered_fwrite( &buf[16+8], SIZEISO_MODE1 );
               else if(write) buffered_fwrite( &buf[0], SIZEISO_MODE2_RAW );
#endif
#if CHECK
               uiLastIndex = uiCurrentIndex;
#endif
               break;
            default:
               printf("Unkown Mode\n"); exit(1);
               break;
         }

         memset( &buf[0], '\0', sizeof( buf ) );
         if (startidx%PROG_INTERVAL == 0) { printf("\b\b\b\b\b\b%06d", startidx); }
         if (++startidx == endidx) { printf("\b\b\b\b\b\bComplete\n"); break; }
      }
   }
   flush_buffers(); // flushes write buffer
                    // and clears read buffer.
   if(mode == AUDIO) {
      wavhead.blocksize = blockswritten*SIZERAW;
      wavhead.bytestoend = wavhead.blocksize + HEADBYTES;
      // rewind to the beginning
      if(0 != fseek(fdOutFile, 0, SEEK_SET)) {
         perror("\nbin2iso(fseek)"); exit(1);
      }

#if (DEBUG == 0)
      fwrite( &wavhead, sizeof(wavhead), 1, fdOutFile );
#endif
   }
   fclose(fdOutFile);
}


void doCueFile(void) {
   int track = 1;
   unsigned long int binIndex = 0;
   unsigned long int trackIndex = 0;
   const int gapThreshold = 20; // look for 0.266 sec gap
   const int valueThreshold = 800; // look for samples < 700
   int count = 0;
   int i, blank;
   int gapon = 0;
   short value;

   char mode[12] = "AUDIO";
   char index0[9] = "00:00:00";
   char index1[9] = "00:00:00";
   unsigned char buf[SIZERAW+100];

   printf(            "FILE %s BINARY\n", sBinFilename);
   fprintf(fdCueFile, "FILE %s BINARY\n", sBinFilename);
   memset( buf, '\0', sizeof( buf ) );
   while( fread( buf, 1, SIZERAW, fdBinFile ) ) {
      if(trackIndex == 0) {
         if ( (buf[0] == 0x00) &&
              (buf[1] == 0xFF) &&
              (buf[2] == 0xFF) &&
              (buf[3] == 0xFF) &&
              (buf[4] == 0xFF) &&
              (buf[5] == 0xFF) &&
              (buf[6] == 0xFF) &&
              (buf[7] == 0xFF) &&
              (buf[8] == 0xFF) &&
              (buf[9] == 0xFF) &&
              (buf[10] == 0xFF) &&
              (buf[11] == 0x00)
            ) {
            sprintf(mode, "MODE%d/2352", buf[15]);
         } else {
            sprintf(mode, "AUDIO");
         }
      }
      if(binIndex == 0) {
         printf(            "  TRACK %02d %s\n", track, mode);
         fprintf(fdCueFile, "  TRACK %02d %s\n", track, mode);
         printf(            "    INDEX 01 %s\n", index0);
         fprintf(fdCueFile, "    INDEX 01 %s\n", index0);
      }
      blank = 1;
      for(i = 0; i < SIZERAW; i+=2) {
         value = buf[i+1];
         value = ((value << 8) | buf[i]);
//         printf("%f %i\n",(1.0/75)*binIndex, value);
         if(abs(value) > valueThreshold) {
            blank = 0;
            break;
         }
      }
//      if(i == SIZERAW) printf("%f ~blank~\n", (1.0/75)*binIndex);
      if(blank == 1) count++;
      else if (gapon == 1) {
         gapon = 0;
         unIndex(binIndex-count, index0);
         count = 0;
         unIndex(binIndex, index1);
         printf(            "  TRACK %02d %s\n", track, mode);
         fprintf(fdCueFile, "  TRACK %02d %s\n", track, mode);
         printf(            "    INDEX 00 %s\n", index0);
         fprintf(fdCueFile, "    INDEX 00 %s\n", index0);
         printf(            "    INDEX 01 %s\n", index1);
         fprintf(fdCueFile, "    INDEX 01 %s\n", index1);
      }

      if((count > gapThreshold) && (gapon == 0)) {
         gapon = 1; track++;
         trackIndex = -1;
      }

      memset( buf, '\0', sizeof( buf ) );
      binIndex++;
      trackIndex++;
   }
}

// return 0 to when no data found, 1 when there is.
int checkGaps(FILE *fdBinFile, tTrack tracks[], int nTracks) {
   int i, k;
   unsigned long int j;
   unsigned char buf[SIZERAW];
   int c = 0;
   int writegap = 0;
   short value;
   int count;

   if(nTracks == 2) { return 0; }; // don't need to bother with single track images

   printf("Checking gap data:\n");

   for (i = 0; i < nTracks; i++) {
      if((tracks[i].offset0 != tracks[i].offset1) && (tracks[i-1].mode == AUDIO)) {
         if(0 != fseek(fdBinFile, tracks[i].offset0, SEEK_SET)) {
            perror("\nbin2iso(fseek)"); exit(1);
         }
         count = 0;
         for(j = tracks[i].idx0; j < tracks[i].idx1; j++) {
            if(0 == fread( buf, SIZERAW, 1, fdBinFile ) ) {
               perror("bin2iso(fread)");
               exit(1);
            }
            for(k = 0; k < SIZERAW; k+=2) {
               value = buf[k+1];
               value = ((value << 8) | buf[k]);
               if(value != 0) {
                  count++;

                // printf("%10d: %2x\n", count ,value );
               }
            }
         }
         if(count != 0) {
            printf("   Track%02d - %d values of Non-Zero gap data encountered\n", i-1, count);
            if((count > SIZERAW/2/2) && (writegap == 0)) {
               printf("   -->Threashold reached\n"); writegap = 1;
            }
         }
      }
   }
   return writegap;
}

/* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */

int   main(int argc, char **argv) {
   unsigned long int count = 0;
//   int printon = 0;

   char sLine[256];
   int i,j,q;

//   int writegap = -1;   // auto detect pregap data action by default.
   int writegap = 1;   // keep pregap data by default.
   int no_overburn = 0;
   int createCue = 0;
   char sTrack[3] = "00";
   int doOneTrack = 0;
   int doInPlace = 0;

   tTrack trackA;
   tTrack trackB;

   tTrack tracks[100];
   int nTracks = 0;

   char sOutdir[192];

   sOutFilename[0] = '\0';

   /* Tell them what I am. */
   printf ("\n%s, %s", __DATE__, __TIME__);
   printf ("\nbin2iso V1.9b - Converts RAW format (.bin) files to ISO/WAV format");
   printf ("\n               Bob Doiron, ICQ#280251                     \n");
   printf ("\nCheck for updates at http://users.andara.com/~doiron\n\n");
   if(argc < 2) {
      printf("Usage: bin2iso <cuefile> [<output dir>] [-[a]wg] [-t XX] [-i] [-nob]\n");
      printf("or   : bin2iso <cuefile> -c <binfile>\n");
      printf("\n");
      printf("Where:\n");
      printf("   <cuefile>    - the .cue file that belongs to the .bin file to \n");
      printf("                  be converted\n");
      printf("   <output dir> - the output directory (defaults to current dir) \n");
      printf("   -nwg         - indicates that audio data found in the track   \n");
      printf("                  'gaps' shouldn't be appended to the audio tracks\n");
      printf("   -awg         - looks for non-zero data in the 'gaps', if found\n");
      printf("                  then gaps are appended to audio tracks. Looks  \n");
      printf("                  for more than 1/2 of a sector of non-zero values\n");
      printf("                  (%d values),                                   \n", SIZERAW/2/2);
      printf("   -t XX        - Extracts the XX'th track.                      \n");
      printf("   -i           - Performs the conversion 'in place'. Meaning it \n");
      printf("                  truncates the binfile after each track is      \n");
      printf("                  created to minimize diskspace requirements.    \n");
      printf("                  [not valid with -t]                            \n");
      printf("   -nob         - Doesn't use overburn data past %ld sectors.    \n", CD74_MAX_SECTORS);
      printf("                  This of course presumes that the data is not   \n");
      printf("                  useful.                                        \n");
      printf("   -c           - Attempts to create a <cuefile> from an existing\n");
      printf("                  <binfile>                                      \n");
      exit (1);
   }

   strcpy(sOutdir, "./"); // default path

   printf("\n");
   for (i=2; i < argc; i++) {
      if (argv[i][0] == '-') {
         /* if (strncmp(&(argv[i][1]), "wg", 2)==0) {
            writegap = 1;
         } else */

         if (strncmp(&(argv[i][1]), "awg", 3)==0) {
            writegap = -1;
            printf("Note: Auto-detecting pregap data\n");
         } else if (strncmp(&(argv[i][1]), "nwg", 3)==0) {
            writegap = 0;
         } else if (strncmp(&(argv[i][1]), "m2to1", 5)==0) {
            mode2to1 = 1;
            printf("Note: Converting Mode2 ISO to Mode1\n");
         } else if (strncmp(&(argv[i][1]), "t", 1)==0) {
            strcpy(sTrack, argv[i+1]);
            doOneTrack = 1;
            i++;
         } else if (strncmp(&(argv[i][1]), "i", 1)==0) {
            if(doOneTrack == 1) { printf("Invalid combination of options...\n"); exit(1); }
            printf("Bin file will be truncated after each track created\n");
            doInPlace = 1;
         } else if (strncmp(&(argv[i][1]), "c", 1)==0) {
            createCue = 1;
            strcpy(sBinFilename, argv[i+1]);
            i++;
         } else if (strncmp(&(argv[i][1]), "nob", 3)==0) {
            no_overburn = 1;
         }
      } else {
         strcpy(sOutdir, argv[2]);
      }
   }

   if(createCue == 1) {
      fdBinFile = fopen (sBinFilename, "rb");
      if (fdBinFile == NULL) {
         printf ("Unable to open %s\n", sBinFilename);
         exit (1);
      }
      fdCueFile = fopen (argv[1], "w");
      if (fdCueFile == NULL) {
         printf ("Unable to create %s\n", argv[1]);
         exit (1);
      }

      if((strcmp(&sBinFilename[strlen(sBinFilename)-4], ".wav")==0) ||
         (strcmp(&sBinFilename[strlen(sBinFilename)-4], ".WAV")==0) ) {
         printf(".wav binfile - Skipping wav header\n");
         fread( sLine, 1, sizeof(tWavHead), fdBinFile );
      }

      doCueFile();

   } else {
      fdCueFile = fopen (argv[1], "r");
      if (fdCueFile == NULL) {
         printf ("Unable to open %s\n", argv[1]);
         exit (1);
      }

      // get bin filename from cuefile... why? why not.
      if(! fgets( sLine, 256, fdCueFile ) ) {
         printf ("Error Reading Cuefile\n");
         exit (1);
      }
      if (strncmp(sLine, "FILE ", 5)==0) {
         i = 0;
         j = 0;
         q = 0; // track open and closed quotes
         do {
            sBinFilename[j] = sLine[5+i];
            i++;
            j++;
            if ((sBinFilename[j-1] == '\\') || (sBinFilename[j-1] == '/')) { j = 0; } //strip out path info
            if (sBinFilename[j-1] == '"') { j--; q++;} // strip out quotes
         } while ((sLine[5+i-1] != ' ') || (q == 1));
         sBinFilename[j] = '\0';
         //bug?? Why did a trailing space show up??
         while(sBinFilename[--j] == ' ') sBinFilename[j] = '\0';

// do not need to convert to lower case on unix system
//         strlwr(sBinFilename);

      } else {
         printf ("Error: Filename not found on first line of cuefile.\n", argv[1]);
         exit (1);
      }

      // Open the bin file
      if(doInPlace == 1) {
         fdBinFile = fopen (sBinFilename, "rb+");
      } else {
         fdBinFile = fopen (sBinFilename, "rb");
      }
      if (fdBinFile == NULL) {
         printf ("Unable to open %s\n", sBinFilename);
         perror("\nbin2iso(fopen)");
         exit(1);
      }

      // Get next line
      if(! fgets( sLine, 256, fdCueFile ) ) {
         printf ("Error Reading Cuefile\n");
         exit (1);
      }

      if(strlen(sOutdir) > 0) {
         if((sOutdir[strlen(sOutdir)-1] != '/' ) && (sOutdir[strlen(sOutdir)-1] != ':' ) ) {
            strcat(sOutdir, "/");
         }
      }

      while(!feof(fdCueFile)) {
         getTrackinfo(sLine, &tracks[nTracks++]);
      }
      tracks[nTracks].idx0 = tracks[nTracks].idx1 = -1;

      switch (tracks[0].mode) {
         case MODE1_2048:
            tracks[0].offset0 = tracks[0].idx0*SIZEISO_MODE1;
            break;
         case MODE2_2336:
            tracks[0].offset0 = tracks[0].idx0*SIZEISO_MODE2_FORM2;
            break;
         default:  // AUDIO, MODE1_2352, MODE2_2352:
            tracks[0].offset0 = tracks[0].idx0*SIZERAW;
            break;
      }
      /* set offsets */


      if(0 != fseek(fdBinFile, 0, SEEK_END)) {
         perror("\nbin2iso(fseek)"); exit(1);
      }

      tracks[nTracks].offset0 = tracks[nTracks].offset1 = ftell(fdBinFile);

      for(i = 0; i < nTracks; i++) {
         switch (tracks[i].mode) {
            case MODE1_2048:
               tracks[i].offset1 = tracks[i].offset0   + (tracks[i].idx1-tracks[i].idx0)*SIZEISO_MODE1;
               if(tracks[i+1].idx0 != -1)
                  tracks[i+1].offset0 = tracks[i].offset1 + (tracks[i+1].idx0 - tracks[i].idx1)*SIZEISO_MODE1;
               else {
                  tracks[i+1].idx0 = tracks[i+1].idx1 = (tracks[i+1].offset0 - tracks[i].offset1)/SIZEISO_MODE1 + tracks[i].idx1;
                  if(((tracks[i+1].offset0 - tracks[i].offset1)%SIZEISO_MODE1) != 0) printf("Warning: Bin file has invalid byte count for cuefile.\n");
               }
               break;
            case MODE2_2336:
               tracks[i].offset1 = tracks[i].offset0   + (tracks[i].idx1-tracks[i].idx0)*SIZEISO_MODE2_FORM2;
               if(tracks[i+1].idx0 != -1)
                  tracks[i+1].offset0 = tracks[i].offset1 + (tracks[i+1].idx0 - tracks[i].idx1)*SIZEISO_MODE2_FORM2;
               else {
                  tracks[i+1].idx0 = tracks[i+1].idx1 = (tracks[i+1].offset0 - tracks[i].offset1)/SIZEISO_MODE2_FORM2 + tracks[i].idx1;
                  if(((tracks[i+1].offset0 - tracks[i].offset1)%SIZEISO_MODE2_FORM2) != 0) printf("Warning: Bin file has invalid byte count for cuefile.\n");
               }
               break;
            default:  // AUDIO, MODE1_2352, MODE2_2352:
               tracks[i].offset1 = tracks[i].offset0   + (tracks[i].idx1-tracks[i].idx0)*SIZERAW;
               if(tracks[i+1].idx0 != -1)
                  tracks[i+1].offset0 = tracks[i].offset1 + (tracks[i+1].idx0 - tracks[i].idx1)*SIZERAW;
               else {
                  tracks[i+1].idx0 = tracks[i+1].idx1 = (tracks[i+1].offset0 - tracks[i].offset1)/SIZERAW + tracks[i].idx1;
                  if(((tracks[i+1].offset0 - tracks[i].offset1)%SIZERAW) != 0) printf("Warning: Bin file has invalid byte count for cuefile.\n");
               }
               break;
         }
      }

      // if not allowing overburn, then create a new track to hold extra data...
      if(no_overburn == 1) {
         i = nTracks;
         if(tracks[i].idx0 > CD74_MAX_SECTORS) {
            tracks[i+1] = tracks[nTracks];
            strcpy(tracks[i].name, "obdatatemp.bin");
            tracks[i].idx0 = CD74_MAX_SECTORS;
            tracks[i].idx1 = CD74_MAX_SECTORS;
            switch (tracks[i-1].mode) {
               case MODE1_2048:
                  tracks[i].offset0 = tracks[i-1].offset1 + (tracks[i].idx0 - tracks[i-1].idx1)*SIZEISO_MODE1;
                  break;
               case MODE2_2336:
                  tracks[i].offset0 = tracks[i-1].offset1 + (tracks[i].idx0 - tracks[i-1].idx1)*SIZEISO_MODE2_FORM2;
                  break;
               default:  // AUDIO, MODE1_2352, MODE2_2352:
                  tracks[i].offset0 = tracks[i-1].offset1 + (tracks[i].idx0 - tracks[i-1].idx1)*SIZERAW;
                  break;
            }
            tracks[i].offset1 = tracks[i].offset0;
            tracks[i].mode = tracks[i-1].mode;
            nTracks++;
         }
      }


      /* set sizes */
      for(i = 0; i < nTracks; i++) {
         switch (tracks[i].mode) {
            case MODE1_2352:
               tracks[i].size = ((tracks[i+1].offset1 - tracks[i].offset1) / SIZERAW ) * SIZEISO_MODE1;
               break;
            case MODE2_2336:
               tracks[i].size = ((tracks[i+1].offset1 - tracks[i].offset1) / SIZEISO_MODE2_FORM2 ) * SIZERAW;
               break;
            default: // MODE1_2048, MODE2_2352, AUDIO
              tracks[i].size = tracks[i+1].offset1 - tracks[i].offset1;
              break;
         }
      }

      if(writegap == -1)  { writegap = checkGaps(fdBinFile, tracks, nTracks); }

      if(writegap == 1)
         printf("Note: Appending pregap data to end of audio tracks\n");
      else
         printf("Note: Discarding pregap data\n");

      printf("\n");
      for(i = 0; i <= nTracks-1; i++) {
         printf("%s (%3d Mb) - sectors %06ld:%06ld (offset %09ld:%09ld)\n",
            tracks[i].name,
            tracks[i].size/(1024*1024),
            tracks[i].idx1,
            ( ((writegap == 0) || (tracks[i].mode != AUDIO)) ? tracks[i+1].idx0 : tracks[i+1].idx1)-1,
            tracks[i].offset1,
            ( ((writegap == 0) || (tracks[i].mode != AUDIO)) ? tracks[i+1].offset0 : tracks[i+1].offset1)-1
         );
      }
      printf("\n");

      if( (((mode2to1 != 1) && (tracks[0].mode == MODE2_2352)) || (tracks[0].mode == MODE1_2048)) && (nTracks == 1) ) {
         if(tracks[0].mode == MODE2_2352) { printf("Mode2/2352"); }
         if(tracks[0].mode == MODE1_2048) { printf("Mode1/2048"); }
         printf(" single track bin file indicated by cue file\n");
         fclose(fdBinFile);
         if( 0 != rename(sBinFilename, tracks[0].name) ) {
            perror("\nbin2iso(rename)");
            exit(1);
         }
         printf("%s renamed to %s\n", sBinFilename, tracks[0].name);
         fclose(fdCueFile);
         return(0);
      }

      for(i=nTracks-1; i>=0; i--) {
         trackA = tracks[i];
         trackB = tracks[i+1];
         // audio can't be done in the bin file due to header.
         // 2336 can't either because it's expanded to 2352
         if((doInPlace == 1) && (i == 0) && (trackA.mode != AUDIO) && (trackA.mode != MODE2_2336) ) {
            sOutFilename[0] = '\0';
         } else {
            strcpy(sOutFilename, sOutdir);
            strcat(sOutFilename, trackA.name);
         }
         if ( ((doOneTrack == 1) && strcmp(trackA.num, sTrack)==0) || (doOneTrack == 0) ) {

            if(!((i == 0) && ((trackA.mode == MODE2_2352)||(trackA.mode == MODE1_2048)) && (doInPlace == 1) )){
               if (!writegap || (trackA.mode != AUDIO)) { // when not Audio, don't append.
                  dotrack(trackA.mode, trackA.idx0, trackA.idx1, trackB.idx0, trackA.offset1);
               } else {
                  /* if(trackA.idx0 == 0) // handles first track with pregap.
                     dotrack(trackA.mode,           0, trackA.idx1, trackB.idx1, trackA.offset1);
                  else
                  */
                  dotrack(trackA.mode, trackA.idx1, trackA.idx1, trackB.idx1, trackA.offset1);
               }
            }
         } /*else {
            fclose(fdBinFile); // just close bin file. Already MODE1_2048 or MODE2_2352
         }*/
         if( (doOneTrack == 0) && (doInPlace == 1) ) {
            if( (i != 0) || ( (i == 0) && ((trackA.mode == AUDIO)||(trackA.mode == MODE2_2336)) ) ) {
               printf("Truncating bin file to %ld bytes\n", trackA.offset1);
               if( -1 == ftruncate(fileno(fdBinFile), trackA.offset1) ) {
                  perror("\nbin2iso(_chsize)");
                  exit(1);
               }
            } else {
               printf("Renaming %s to %s\n", sBinFilename, trackA.name);
               fclose(fdBinFile);
               if( 0 != rename(sBinFilename, trackA.name) ) {
                  perror("\nbin2iso(rename)");
                  exit(1);
               }

               // fix writepos for case when simply truncating...
               if((trackA.mode == MODE2_2352) || (trackA.mode == MODE1_2048)){ writepos = trackB.offset0; }

               printf("Truncating to %ld bytes\n", writepos);

               fdBinFile = fopen(trackA.name, "rb+"); // gets closed in doTrack...
               if(fdBinFile == NULL) { perror("bin2iso(fopen)"); exit(1); }

               if( -1 == ftruncate(fileno(fdBinFile), writepos) ) {
                  perror("\nbin2iso(_chsize)");
                  exit(1);
               }
            }
         }
      }
   }
   fclose(fdCueFile);
   fclose(fdBinFile);
   return(0);
}

Suricata

# TLS
drop tls any any -> any any (msg:"Drop old SSL"; ssl_version:sslv2,sslv3; sid:1;)
drop tls any any -> any any (msg:"Drop unsupported TLSv1.0/1.1"; ssl_version:tls1.0,tls1.1; sid:2;)
drop udp any any -> any any (msg:"ET EXPLOIT SUSPICIOUS DTLS 1.2 Fragmented Client Hello Possible CVE-2014-0195"; content:"|16 fe fd 00 00 00 00 00 00 00|"; depth:10; content:"|01|"; distance:3; within:1; byte_test:3,>,0,0,relative; byte_test:3,>,0,8,relative; byte_extract:3,0,frag_len,relative; byte_jump:3,5,relative; content:"|01|"; within:1; byte_test:3,!=,frag_len,0,relative; reference:url,h30499.www3.hp.com/t5/HP-Security-Research-Blog/ZDI-14-173-CVE-2014-0195-OpenSSL-DTLS-Fragment-Out-of-Bounds/ba-p/6501002; classtype:attempted-user; sid:2018561; rev:3; metadata:created_at 2014_06_13, former_category CURRENT_EVENTS, updated_at 2014_06_13;)
drop tls any any -> any any (msg:"ET EXPLOIT Possible Ticketbleed Client Hello (CVE-2016-9244)"; flow:established,from_client; content:"|16 03|"; depth:2; content:"|01|"; distance:3; within:1; content:"|03 03|"; distance:3; within:2; byte_test:1,<,32,32,relative; byte_test:1,>,1,32,relative; flowbits:set,ET.ticketbleed; flowbits:noalert; reference:cve,2016-9244; reference:url,filippo.io/Ticketbleed; classtype:misc-attack; sid:2023896; rev:3; metadata:affected_product HTTP_Server, attack_target Server, created_at 2017_02_10, deployment Datacenter, performance_impact Moderate, signature_severity Major, updated_at 2017_02_13;)
drop tls any any -> any any (msg:"ET EXPLOIT Possible Ticketbleed Server Hello (CVE-2016-9244)"; flow:established,to_client; content:"|16 03|"; depth:2; content:"|02|"; distance:3; within:1; content:"|03 03|"; distance:3; within:2; content:"|20|"; distance:32; within:1; flowbits:isset,ET.ticketbleed; reference:url,filippo.io/Ticketbleed; reference:cve,2016-9244; classtype:misc-attack; sid:2023897; rev:3; metadata:affected_product HTTP_Server, attack_target Server, created_at 2017_02_10, deployment Datacenter, performance_impact Moderate, signature_severity Major, updated_at 2017_02_13;)

# IP
drop ip any any -> any any (msg:"Drop IP loop"; sameip; sid:3;)
drop ip any any -> any any (msg:"Drop Chinese traffic"; geoip: any,CN,HK,MO; sid:4;)

# Policy
drop ip any any -> any any (msg:"Drop RFB"; app-layer-protocol:rfb; sid:5;)
drop ip any any -> any any (msg:"Drop Kerberos"; app-layer-protocol:krb5; sid:6;)
drop ip any any -> any any (msg:"Drop SNMP"; app-layer-protocol:snmp; sid:7;)
drop ip any any -> any any (msg:"Drop IKEv2"; app-layer-protocol:ikev2; sid:8;)
drop ip any any -> any any (msg:"Drop DCE/RPC"; app-layer-protocol:dcerpc; sid:9;)
drop ip any any -> any any (msg:"Drop FTP"; app-layer-protocol:ftp; sid:10;)
drop ip any any -> any any (msg:"Drop RDP"; app-layer-protocol:rdp; sid:11;)
alert ip any any -> any any (msg:"Alert SSH"; app-layer-protocol:ssh; sid:12;)
drop ip any any <> !17.0.0.0/8 !587 (msg:"Drop unallowed SMTP"; app-layer-protocol:smtp; sid:13;)
drop ip any any -> any any (msg:"Drop IMAP"; app-layer-protocol:imap; sid:14;)
drop ip any any -> any any (msg:"Drop SMB"; app-layer-protocol:smb; sid:15;)
drop ip any any -> any any (msg:"Drop NFS"; app-layer-protocol:nfs; sid:16;)
drop ip any any -> any any (msg:"Drop TFTP"; app-layer-protocol:tftp; sid:17;)
drop ip any any -> any any (msg:"Drop DNS"; app-layer-protocol:dns; sid:18;)
drop ip any any -> any any (msg:"Drop DHCP"; app-layer-protocol:dhcp; sid:19;)
alert ip any any -> any any (msg:"Alert HTTP"; app-layer-protocol:http; sid:20;)
drop ip any any -> any any (msg:"Drop MQTT"; app-layer-protocol:mqtt; sid:21;)
#drop ip any any -> any any (msg:"Drop MODBUS"; app-layer-protocol:modbus; sid:22;)
#drop ip any any -> any any (msg:"Drop DNP3"; app-layer-protocol:dnp3; sid:23;)
#drop ip any any -> any any (msg:"Drop ENIP"; app-layer-protocol:enip; sid:24;)
drop ip any any -> any any (msg:"Drop SIP"; app-layer-protocol:sip; sid:25;)
drop ip !192.168.1.108 any <> !192.168.1.108 any (msg:"Drop unallowed NTP"; app-layer-protocol:ntp; sid:26;)
#drop ip any any -> any any (msg:"Drop HTTP2"; app-layer-protocol:http2; sid:27;)

# ICMP
drop icmp any any -> any any (msg:"ET DOS ICMP Path MTU lowered below acceptable threshold"; itype: 3; icode: 4; byte_test:2,<,576,6; byte_test:2,!=,0,7; reference:cve,CAN-2004-1060; reference:url,www.microsoft.com/technet/security/bulletin/MS05-019.mspx; reference:url,isc.sans.org/diary.php?date=2005-04-12; reference:url,doc.emergingthreats.net/bin/view/Main/2001882; classtype:denial-of-service; sid:2001882; rev:10; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop icmp any any -> any any (msg:"ET EXPLOIT Possible CVE-2020-11902 ICMPv4 parameter problem with tunnel inside"; itype:12; reference:url,www.jsof-tech.com/ripple20/; classtype:attempted-admin; sid:2030389; rev:1; metadata:created_at 2020_06_22, former_category EXPLOIT, performance_impact Significant, signature_severity Major, updated_at 2020_06_22;)
drop icmp any any -> any any (msg:"ET EXPLOIT Possible CVE-2020-11910 anomalous ICMPv4 type 3,code 4 Path MTU Discovery"; itype:3; icode:4; reference:url,www.jsof-tech.com/ripple20/; classtype:attempted-admin; sid:2030390; rev:1; metadata:created_at 2020_06_22, former_category EXPLOIT, performance_impact Significant, signature_severity Major, updated_at 2020_06_22;)
drop icmp any any -> any any (msg:"ET EXPLOIT Possible CVE-2020-1191 anomalous ICMPv4 Address Mask Reply message (type 18, code 0)"; itype:18; icode:0; reference:url,www.jsof-tech.com/ripple20/; classtype:attempted-admin; sid:2030391; rev:1; metadata:created_at 2020_06_22, former_category EXPLOIT, performance_impact Significant, signature_severity Major, updated_at 2020_06_22;)

# eDonkey
drop udp any any -> any any (msg:"ET P2P Edonkey IP Reply"; flowbits:isset,BEedk.ip.requestect; dsize:<20; content:"|e3 1c|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003309; classtype:policy-violation; sid:2003309; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey IP Query End"; dsize:<20; content:"|e3 1d|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003316; classtype:policy-violation; sid:2003316; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Publicize File ACK"; dsize:<20; content:"|e3 0d|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003311; classtype:policy-violation; sid:2003311; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Connect Request"; dsize:25; content:"|e3 0a|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003312; classtype:policy-violation; sid:2003312; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Search Request (by file hash)"; dsize:19; content:"|e3 0e 14|"; depth:3; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003314; classtype:policy-violation; sid:2003314; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Get Sources Request (by hash)"; dsize:19; content:"|e3 9a|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003318; classtype:policy-violation; sid:2003318; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P Edonkey Server Status"; flow:established; dsize:14; content:"|e3 09 00 00 00 34|"; depth:6; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003324; classtype:policy-violation; sid:2003324; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P eDonkey File Status"; flow: to_server,established; content:"|e3 14|"; depth: 2; reference:url,www.edonkey.com; reference:url,doc.emergingthreats.net/bin/view/Main/2001296; classtype:policy-violation; sid:2001296; rev:9; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P eDonkey File Status Request"; flow: to_server,established; content:"|e3 11|"; depth: 2; reference:url,www.edonkey.com; reference:url,doc.emergingthreats.net/bin/view/Main/2001297; classtype:policy-violation; sid:2001297; rev:10; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P eDonkey Server Status Request"; content:"|e3 96|"; depth: 2; reference:url,www.edonkey.com; reference:url,doc.emergingthreats.net/bin/view/Main/2001298; classtype:policy-violation; sid:2001298; rev:9; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P eDonkey Server Status"; content:"|e3 97|"; depth: 2; reference:url,www.edonkey.com; reference:url,doc.emergingthreats.net/bin/view/Main/2001299; classtype:policy-violation; sid:2001299; rev:9; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Overnet (Edonkey) Server Announce"; content:"|00 00 02 03 00 6c 6f 63|"; offset: 36; content:"|00 62 63 70 3a 2f 2f|"; distance: 1; reference:url,www.overnet.com; reference:url,doc.emergingthreats.net/bin/view/Main/2000335; classtype:policy-violation; sid:2000335; rev:9; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P Edonkey Client to Server Hello"; flow:established; dsize:>5; content:"|e3|"; offset:1; content:"|01|"; distance:4; within:5; content:"|02 01 00 01|"; distance:26; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003323; classtype:policy-violation; sid:2003323; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P Edonkey Server Message"; flow:established; dsize:>10; content:"|e3|"; depth:1; content:"|38|"; distance:4; within:5; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003321; classtype:policy-violation; sid:2003321; rev:5; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P Edonkey Server List"; flow:established; dsize:>12; content:"|e3|"; depth:1; content:"|32|"; distance:4; within:5; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003322; classtype:policy-violation; sid:2003322; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Search Reply"; dsize:>200; content:"|e3 0f|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003315; classtype:policy-violation; sid:2003315; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Publicize File"; dsize:>15; content:"|e3 0c|"; depth:2; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003310; classtype:policy-violation; sid:2003310; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P Edonkey Search Request (search by name)"; dsize:>5; content:"|e3 98|"; depth:2; content:"|01|"; within:3; reference:url,www.giac.org/certified_professionals/practicals/gcih/0446.php; reference:url,doc.emergingthreats.net/bin/view/Main/2003319; classtype:policy-violation; sid:2003319; rev:4; metadata:created_at 2010_07_30, updated_at 2019_01_18;)

# Torrent
drop tcp any any -> any any (msg:"ET P2P BitTorrent Announce"; flow: to_server,established; content:"/announce"; reference:url,bitconjurer.org/BitTorrent/protocol.html; reference:url,doc.emergingthreats.net/bin/view/Main/2000369; classtype:policy-violation; sid:2000369; rev:6; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P BitTorrent DHT ping request"; content:"d1|3a|ad2|3a|id20|3a|"; depth:12; nocase; threshold: type both, count 1, seconds 300, track by_src; reference:url,wiki.theory.org/BitTorrentDraftDHTProtocol; reference:url,doc.emergingthreats.net/bin/view/Main/2008581; classtype:policy-violation; sid:2008581; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P BitTorrent DHT announce_peers request"; content:"d1|3a|ad2|3a|id20|3a|"; nocase; depth:14; content:"e1|3a|q13|3a|announce_peer1|3a|"; nocase; distance:55; threshold: type both, count 1, seconds 300, track by_src; reference:url,wiki.theory.org/BitTorrentDraftDHTProtocol; reference:url,doc.emergingthreats.net/bin/view/Main/2008585; classtype:policy-violation; sid:2008585; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P BitTorrent DHT nodes reply"; content:"d1|3a|rd2|3a|id20|3a|"; nocase; depth:12; content:"5|3a|nodes"; nocase; distance:20; within:7; threshold: type both, count 1, seconds 300, track by_src; reference:url,wiki.theory.org/BitTorrentDraftDHTProtocol; reference:url,doc.emergingthreats.net/bin/view/Main/2008583; classtype:policy-violation; sid:2008583; rev:4; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P BitTorrent DHT get_peers request"; content:"d1|3a|ad2|3a|id20|3a|"; nocase; offset:12; content:"9|3a|info_hash20|3a|"; nocase; distance:20; within:14; content:"e1|3a|q9|3a|get_peers1|3a|"; nocase; distance:20; threshold: type both, count 1, seconds 300, track by_src; reference:url,wiki.theory.org/BitTorrentDraftDHTProtocol; reference:url,doc.emergingthreats.net/bin/view/Main/2008584; classtype:policy-violation; sid:2008584; rev:5; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop udp any any -> any any (msg:"ET P2P BitTorrent DHT find_node request"; content:"d1|3a|ad2|3a|id20|3a|"; nocase; depth:24; content:"6|3a|target20|3a|"; nocase; distance:20; content:"e1|3a|q9|3a|find_node1|3a|"; nocase; distance:20; content:"e1|3a|q9|3a|find_node1|3a|"; distance:20; nocase; threshold: type both, count 1, seconds 300, track by_src; reference:url,wiki.theory.org/BitTorrentDraftDHTProtocol; reference:url,doc.emergingthreats.net/bin/view/Main/2008582; classtype:policy-violation; sid:2008582; rev:7; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P BitTorrent Traffic"; flow: established; content:"|0000400907000000|"; depth:8; threshold: type limit, count 1, seconds 120, track by_src; reference:url,bitconjurer.org/BitTorrent/protocol.html; reference:url,doc.emergingthreats.net/bin/view/Main/2000357; classtype:policy-violation; sid:2000357; rev:9; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
drop tcp any any -> any any (msg:"ET P2P BitTorrent peer sync"; flow:established; content:"|00 00 00 0d 06 00|"; depth:6; threshold: type limit, track by_dst, seconds 300, count 1; reference:url,bitconjurer.org/BitTorrent/protocol.html; reference:url,doc.emergingthreats.net/bin/view/Main/2000334; classtype:policy-violation; sid:2000334; rev:13; metadata:created_at 2010_07_30, updated_at 2010_07_30;)

# STUN
alert udp any any -> any any (msg:"Pass STUN Binding Request"; content:"|00 01|"; depth:2; content:"|21 12 a4 42|"; distance:2; within:4; sid:28;)
alert udp any any -> any any (msg:"Pass STUN Binding Response"; content:"|01 01|"; depth:2; content:"|21 12 a4 42|"; distance:2; within:4; sid:29;)
alert udp any any -> any any (msg:"Pass STUN Binding Error"; content:"|01 11|"; depth:2; content:"|21 12 a4 42|"; distance:2; within:4; sid:30;)
alert udp any any -> any any (msg:"Pass STUN Shared Secret Request"; content:"|00 02|"; depth:2; content:"|21 12 a4 42|"; distance:2; within:4; sid:31;)
alert udp any any -> any any (msg:"Pass STUN Shared Secret Response"; content:"|01 02|"; depth:2; content:"|21 12 a4 42|"; distance:2; within:4; sid:32;)
alert udp any any -> any any (msg:"Pass STUN Shared Secret Error"; content:"|01 12|"; depth:2; content:"|21 12 a4 42|"; distance:2; within:4; sid:33;)

# Apple
drop udp any any -> any any (msg:"ET WEB_CLIENT Apple Quicktime RTSP Content-Type overflow attempt"; content:"RTSP/"; nocase; depth:5; content:"|0a|Content-Type|3a|"; nocase; distance:0; isdataat:50,relative; content:!"|0a|"; within:50; reference:url,www.kb.cert.org/vuls/id/659761; reference:url,www.milw0rm.com/exploits/4657; reference:url,doc.emergingthreats.net/2007704; classtype:attempted-user; sid:2007704; rev:6; metadata:affected_product Web_Browsers, affected_product Web_Browser_Plugins, attack_target Client_Endpoint, created_at 2010_07_30, deployment Perimeter, signature_severity Major, tag Web_Client_Attacks, updated_at 2016_07_01;)
drop udp any 1024:65535 -> any any (msg:"ET INFO QUIC UDP Internet Connections Protocol Client Hello (OUTBOUND)"; flow:to_server; content:"|80 01|CHLO"; content:"PAD"; content:"SNI"; content:"CCS"; content:"PDMD"; content:"VERS"; nocase;flowbits:set,ET.QUIC.FirstClientHello; reference:url,tools.ietf.org/html/draft-tsvwg-quic-protocol-00; classtype:protocol-command-decode; sid:2022996; rev:1; metadata:attack_target Client_Endpoint, created_at 2016_08_01, deployment Perimeter, performance_impact Low, signature_severity Major, updated_at 2016_08_01;)
drop udp any 1024:65535 <> any any (msg:"ET INFO SOCKSv5 UDP Proxy Connect Request"; content:"|00 00|"; depth:2; content:"|01|"; offset:3; depth:1; threshold:type both, track by_dst, count 1, seconds 900; reference:url,handlers.sans.org/wsalusky/rants/; reference:url,en.wikipedia.org/wiki/SOCKS; reference:url,ss5.sourceforge.net/socks4.protocol.txt; reference:url,ss5.sourceforge.net/socks4A.protocol.txt; reference:url,www.ietf.org/rfc/rfc1928.txt; reference:url,www.ietf.org/rfc/rfc1929.txt; reference:url,www.ietf.org/rfc/rfc1961.txt; reference:url,www.ietf.org/rfc/rfc3089.txt; reference:url,doc.emergingthreats.net/bin/view/Main/2003287; classtype:protocol-command-decode; sid:2003287; rev:7; metadata:created_at 2010_07_30, former_category MALWARE, updated_at 2017_10_27;)

Job stack

type job string
type stack struct {
  sync.Mutex
  jobs []job
}

func (s *stack) push(in job) {
  s.Lock()
  if s.jobs == nil || len(s.jobs) == 0 {
    s.jobs = []job{in}
  } else {
    s.jobs = append(s.jobs, in)
  }
  s.Unlock()
}

func (s *stack) pop() (job, error) {
  if s.jobs == nil || len(s.jobs) == 0 {
    return "", fmt.Errorf("pila vuota")
  }
  out := s.jobs[0]
  s.Lock()
  if len(s.jobs) == 1 {
    s.jobs = []job{}
  } else {
    s.jobs = s.jobs[1:]
  }
  s.Unlock()
  return out, nil
}

func main() {
  done := make(chan bool)

  var items stack

  go func(items *stack) {
    for {
      select {
      case <-time.Tick(time.Second / 3):
        items.push(job(fmt.Sprintf("job %v", time.Now())))
      }
    }
  }(&items)

  go func(items *stack, done chan bool) {
    for {
      select {
      case <-time.Tick(time.Second / 5):
        item, err := items.pop()
        if err != nil {
          log.Println(err)
        } else {
          log.Println(item)
        }
      case <-done:
        log.Println("chiudo")
        time.Sleep(2 * time.Second)
        done <- true
        return
      }
    }
  }(&items, done)

  log.Println("sono il main")
  time.Sleep(30 * time.Second)
  done <- true
  pippo := <-done
  log.Printf("fine del main %v", pippo)
}

Portchk

require 'socket'
require 'timeout'

unless ARGV.length == 2
  abort "Usage: #{__FILE__} <host> <port>"
end

where = ARGV[0]
port = ARGV[1]

begin
  Timeout::timeout(10) do
    begin
      TCPSocket.new(where, port).close
      puts "connect(#{where}, #{port}) succeeded"
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError
      puts "connect(#{where}, #{port}) errored"
    end
  end
rescue Timeout::Error
  puts "connect(#{where}, #{port}) failed"
end

Dupes

require 'find'
require 'digest/sha2'
require 'optparse'
require 'set'

# optparse
args = { :dir => nil , :del => false }
arguments = OptionParser.new do |arg|

  arg.banner = "Usage: #{__FILE__} [options]"

  arg.on("-d", "--dir DIRECTORY", "directory to find duplicates") do |dir|
    args[:dir] = dir
  end

  arg.on("-f", "--force", "remove without prompting.") do
    args[:del] = true
  end

  arg.on("-h", "--help", "print help message") do
    puts arguments
    exit 0
  end
end

arguments.parse!
exit 1 if args[:dir] == nil

# digests
hashes = Hash.new
puts "Building digests ..."

Find.find(args[:dir]) do |path|
  STDOUT.flush
  hash = nil

  if (not FileTest.directory?(path) and not FileTest.symlink?(path)\
      and not FileTest.blockdev?(path) and not FileTest.chardev?(path)\
      and not FileTest.socket?(path) and not FileTest.pipe?(path)\
      and not FileTest.zero?(path)) then

    begin
      digest = Digest::SHA2.new
      File.open(path, 'r') do |fd|
        while buffer = fd.read(9216)
          digest.update(buffer)
        end
      end
      hash = digest.hexdigest

    rescue NoMemoryError
      puts "NoMemoryError on #{path}"
      GC.start
    rescue IOError
      puts "IOError on #{path}"
      GC.start
    rescue Errno::ENOSYS; next
    rescue Errno::EACCES; next
    rescue Errno::EINVAL; next
    rescue => e
      puts "Error on #{path}, exception #{e}"
      exit 255
    end
  end

  if (hashes[hash]) then
    hashes[hash].add(path)
  else
    hashes[hash] = Set.new.add(path)
  end
end

# results
hashes.each_pair do |hash, paths|
  files = paths.to_a
  choice = nil

  if (files.size > 1) then
    puts "Duplicate digest <#{hash}> for files:\n  #{files.join("\n  ")}"

    if not args[:del] then
      puts "  Delete? [y/N] "
      choice = gets.chomp == 'y' ? true : false
    end

    if args[:del] or choice then
      for i in 1...files.size
        File.delete files[i]
      end
    end

  end
end

Simplex protocol

#define MAX_PKT 1024

#define MAX_SEQ 4096

typedef unsigned int seq_nr;

#define inc(k) if(k<MAX_SEQ) k++; else k=0;

typedef struct {
  unsigned char data[MAX_PKT];
} packet;

typedef enum {
  data, ack, nack
} frame_kind;

typedef struct {
  frame_kind kind;
  seq_nr seq;
  seq_nr ack;
  packet data;
} frame;

typedef enum {
  frame_arrival
} event_type;

void wait_for_event(event_type *event);

void from_network_layer(packet *p);

void to_network_layer(packet *p);

void from_physical_layer(frame *r);

void to_physical_layer(frame *s);

void start_timer(seq_nr k);

void stop_timer(seq_nr k);

void start_ack_timer(void);

void stop_ack_timer(void);

void enable_network_layer(void);

void disable_network_layer(void);
#include <stdbool.h>
#include "protocol.h"

void sender1(void) {
  frame s;
  packet buffer;

  while (true) {
    from_network_layer(&buffer);
    s.data = buffer;
    to_physical_layer(&s);
  }
}

void receiver1(void) {
  frame r;
  event_type event;

  while (true) {
    wait_for_event(&event);
    from_physical_layer(&r);
    to_network_layer(&r.data);
  }
}
#include <stdbool.h>
#include "protocol.h"

void sender2(void) {
  frame s;
  packet buffer;
  event_type event;

  while(true) {
    from_network_layer(&buffer);
    s.data = buffer;
    to_physical_layer(&s);
    wait_for_event(&event);
  }
}

void receiver2(void) {
  frame r,s;
  event_type event;

  while(true) {
    wait_for_event(&event);
    from_physical_layer(&r);
    to_network_layer(&r.data);
    to_physical_layer(&s);
  }
}

Pixel madness

0x3+1x1+0x1+0x1+0x7+1x2+0x15+1x1+0x8+1x1+0x8+1x1+0x1+1x1+0x1+1x1+0x1+1x1+0x1+1x1+0x3+1x1+0x1+1x1+0x3+1x1+0x1+1x4+0x2+1x1+0x25
0x2+1x1+0x4+1x1+0x4+1x3+0x1+1x2+0x2+1x8+0x11+1x4+0x1+1x3+0x6+1x2+0x4+1x1+0x4+1x2+0x7+1x4+0x4+1x2+0x7+1x2+0x3+1x2+0x3
0x3+1x1+0x2+1x1+0x2+1x1+0x11+1x2+0x2+1x3+0x7+1x1+0x4+1x2+0x2+1x2+0x7+1x1+0x6+1x1+0x2+1x1+0x4+1x3+0x1+1x1+0x4+1x1+0x2+1x1+0x2+1x1+0x3+1x1+0x2+1x3+0x2+1x2+0x3
1x1+0x2+1x1+0x4+1x1+0x2+1x1+0x1+1x1+0x2+1x1+0x2+1x1+0x1+1x2+0x2+1x2+0x1+1x2+0x3+1x1+0x3+1x1+0x2+1x2+0x1+1x3+0x3+1x1+0x2+1x1+0x4+1x2+0x1+1x1+0x4+1x1+0x3+1x2+0x12+1x2+0x1+1x1+0x3+1x7+0x3
0x3+1x1+0x7+1x1+0x1+1x1+0x4+1x1+0x2+1x2+0x2+1x2+0x4+1x1+0x2+1x1+0x1+1x2+0x1+1x8+0x1+1x1+0x4+1x1+0x5+1x1+0x3+1x2+0x2+1x1+0x1+1x2+0x2+1x1+0x3+1x2+0x9+1x1+0x1+1x2+0x2+1x3+0x2+1x1                
0x7+1x1+0x4+1x1+0x4+1x1+0x1+1x1+0x1+1x7+0x3+1x1+0x1+1x2+0x3+1x1+0x1+1x6+0x1+1x1+0x3+1x1+0x2+1x1+0x14+1x2+0x8+1x1+0x10+1x2+0x3+1x2+0x1+1x1+0x1
0x6+1x5+0x4+1x1+0x7+1x1+0x2+1x1+0x3+1x2+0x4+1x1+0x8+1x1+0x3+1x2+0x1+1x2+0x3+1x1+0x8+1x1+0x2+1x2+0x1+1x1+0x3+1x7+0x5+1x2+0x2+1x1+0x2+1x2+0x3
0x1+1x1+0x2+1x1+0x1+1x2+0x5+1x1+0x6+1x2+0x3+1x1+0x2+1x1+0x1+1x2+0x20+1x8+0x1+1x1+0x1+1x1+0x4+1x2+0x3+1x1+0x2+1x2+0x3+1x2+0x7+1x2+0x3+1x2+0x4
0x2+1x1+0x3+1x5+0x5+1x2+0x7+1x1+0x4+1x2+0x2+1x1+0x2+1x2+0x1+1x1+0x3+1x1+0x6+1x2+0x2+1x2+0x3+1x2+0x2+1x3+0x1+1x1+0x6+1x3+0x3+1x5+0x3+1x1+0x4+1x1+0x5
0x4+1x2+0x3+1x2+0x3+1x1+0x5+1x2+0x2+1x1+0x1+1x1+0x1+1x1+0x1+1x2+0x9+1x1+0x3+1x1+0x2+1x1+0x1+1x1+0x2+1x1+0x1+1x2+0x2+1x1+0x2+1x1+0x1+1x1+0x4+1x3+0x1+1x1+0x2+1x2+0x3+1x2+0x3+1x1+0x5+1x1+0x4+1x1+0x2
0x6+1x5+0x4+1x1+0x1+1x1+0x2+1x2+0x6+1x1+0x1+1x7+0x4+1x3+0x3+1x1+0x4+1x1+0x2+1x2+0x4+1x1+0x6+1x1+0x6+1x8+0x3+1x1+0x5+1x1+0x7
0x2+1x1+0x3+1x6+0x4+1x1+0x1+1x3+0x4+1x1+0x2+1x2+0x4+1x1+0x5+1x1+0x2+1x1+0x3+1x2+0x3+1x1+0x2+1x3+0x1+1x1+0x2+1x2+0x3+1x3+0x2+1x3+0x9+1x1+0x4+1x2+0x7+1x2
import os
import sys

input = 'pixel_madness.txt'
output = 'pixel_madness.bin'

if not os.path.isfile(input):
    print('{} non esiste'.format(input))
    sys.exit()

if os.path.isfile(output):
    os.remove(output)
fo = open(output, 'w')

with open(input) as fi:
    for linea in fi:
        dupla = linea.split('+')
        for item in dupla:
            x = item.split('x')
            for _ in range(int(x[1])):
                if int(x[0]) == 0:
                    fo.write('X')
                else:
                    fo.write(' ')
        fo.write('\n')

fo.close()

InstallAPK

import java.io.File;
import java.io.IOException;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.tools.ant.BuildException;

/**
 * The main graphical user interface
 * @author Tommaso Gragnato
 */
public class Installer extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        InstallAPK install = new InstallAPK();

        // Nodes
        ListView<File> table = new ListView<>();
        Button selectADB = new Button();
        Button openFileButton = new Button();
        Button btn = new Button();
        ListView<String> logger = new ListView<>();

        // Select the ADB executable
        selectADB.setText("Select ADB executable");
        selectADB.setOnAction((ActionEvent event) -> {

            FileChooser fileChooser = new FileChooser();
            install.setADB(fileChooser.showOpenDialog(primaryStage));
        });

        // Select APK files for the installation list
        openFileButton.setText("Select APKs");
        openFileButton.setOnAction((ActionEvent event) -> {

            FileChooser fileChooser = new FileChooser();
            List<File> list = fileChooser.showOpenMultipleDialog(primaryStage);
            ObservableList<File> filtered = FXCollections.observableArrayList();
            for (File file : list) {
                if (file.isFile() && file.getPath().toLowerCase().endsWith(".apk")) {
                    filtered.add(file);
                }
            }
            table.setItems(filtered);
        });

        // Install APKs
        btn.setText("Install");
        btn.setOnAction((ActionEvent event) -> {

            for (File file : table.getItems()) {
                install.setAPK(file);
                try {
                    install.execute();
                    ObservableList<String> log = logger.getItems();
                    log.add(file.getPath()+" installed on every device(s)...");
                    logger.setItems(log);
                }
                catch (BuildException ex) {
                    ObservableList<String> log = logger.getItems();
                    log.add(ex.toString());
                    logger.setItems(log);
                }
            }
        });

        // Layouts
        HBox root = new HBox();
        VBox leftColumn = new VBox();
        root.getChildren().addAll(table, leftColumn);
        leftColumn.getChildren().addAll(selectADB, openFileButton, btn, logger);

        // Size and alignment
        leftColumn.setPadding(new Insets(20, 20, 20, 20));
        table.setMinWidth(500);
        selectADB.setMinWidth(460);
        openFileButton.setMinWidth(460);
        btn.setMinWidth(460);
        logger.setMinWidth(460);

        Scene scene = new Scene(root, 1000, 500);

        primaryStage.setTitle("myAPKs");
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
 * Custom task that uses the ADB tool to install a specified APK on all
 * connected devices and emulators.
 * @author Daniel Dyer
 */
public class InstallAPK extends Task
{
    private File apkFile;

    public void setAPK(File apkFile)
    {
        this.apkFile = apkFile;
    }

    @Override
    public void execute() throws BuildException
    {
        if (apkFile == null)
        {
            throw new BuildException("APK file must be specified");
        }
        try
        {
            List<String> devices = getDeviceIdentifiers();
            System.out.printf("Installing %s on %d device(s)...%n", apkFile, devices.size());
            ExecutorService executor = Executors.newFixedThreadPool(devices.size());
            List<Future<Void>> futures = new ArrayList<Future<Void>>(devices.size());
            for (final String device : devices)
            {
                futures.add(executor.submit(new Callable<Void>()
                {
                    public Void call() throws IOException, InterruptedException
                    {
                        installOnDevice(device);
                        return null;
                    }
                }));
            }
            for (Future<Void> future : futures)
            {
                future.get();
            }
            executor.shutdown();
            executor.awaitTermination(60, TimeUnit.SECONDS);
        }
        catch (Exception ex)
        {
            throw new BuildException(ex);
        }
    }

    private void installOnDevice(String device) throws IOException, InterruptedException
    {
        String[] command = new String[]{"adb", "-s", device, "install", "-r", apkFile.toString()};
        Process process = Runtime.getRuntime().exec(command);
        consumeStream(process.getInputStream(), System.out, device);
        if (process.waitFor() != 0)
        {
            consumeStream(process.getErrorStream(), System.err, device);
            throw new BuildException(String.format("Installing APK on %s failed.", device));
        }
    }

    private void consumeStream(InputStream in, PrintStream out, String tag) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        try
        {
            for (String line = reader.readLine(); line != null; line = reader.readLine())
            {
                out.println(tag != null ? String.format("[%s] %s", tag, line.trim()) : line);
            }
        }
        finally
        {
            reader.close();
        }
    }

    private List<String> getDeviceIdentifiers() throws IOException, InterruptedException
    {
        Process process = Runtime.getRuntime().exec("adb devices");
        List devices = new ArrayList<String>(10);
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        try
        {
            for (String line = reader.readLine(); line != null; line = reader.readLine())
            {
                if (line.endsWith("device"))
                {
                    devices.add(line.split("s")[0]);
                }
            }
            if (process.waitFor() != 0)
            {
                consumeStream(process.getErrorStream(), System.err, null);
                throw new BuildException("Failed getting list of connected devices/emulators.");
            }
        }
        finally
        {
            reader.close();
        }
        return devices;
    }
}

Copy

#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]);

#define BUF_SIZE 4096
#define OUTPUT_MODE 0700

int main(int argc, char *argv[]) {

  int in_fd, out_fd, byte_letti, byte_scritti;
  char buffer[BUF_SIZE];

  if (argc != 3) exit(1);
  in_fd = open(argv[1], O_RDONLY);
  if(in_fd < 0) exit(2);
  out_fd = creat(argv[2], OUTPUT_MODE);
  if(out_fd < 0) exit(3);

  while(1) {
    byte_letti = read(in_fd, buffer, BUF_SIZE);
    if(byte_letti <= 0) break;
    byte_scritti = write(out_fd, buffer, byte_letti);
    if (byte_scritti <= 0) exit(4);
  }

  close(in_fd); close(out_fd);
  if (byte_letti == 0) exit(0);
  else exit(5);
}