35 changed files with 1776 additions and 33 deletions

No files matched your search

Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+94
View File
@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="62118a1b-608f-4144-b29c-cf46419ca676" name="Changes" comment="">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/udp/SocketUDP.java" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/udp/SocketUDP.java" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 0
}</component>
<component name="ProjectId" id="3GbOdQKFlKqBjAjqjAv5TRPxr6Z" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"Application.Main.executor": "Run",
"ModuleVcsDetector.initialDetectionPerformed": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
"RunOnceActivity.git.unshallow": "true",
"git-widget-placeholder": "main",
"ignore.virus.scanning.warn.message": "true",
"kotlin-language-version-configured": "true",
"last_opened_file_path": "C:/Users/extre/OneDrive/Documentos/Faculdade/2026_02/Monitoria/Pitiupi",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.2",
"settings.editor.selected.configurable": "preferences.keymap"
}
}]]></component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi\plugins" />
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\plugins\ping" />
</key>
<key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\plugins\ping" />
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\privateChat" />
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\privateChat\src" />
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi\plugins" />
<recent name="C:\Users\extre\OneDrive\Documentos\Faculdade\2026_02\Monitoria\Pitiupi\pitiupi.mpChat\out\META-INF" />
</key>
</component>
<component name="RunManager">
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="pitiupi.Main" />
<module name="pitiupi" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="pitiupi.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.Main" />
</list>
</recent_temporary>
</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-9823dce3aa75-bf35d07a577b-intellij.indexing.shared.core-IU-252.28539.149" />
</set>
</attachedChunks>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="62118a1b-608f-4144-b29c-cf46419ca676" name="Changes" comment="" />
<created>1784236888334</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1784236888334</updated>
</task>
<servers />
</component>
</project>
+379
View File
@@ -0,0 +1,379 @@
# Plugins online no Pitiupi
Este documento descreve a extensão do sistema de plugins do Pitiupi: baixar e instalar plugins por HTTP, compartilhar os próprios plugins, atualizar plugins e atualizar o próprio Pitiupi.
- [1. Visão geral](#1-visão-geral)
- [2. O que já existia](#2-o-que-já-existia)
- [3. O que foi modificado](#3-o-que-foi-modificado)
- [4. Como funciona](#4-como-funciona)
- [5. Como usar](#5-como-usar)
- [6. Segurança](#6-segurança)
- [7. Vantagens](#7-vantagens)
- [8. Limitações](#8-limitações)
- [9. Testes](#9-testes)
- [10. Solução de problemas](#10-solução-de-problemas)
- [11. Decisões de projeto](#11-decisões-de-projeto)
---
## 1. Visão geral
Antes, para instalar um plugin era preciso ter o arquivo `.jar` na máquina e escolhê-lo num seletor de arquivos. Agora o Pitiupi também consegue:
| Item | Recurso | Onde está na interface |
| --- | --- | --- |
| 3 | Consultar um servidor de plugins, ver a lista e baixar/instalar | **Plugins > Plugins online…** |
| 4 | Iniciar um servidor HTTP próprio que compartilha os plugins instalados | **Plugins > Compartilhar meus plugins…** |
| 5 | Comparar a versão instalada com a do servidor e atualizar | Coluna **Situação** e botão **Atualizar** em *Plugins online…* |
| 6 | Verificar se há uma versão nova do Pitiupi, baixar, trocar o JAR e reiniciar | **Ajuda > Verificar atualização…** |
Tudo usa apenas o que já vem no JDK (`java.net.http.HttpClient` e `com.sun.net.httpserver.HttpServer`). Nenhuma dependência nova foi adicionada.
---
## 2. O que já existia
Os itens 1 e 2 da lista original já estavam implementados e **não foram refeitos**:
1. **Pasta de plugins com caminho absoluto.** `PitiupiHome` resolve a raiz de dados e sempre a converte para caminho absoluto. A pasta de plugins é `<raiz>/plugins`. A raiz é escolhida nesta ordem:
1. variável de ambiente `PITIUPI_HOME` (aceita `~/`);
2. `.pitiupi/` ao lado do `plugins.registry.json` (raiz do clone);
3. `$HOME/pitiupi`, como último recurso.
Usando `scripts/pitiupi.sh`, o caminho real é `<clone>/.pitiupi/plugins`.
2. **Gestão local de plugins.** Na aba **Configurações** (`SettingsPanel`): tabela de plugins instalados, **Instalar JAR…** (seletor de arquivo) e **Remover selecionado**. Depois de instalar ou remover, o app oferece reiniciar. A mesma coisa existe por linha de comando em `PluginStoreCli`.
---
## 3. O que foi modificado
### 3.1 Arquivos novos
| Arquivo | Função |
| --- | --- |
| `plugins/remote/RemotePluginEntry` | Uma linha da lista (id, nome, versão, autor, descrição, arquivo, SHA-256) |
| `plugins/remote/PluginListFormat` | Lê e gera o `lista-de-plugins.txt`; valida cada campo vindo da rede |
| `plugins/remote/PluginRepositoryClient` | Cliente HTTP: normaliza o endereço, busca a lista, baixa o JAR e confere o SHA-256 |
| `plugins/remote/PluginServer` | Servidor HTTP embutido que gera a lista na hora e serve os JARs |
| `plugins/remote/Sha256` | Hash SHA-256 de arquivo, lendo em blocos |
| `plugins/remote/VersionCompare` | Compara versões número a número (`1.10` > `1.9`) |
| `plugins/remote/PluginStatus` | Casa plugin instalado com plugin remoto e diz se há atualização |
| `platform/AppVersion` | Versão do Pitiupi (do manifesto) e caminho do JAR em execução |
| `presentation/shell/RemotePluginsDialog` | Tela *Plugins online* |
| `presentation/shell/PluginServerDialog` | Tela *Compartilhar meus plugins* |
| `presentation/shell/SelfUpdater` | Verificação e aplicação da atualização do Pitiupi |
Todos os caminhos acima são relativos a `pitiupi/src/pitiupi/`.
### 3.2 Arquivos alterados
| Arquivo | Mudança |
| --- | --- |
| `PluginStore` | Novo `installFromFile(origem, nomeDestino, atualizaCatalogo)`. A assinatura antiga continua existindo e chama a nova |
| `PluginMetadataWriter` | `metaPathFor` virou público; passa a gravar também `description` no `.plugin.meta` |
| `models/Plugin` | Novo método `getDescription()`, **não abstrato** (devolve `""`), para não quebrar plugins existentes |
| `ConfigLoader` | Novos `getString` e `setString` (usados para a chave `plugins.serverUrl`) |
| `ErrorCode` | Seis códigos novos: servidor inacessível, lista inválida, falha no download, hash não confere, falha ao iniciar servidor, falha na atualização |
| `ShellMenuBar` | Novo menu **Plugins** e novo item **Ajuda > Verificar atualização…** |
| `MainShellFrame` | Cria o `PluginServer`, passa ao menu e o encerra em `exit()` |
| `ApplicationRestarter` | `locateRunningJar` agora usa `AppVersion.runningJar()` (antes usava `getLocation().getPath()`, que devolvia caminho codificado e não funcionava fora de JAR) |
| `pitiupi/manifest.mf` | Nova linha `Implementation-Version: 1.0.0` |
| `scripts/pitiupi.sh` | O `rm -f plugins/*.jar` virou `find ... -type l -name '*.jar' -delete` (ver 4.5) |
### 3.3 Testes novos
`VersionCompareTest`, `PluginListFormatTest`, `PluginStatusTest` e `PluginServerTest` em `pitiupi/test/pitiupi/plugins/remote/`: 20 testes novos, somando 74 com os 54 que já existiam.
---
## 4. Como funciona
### 4.1 Visão geral
```
Máquina A (servidor) Máquina B (cliente)
──────────────────── ───────────────────
PluginServer (porta 9090) RemotePluginsDialog
│ │
│ <──── GET /lista-de-plugins.txt ──────────┤ "Atualizar lista"
│ lê os .jar e .plugin.meta da pasta │
│ calcula o SHA-256, monta o texto │
├───────────── texto TSV ───────────────────>│ vira a tabela
│ │
│ <──── GET /chat.jar ──────────────────────┤ "Instalar" / "Atualizar"
├───────────── bytes do JAR ────────────────>│ baixa para cache/, confere o SHA-256
│ instala em plugins/
│ pede reinício
```
É HTTP puro, independente do UDP/TCP do chat. Por isso o servidor usa outra porta (padrão **9090**): o login do Pitiupi ocupa de 8000 a 9000.
### 4.2 Formato do `lista-de-plugins.txt`
Uma linha por plugin, sete colunas separadas por **TAB**. Linhas que começam com `#` são comentário.
```
# id nome versao autor descricao arquivo sha256
chat Chat 1.2.0 Fulano Chat de sala pitiupi.chat.jar 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
```
| Coluna | Regra |
| --- | --- |
| `id` | Letras, números, `.`, `_` e `-`. Serve para casar com o plugin instalado |
| `nome` | Texto exibido na tabela |
| `versao` | Números separados por ponto (`1.2.0`) |
| `autor`, `descricao` | Texto livre (pode ficar vazio) |
| `arquivo` | Nome do JAR: só letras, números, `.`, `_`, `-`, terminando em `.jar` (sem `/`, sem `..`) |
| `sha256` | Exatamente 64 caracteres hexadecimais |
Linhas que violam alguma regra são **descartadas**, e as demais continuam valendo. Se a tabela vier vazia, confira primeiro o hash da linha.
### 4.3 O servidor embutido
| Pedido | Resposta |
| --- | --- |
| `GET /lista-de-plugins.txt` | Lista gerada **a cada pedido**, a partir dos `.jar` da pasta de plugins |
| `GET /atualizacao-pitiupi.txt` | Uma linha descrevendo o Pitiupi em execução (só se estiver rodando de um JAR) |
| `GET /pitiupi.jar` | O JAR do Pitiupi em execução |
| `GET /<nome>.jar` | O JAR da pasta de plugins com esse nome, se existir |
| outro método (POST etc.) | 405 |
| qualquer outra coisa | 404 |
Detalhes:
- A **pasta compartilhada** é a pasta de plugins instalados (`PITIUPI_HOME/plugins`).
- Versão, autor e descrição vêm do arquivo `<jar>.plugin.meta`, que o Pitiupi grava quando o plugin carrega com sucesso. Um plugin que nunca foi carregado aparece com versão `0`.
- O `id` na lista é o `arquivoId` do `.plugin.meta` (por exemplo `chat`, tanto para `chat.jar` quanto para `pitiupi.chat.jar`).
- O servidor escuta na interface escolhida em *Configurações > Saída* (`LocalNetworkInfo.bestLocalInet4Address()`), e não em todas.
- **Proteção contra path traversal:** o nome pedido nunca vira caminho. Ele precisa casar com a expressão de nome seguro e, depois, o servidor **lista a pasta** e procura um arquivo com aquele nome exato. `/..%2Fconfig.properties` dá 404 (há teste automático para isso).
### 4.4 O cliente
- `normalize("192.168.0.10:9090")` vira `http://192.168.0.10:9090/` (acrescenta `http://` e a barra final).
- Timeouts: 5 s para conectar, 10 s para a lista, 60 s para o download.
- Limites: lista de até 256 KB, JAR de até 50 MB.
- O download grava num arquivo temporário em `cache/`, calcula o SHA-256 enquanto grava e, se o hash não bater com o da lista, **apaga o temporário** e recusa a instalação.
- Toda a rede roda em `SwingWorker`, então a janela não congela.
- O endereço do servidor fica salvo em `config.properties`, na chave `plugins.serverUrl`.
### 4.5 Instalação e atualização de plugin
1. O cliente baixa para `cache/` e confere o hash.
2. Se o plugin **já está instalado**, o novo JAR substitui o arquivo existente (por exemplo `chat.jar`), em vez de usar o nome do servidor (`pitiupi.chat.jar`). Isso evita ficar com dois JARs do mesmo plugin, que seria carregado duas vezes.
3. A troca usa `ATOMIC_MOVE`: o Pitiupi nunca enxerga um JAR pela metade.
4. O download **não altera** o `plugins.registry.json` versionado.
5. O plugin só passa a valer no próximo início. Por isso a tela mostra **reinício pendente** e oferece reiniciar.
Como a atualização é detectada: `PluginStatus` casa o `id` remoto com o `arquivoId`, o `identifier` ou o nome do arquivo (sem `.jar` e sem o prefixo `pitiupi.`) de cada JAR instalado. Os estados são:
| Texto na coluna *Situação* | Significado |
| --- | --- |
| `—` | Não instalado |
| `instalado (1.2.0)` | Instalado e igual ou mais novo que o do servidor |
| `atualização: 1.2.0 → 1.3.0` | O servidor tem versão maior |
| `versão desconhecida` | JAR instalado, mas sem `.plugin.meta` (nunca foi carregado) |
| `reinício pendente` | Baixado nesta sessão; aguardando reiniciar |
### 4.6 Atualização do próprio Pitiupi
1. `AppVersion.current()` lê o `Implementation-Version` do manifesto do JAR. Fora de um JAR (IDE), devolve `0.0.0-dev` e a atualização é desativada.
2. `SelfUpdater` busca `atualizacao-pitiupi.txt` no servidor cadastrado e compara a versão.
3. Se houver versão maior e o usuário confirmar:
1. baixa o novo JAR e confere o SHA-256;
2. confere que o `Main-Class` do JAR baixado é `pitiupi.Main`;
3. copia para `pitiupi.jar.new` (mesma pasta do JAR em execução);
4. guarda o JAR atual em `pitiupi.jar.bak`;
5. troca `pitiupi.jar.new` por `pitiupi.jar` com `ATOMIC_MOVE`;
6. reinicia pelo `ApplicationRestarter`.
**Por que `.new` e depois mover:** a JVM mantém o JAR aberto e lê classes dele sob demanda. Sobrescrever o conteúdo no lugar corromperia a leitura. No Linux, o `rename` troca o nome e deixa o arquivo antigo existindo enquanto estiver aberto.
### 4.7 Mudança no `pitiupi.sh`
Antes, cada `run`/`build`/`link` apagava todos os `.jar` de `.pitiupi/plugins/`, o que destruiria qualquer plugin baixado. Agora só apaga **links simbólicos** e recria os do `plugins.registry.json`. Arquivos comuns (os baixados) sobrevivem.
---
## 5. Como usar
### 5.1 Compilar e rodar
```bash
cd ~/facul/2.26/alice/fls/pitiupi
./scripts/pitiupi.sh run --all
```
Só compilar o núcleo: `cd pitiupi && ant jar`. Testes: ver a seção 9.
### 5.2 Instalar um plugin de um servidor
1. **Plugins > Plugins online…**
2. Em *Servidor*, digite o endereço, por exemplo `192.168.0.10:9090` (o `http://` é opcional).
3. Clique em **Atualizar lista**. O endereço fica salvo para a próxima vez.
4. Selecione o plugin e clique em **Instalar** (ou **Atualizar**).
5. Confirme. O Pitiupi baixa, confere o hash e instala.
6. Aceite o reinício para o plugin passar a valer.
### 5.3 Compartilhar seus plugins
1. **Plugins > Compartilhar meus plugins…**
2. Deixe a porta em 9090 (ou escolha outra entre 1024 e 65535) e clique em **Iniciar**.
3. O campo mostra o endereço, por exemplo `192.168.0.10:9090`. Passe-o para quem quiser instalar.
4. **Parar** encerra o servidor (fechar o Pitiupi também encerra).
Se as outras máquinas não conectarem, libere a porta no firewall:
```bash
sudo ufw allow 9090/tcp
```
Para conferir de outra máquina:
```bash
curl http://192.168.0.10:9090/lista-de-plugins.txt
```
> **Dica:** o servidor lê versão e autor dos arquivos `.plugin.meta`, que só existem depois de o plugin ter carregado uma vez. Abra o Pitiupi com o plugin instalado antes de compartilhá-lo.
### 5.4 Publicar plugins num servidor web comum
Não é obrigatório usar o servidor embutido. Qualquer servidor web estático serve, desde que publique os JARs e a lista. Gerando a lista a partir de uma pasta com os JARs:
```bash
cd /caminho/da/pasta/publica
{
printf '# id\tnome\tversao\tautor\tdescricao\tarquivo\tsha256\n'
printf 'chat\tChat\t1.2.0\tAutor\tChat de sala\tpitiupi.chat.jar\t%s\n' \
"$(sha256sum pitiupi.chat.jar | cut -d' ' -f1)"
} > lista-de-plugins.txt
```
Repita a linha `printf` para cada plugin e **refaça a lista sempre que trocar um JAR** (o hash muda).
### 5.5 Atualizar o próprio Pitiupi
Quem publica a versão nova:
1. Suba o número em `pitiupi/manifest.mf` (`Implementation-Version: 1.1.0`).
2. Compile: `cd pitiupi && ant jar`.
3. Publique `pitiupi/dist/pitiupi.jar` e um `atualizacao-pitiupi.txt` com **uma linha**:
```bash
printf 'pitiupi\tPitiupi\t1.1.0\t\t\tpitiupi.jar\t%s\n' \
"$(sha256sum pitiupi.jar | cut -d' ' -f1)" > atualizacao-pitiupi.txt
```
Quem usa:
1. Rode o Pitiupi **pelo JAR** (`java -jar pitiupi.jar`) e cadastre o servidor em *Plugins online…*.
2. **Ajuda > Verificar atualização…**
3. Se houver versão nova, confirme. O programa baixa, troca o JAR e reinicia sozinho. O JAR anterior fica em `pitiupi.jar.bak`.
Se a versão nova não abrir, volte a anterior:
```bash
mv pitiupi.jar.bak pitiupi.jar
```
---
## 6. Segurança
- **Integridade:** o SHA-256 garante que o arquivo baixado é o mesmo descrito na lista (nada corrompido nem cortado no meio).
- **Autenticidade, não:** o hash vem da **mesma lista, pelo mesmo HTTP puro**. Quem controla o servidor, ou a rede entre você e ele, pode trocar o JAR e o hash juntos. Para uma rede de laboratório isso é aceitável; para algo mais sério, a evolução natural é assinar os JARs (por exemplo com Ed25519, que o JDK já suporta) e embutir a chave pública no Pitiupi, ou usar HTTPS.
- **Plugin é código:** um plugin instalado roda com o mesmo poder do Pitiupi (não há sandbox). A tela pede confirmação e avisa disso, mas **só instale de quem você confia**.
- **Validação do que vem da rede:** nome de arquivo, id e hash passam por expressões restritivas na leitura da lista, e o `PluginStore` valida de novo o nome de destino (`.jar`, sem `..`, sem `/` nem `\`).
- **Servidor sem autenticação:** quem alcançar a porta pode listar e baixar todos os JARs da pasta de plugins. Compartilhe só em redes em que isso seja aceitável.
---
## 7. Vantagens
- **Sem dependências novas:** só classes do JDK (cliente e servidor HTTP, `MessageDigest`).
- **Sem infraestrutura obrigatória:** o próprio Pitiupi vira servidor de plugins, e qualquer servidor estático também funciona.
- **Formato simples:** a lista é um `.txt` em TSV, legível e editável à mão, sem biblioteca de JSON.
- **Resistente a arquivo ruim:** uma linha inválida não derruba a lista; um download corrompido é recusado e não deixa resíduo.
- **Instalação segura contra interrupção:** troca atômica, sem JAR pela metade.
- **Não polui o repositório:** downloads não alteram o `plugins.registry.json` versionado.
- **Sem plugin duplicado:** a atualização reaproveita o nome do JAR já instalado.
- **Reversível:** a atualização do Pitiupi mantém `pitiupi.jar.bak`.
- **Compatível com o que existia:** `getDescription()` não é abstrato, a assinatura antiga de `installFromFile` continua válida, e os 54 testes anteriores seguem passando.
- **Interface sem travar:** toda a rede roda fora da thread da janela.
---
## 8. Limitações
**Segurança**
- Sem assinatura de JAR e sem HTTPS por padrão (ver a seção 6).
- Servidor embutido sem autenticação.
**Funcionamento**
- **Reinício obrigatório:** plugins são carregados só na inicialização.
- **Um único servidor cadastrado:** há uma só chave `plugins.serverUrl`.
- **Plugins do `plugins.registry.json` não se mantêm atualizados:** o `pitiupi.sh run` recompila e religa esses plugins a cada execução, desfazendo uma atualização baixada. A atualização por HTTP vale para plugins **fora** do registro.
- **Auto-atualização do Pitiupi só funciona rodando pelo JAR** (`java -jar`). Rodando por `./scripts/pitiupi.sh run`, o script recompila `pitiupi/dist/pitiupi.jar` e sobrescreve a atualização. Rodando da IDE (pasta de classes), a opção é desativada.
- **Versão desconhecida até o primeiro carregamento:** um plugin sem `.plugin.meta` aparece como `versão desconhecida` (no cliente) ou com versão `0` (no servidor).
- **Comparação de versões simples:** só números separados por ponto. Sufixos como `-beta` são ignorados (`1.0.0-beta` conta como `1.0.0`).
- **Sem verificação automática ao abrir:** a checagem de atualização é manual.
- **O servidor recalcula o hash a cada pedido de lista:** irrelevante para poucos plugins; para muitos ou muito grandes, valeria guardar em cache.
- **Sem retomada de download** nem barra de progresso.
**Plataforma**
- **Windows não foi tratado:** o Windows trava arquivos abertos, então trocar um JAR já carregado (um plugin em uso ou o `pitiupi.jar`) pode falhar. A solução seria gravar como `.update` e aplicar na próxima subida, antes de carregar os plugins. O desenvolvimento e o uso previsto são em Linux.
- **Firewall:** para outras máquinas acessarem o servidor, a porta precisa estar liberada.
**Reinício**
- `ApplicationRestarter.restart()` usa `System.exit(0)` sem passar por `shutdownGracefully()`. Os outros usuários só te removem da lista no timeout de presença (cerca de 15 s).
---
## 9. Testes
Testes automáticos (JUnit 5, pelo Ant):
```bash
cd pitiupi && ant test
```
Precisa do `junit-platform-console-standalone-1.10.2.jar` em `pitiupi/test/lib/` (o `README.md` dessa pasta diz onde baixar). Resultado atual: **74 testes, todos passando** (54 anteriores + 20 novos).
| Teste | O que cobre |
| --- | --- |
| `VersionCompareTest` | `1.10 > 1.9`, `1.0 = 1.0.0`, sufixos ignorados |
| `PluginListFormatTest` | gerar e ler devolve a mesma lista; linhas ruins descartadas; BOM; TAB dentro de campo; validação de nome de JAR |
| `PluginStatusTest` | casar instalado com remoto (por `arquivoId` e por nome); estados de atualização |
| `PluginServerTest` | lista só com JARs e metadados corretos; download com o mesmo conteúdo; hash errado recusado sem deixar resíduo; só JARs listados são servidos; `..%2F` dá 404; POST dá 405 |
**Não coberto por teste automático** (verificar à mão): as telas Swing e o fluxo de reinício, em especial a atualização do próprio Pitiupi.
---
## 10. Solução de problemas
| Sintoma | Causa provável | O que fazer |
| --- | --- | --- |
| A tabela de *Plugins online* vem vazia | Hash da linha inválido ou colunas faltando (a linha é descartada) | `curl -s http://ENDERECO/lista-de-plugins.txt` e confira 7 colunas e hash de 64 caracteres |
| "O arquivo baixado não confere com o hash" | A lista está com hash de outro arquivo (JAR foi trocado e a lista não) | Refaça a lista com `sha256sum` do JAR atual |
| "Não foi possível acessar o servidor" | Endereço errado, servidor parado ou firewall | `curl -v http://ENDERECO/lista-de-plugins.txt`; `sudo ufw allow 9090/tcp` |
| Servidor não inicia | Porta ocupada | Escolha outra porta no diálogo |
| Situação "versão desconhecida" | O plugin nunca foi carregado, então não tem `.plugin.meta` | Reinicie o Pitiupi com o plugin instalado |
| Plugin voltou à versão antiga | O plugin está no `plugins.registry.json` e o `pitiupi.sh run` o religou | Atualize pelo registro, ou use plugins fora do registro |
| "A atualização automática só funciona quando o Pitiupi roda pelo JAR" | Está rodando da IDE ou pelo script | Rode com `java -jar pitiupi/dist/pitiupi.jar` |
| Dois JARs do mesmo plugin em `plugins/` | Instalação manual com nome diferente do instalado | Apague o extra com `rm` |
---
## 11. Decisões de projeto
Sugestão de linhas para o `docs/decision-register.md`, na numeração seguinte à última existente:
| ID | Decisão | Motivação |
| --- | --- | --- |
| D31 | Lista de plugins em TSV com SHA-256 | Formato simples e editável, sem biblioteca de JSON; o hash detecta arquivo corrompido |
| D32 | Servidor HTTP em porta própria (padrão 9090) | Fora da faixa 8000–9000 do login, que é usada por UDP e TCP |
| D33 | Servidor só serve nomes que existem na pasta | Elimina path traversal: o pedido nunca vira caminho de arquivo |
| D34 | Atualização reaproveita o nome do JAR instalado | Evita dois JARs do mesmo plugin sendo carregados |
| D35 | Downloads não alteram o `plugins.registry.json` | O registro é versionado; downloads são dado de execução |
| D36 | Auto-atualização por `.new` + `ATOMIC_MOVE` + `.bak` | A JVM mantém o JAR aberto; o rename atômico não corrompe a leitura e o backup permite voltar |
+1
View File
@@ -1,3 +1,4 @@
Manifest-Version: 1.0 Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build X-COMMENT: Main-Class will be added automatically by build
Implementation-Version: 1.0.0
+7 -1
View File
@@ -7,7 +7,13 @@ public enum ErrorCode {
PLUGIN_INSTALL_FAILED("Não foi possível instalar o plugin."), PLUGIN_INSTALL_FAILED("Não foi possível instalar o plugin."),
PLUGIN_REMOVE_FAILED("Não foi possível remover o plugin."), PLUGIN_REMOVE_FAILED("Não foi possível remover o plugin."),
PLUGIN_LOAD_FAILED("Falha ao carregar um plugin."), PLUGIN_LOAD_FAILED("Falha ao carregar um plugin."),
INVALID_PATH("Caminho de arquivo inválido."); INVALID_PATH("Caminho de arquivo inválido."),
PLUGIN_SERVER_UNREACHABLE("Não foi possível acessar o servidor de plugins."),
PLUGIN_LIST_INVALID("A lista de plugins do servidor está inválida."),
PLUGIN_DOWNLOAD_FAILED("Não foi possível baixar o plugin."),
PLUGIN_HASH_MISMATCH("O arquivo baixado não confere com o hash da lista. Instalação cancelada."),
PLUGIN_SERVER_START_FAILED("Não foi possível iniciar o servidor de plugins."),
UPDATE_FAILED("Não foi possível atualizar o Pitiupi.");
private final String userMessage; private final String userMessage;
+7
View File
@@ -37,6 +37,13 @@ public abstract class Plugin {
public abstract String getAuthor(); public abstract String getAuthor();
public abstract String getVersion(); public abstract String getVersion();
/**
* Descrição curta exibida na lista de plugins online. Padrão: vazia.
*/
public String getDescription() {
return "";
}
public abstract String getIdentifier(); public abstract String getIdentifier();
/** /**
+54 -15
View File
@@ -10,6 +10,7 @@ import java.io.IOException;
import java.io.ObjectInput; import java.io.ObjectInput;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.net.*; import java.net.*;
import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -163,35 +164,73 @@ public class SocketUDP extends Thread {
* @throws ClassNotFoundException caso ocorra um erro ao verificar uma * @throws ClassNotFoundException caso ocorra um erro ao verificar uma
* mensagem de heartbeat. * mensagem de heartbeat.
*/ */
public void receive() throws UnknownHostException, IOException, ClassNotFoundException { public void receive() throws IOException {
byte[] buf = new byte[256000]; byte[] buffer = new byte[256000];
while (running) { while (running) {
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length); DatagramPacket packet = new DatagramPacket(
buffer,
buffer.length
);
try { try {
multicastSocket.receive(msgPacket); multicastSocket.receive(packet);
handlePacket(packet);
} catch (SocketException ex) {
if (!running) {
break;
}
Logger.getLogger(SocketUDP.class.getName())
.log(Level.SEVERE, "Erro no socket UDP", ex);
break;
} catch (IOException ex) { } catch (IOException ex) {
if (!running) { if (!running) {
break; break;
} }
throw ex;
Logger.getLogger(SocketUDP.class.getName())
.log(Level.SEVERE, "Erro ao receber datagrama UDP", ex);
break;
} catch (RuntimeException ex) {
Logger.getLogger(SocketUDP.class.getName())
.log(Level.WARNING, "Falha ao processar datagrama UDP", ex);
}
}
} }
Object coreMessage = tryParseCoreUdpMessage(msgPacket.getData()); private void handlePacket(DatagramPacket packet) {
byte[] data = Arrays.copyOf(
packet.getData(),
packet.getLength()
);
Object coreMessage = tryParseCoreUdpMessage(data);
if (coreMessage instanceof HeartbeatMessage heartbeat) { if (coreMessage instanceof HeartbeatMessage heartbeat) {
connectionManager.receiveHeartbeat(heartbeat, msgPacket.getAddress()); connectionManager.receiveHeartbeat(
continue; heartbeat,
packet.getAddress()
);
return;
} }
if (coreMessage instanceof GoodbyeMessage goodbye) { if (coreMessage instanceof GoodbyeMessage goodbye) {
connectionManager.receiveGoodbye(goodbye); connectionManager.receiveGoodbye(goodbye);
continue; return;
}
if (coreMessage instanceof SessionInviteMessage invite) {
connectionManager.receiveSessionInvite(invite);
continue;
} }
pluginManager.handleMessage(msgPacket.getData()); if (coreMessage instanceof SessionInviteMessage invite) {
connectionManager.receiveSessionInvite(invite);
return;
} }
pluginManager.handleMessage(data);
} }
/** /**
@@ -224,7 +263,7 @@ public class SocketUDP extends Thread {
public void run() { public void run() {
try { try {
this.receive(); this.receive();
} catch (IOException | ClassNotFoundException ex) { } catch (IOException ex) {
Logger.getLogger(SocketUDP.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(SocketUDP.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
@@ -0,0 +1,24 @@
package pitiupi.platform;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
public final class AppVersion {
private AppVersion() { }
public static String current() {
String v = AppVersion.class.getPackage().getImplementationVersion();
return v != null ? v : "0.0.0-dev";
}
/** O JAR em execução, ou vazio se estiver rodando de pasta de classes (IDE). */
public static Optional<Path> runningJar() {
try {
Path p = Path.of(AppVersion.class.getProtectionDomain().getCodeSource().getLocation().toURI());
return Files.isRegularFile(p) && p.toString().endsWith(".jar") ? Optional.of(p) : Optional.empty();
} catch (Exception e) {
return Optional.empty();
}
}
}
@@ -50,6 +50,15 @@ public final class ConfigLoader {
store(); store();
} }
public String getString(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
public void setString(String key, String value) throws IOException {
properties.setProperty(key, value);
store();
}
public boolean isMigrationCwdPluginsDone() { public boolean isMigrationCwdPluginsDone() {
return getBoolean("migration.cwdPluginsDone", false); return getBoolean("migration.cwdPluginsDone", false);
} }
@@ -0,0 +1,56 @@
package pitiupi.plugins.remote;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public final class PluginListFormat {
public static final String FILE_NAME = "lista-de-plugins.txt";
public static final String CORE_FILE_NAME = "atualizacao-pitiupi.txt";
private static final Pattern SAFE_JAR = Pattern.compile("[A-Za-z0-9._-]+\\.jar");
private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9._-]+");
private static final Pattern SHA256 = Pattern.compile("[0-9a-fA-F]{64}");
private PluginListFormat() { }
public static boolean isSafeJarName(String name) {
return name != null && SAFE_JAR.matcher(name).matches();
}
public static List<RemotePluginEntry> parse(String text) {
List<RemotePluginEntry> out = new ArrayList<>();
if (text.startsWith("\uFEFF")) {
text = text.substring(1);
}
for (String raw : text.split("\\R")) {
if (raw.isBlank() || raw.stripLeading().startsWith("#")) {
continue;
}
String[] c = raw.split("\t", -1);
if (c.length < 7) {
continue;
}
String id = c[0].trim(), file = c[5].trim(), sha = c[6].trim();
if (!SAFE_ID.matcher(id).matches() || !isSafeJarName(file)
|| !SHA256.matcher(sha).matches()) {
continue; // linha ruim não derruba a lista inteira
}
out.add(new RemotePluginEntry(id, c[1].trim(), c[2].trim(), c[3].trim(),
c[4].trim(), file, sha));
}
return out;
}
public static String format(List<RemotePluginEntry> entries) {
StringBuilder sb = new StringBuilder("# id\tnome\tversao\tautor\tdescricao\tarquivo\tsha256\n");
for (RemotePluginEntry e : entries) {
sb.append(String.join("\t", clean(e.id()), clean(e.name()), clean(e.version()),
clean(e.author()), clean(e.description()), e.file(), e.sha256())).append('\n');
}
return sb.toString();
}
private static String clean(String s) {
return s == null ? "" : s.replaceAll("[\\t\\r\\n]+", " ").trim();
}
}
@@ -0,0 +1,116 @@
package pitiupi.plugins.remote;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
import java.util.List;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
public final class PluginRepositoryClient {
private static final long MAX_JAR_BYTES = 50L * 1024 * 1024;
private static final long MAX_LIST_BYTES = 256L * 1024;
private final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
/** "192.168.0.10:9090" vira "http://192.168.0.10:9090/". */
public static URI normalize(String input) {
String s = input == null ? "" : input.trim();
if (s.isEmpty()) {
throw new IllegalArgumentException("Informe o endereço do servidor.");
}
if (!s.contains("://")) {
s = "http://" + s;
}
URI uri = URI.create(s);
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme) || uri.getHost() == null) {
throw new IllegalArgumentException("Endereço inválido: " + input);
}
return URI.create(s.endsWith("/") ? s : s + "/");
}
public List<RemotePluginEntry> fetchList(URI base, String listName) throws PitiupiException {
try {
HttpRequest req = HttpRequest.newBuilder(base.resolve(listName))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<byte[]> res = http.send(req, HttpResponse.BodyHandlers.ofByteArray());
if (res.statusCode() != 200) {
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, "HTTP " + res.statusCode());
}
if (res.body().length > MAX_LIST_BYTES) {
throw new PitiupiException(ErrorCode.PLUGIN_LIST_INVALID);
}
return PluginListFormat.parse(new String(res.body(), StandardCharsets.UTF_8));
} catch (IOException e) {
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_UNREACHABLE, e);
}
}
/** Baixa para um arquivo temporário em cacheDir, conferindo tamanho e SHA-256. */
public Path download(URI base, RemotePluginEntry entry, Path cacheDir) throws PitiupiException {
Path tmp = null;
try {
Files.createDirectories(cacheDir);
HttpRequest req = HttpRequest.newBuilder(base.resolve(entry.file()))
.timeout(Duration.ofSeconds(60)).GET().build();
HttpResponse<InputStream> res = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
if (res.statusCode() != 200) {
res.body().close();
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, "HTTP " + res.statusCode());
}
tmp = Files.createTempFile(cacheDir, "dl-", ".part");
MessageDigest md = MessageDigest.getInstance("SHA-256");
long total = 0;
try (InputStream in = res.body(); OutputStream out = Files.newOutputStream(tmp)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
total += n;
if (total > MAX_JAR_BYTES) {
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, "Arquivo grande demais");
}
md.update(buf, 0, n);
out.write(buf, 0, n);
}
}
if (!HexFormat.of().formatHex(md.digest()).equalsIgnoreCase(entry.sha256())) {
throw new PitiupiException(ErrorCode.PLUGIN_HASH_MISMATCH);
}
return tmp;
} catch (PitiupiException e) {
deleteQuietly(tmp);
throw e;
} catch (IOException | NoSuchAlgorithmException e) {
deleteQuietly(tmp);
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, e);
} catch (InterruptedException e) {
deleteQuietly(tmp);
Thread.currentThread().interrupt();
throw new PitiupiException(ErrorCode.PLUGIN_DOWNLOAD_FAILED, e);
}
}
private static void deleteQuietly(Path p) {
if (p != null) {
try { Files.deleteIfExists(p); } catch (IOException ignored) { }
}
}
}
@@ -0,0 +1,154 @@
package pitiupi.plugins.remote;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
import pitiupi.platform.AppVersion;
import pitiupi.plugins.store.PluginMetadataWriter;
public final class PluginServer {
private final Path sharedDir;
private HttpServer server;
private ExecutorService pool;
public PluginServer(Path sharedDir) {
this.sharedDir = sharedDir;
}
public synchronized void start(InetAddress bind, int port) throws PitiupiException {
if (server != null) {
return;
}
try {
// bind == null -> todas as interfaces
server = HttpServer.create(new InetSocketAddress(bind, port), 0);
pool = Executors.newFixedThreadPool(4);
server.setExecutor(pool);
server.createContext("/", this::handle);
server.start();
} catch (IOException e) {
server = null;
throw new PitiupiException(ErrorCode.PLUGIN_SERVER_START_FAILED, e);
}
}
public synchronized void stop() {
if (server != null) {
server.stop(0);
pool.shutdownNow();
server = null;
}
}
public synchronized boolean isRunning() { return server != null; }
public synchronized int getPort() { return server.getAddress().getPort(); }
private void handle(HttpExchange ex) throws IOException {
try (ex) {
if (!"GET".equals(ex.getRequestMethod())) {
reply(ex, 405, "text/plain", new byte[0]);
return;
}
String path = ex.getRequestURI().getPath();
if (("/" + PluginListFormat.FILE_NAME).equals(path)) {
byte[] body = PluginListFormat.format(buildList()).getBytes(StandardCharsets.UTF_8);
reply(ex, 200, "text/plain; charset=utf-8", body);
} else if (("/" + PluginListFormat.CORE_FILE_NAME).equals(path)) {
reply(ex, 200, "text/plain; charset=utf-8", coreList().getBytes(StandardCharsets.UTF_8));
} else {
Path jar = "/pitiupi.jar".equals(path) ? AppVersion.runningJar().orElse(null)
: findShared(path.substring(1));
if (jar == null) {
reply(ex, 404, "text/plain", new byte[0]);
return;
}
ex.getResponseHeaders().set("Content-Type", "application/java-archive");
ex.sendResponseHeaders(200, Files.size(jar));
try (OutputStream out = ex.getResponseBody()) {
Files.copy(jar, out);
}
}
} catch (IOException e) {
// cliente caiu no meio ou erro de leitura: a conexão é fechada pelo try-with-resources
}
}
/** Só serve arquivos que estão na pasta: o nome do pedido nunca vira caminho (sem path traversal). */
private Path findShared(String name) throws IOException {
if (!PluginListFormat.isSafeJarName(name)) {
return null;
}
try (Stream<Path> s = Files.list(sharedDir)) {
return s.filter(p -> p.getFileName().toString().equals(name))
.filter(Files::isRegularFile).findFirst().orElse(null);
}
}
List<RemotePluginEntry> buildList() throws IOException {
List<RemotePluginEntry> out = new ArrayList<>();
try (Stream<Path> s = Files.list(sharedDir)) {
for (Path jar : s.filter(p -> PluginListFormat.isSafeJarName(p.getFileName().toString()))
.sorted().toList()) {
String file = jar.getFileName().toString();
String stem = file.substring(0, file.length() - 4);
Properties meta = readMeta(jar);
out.add(new RemotePluginEntry(
meta.getProperty("arquivoId", stem),
meta.getProperty("displayName", meta.getProperty("name", stem)),
meta.getProperty("version", "0"),
meta.getProperty("author", ""),
meta.getProperty("description", ""),
file,
Sha256.of(jar)));
}
}
return out;
}
private String coreList() throws IOException {
Optional<Path> jar = AppVersion.runningJar();
if (jar.isEmpty()) {
return "";
}
return PluginListFormat.format(List.of(new RemotePluginEntry(
"pitiupi", "Pitiupi", AppVersion.current(), "", "", "pitiupi.jar", Sha256.of(jar.get()))));
}
private static Properties readMeta(Path jar) {
Properties p = new Properties();
Path meta = PluginMetadataWriter.metaPathFor(jar);
if (Files.isRegularFile(meta)) {
try (InputStream in = Files.newInputStream(meta)) {
p.load(in);
} catch (IOException ignored) { }
}
return p;
}
private static void reply(HttpExchange ex, int code, String type, byte[] body) throws IOException {
ex.getResponseHeaders().set("Content-Type", type);
ex.sendResponseHeaders(code, body.length == 0 ? -1 : body.length);
if (body.length > 0) {
try (OutputStream out = ex.getResponseBody()) {
out.write(body);
}
}
}
}
@@ -0,0 +1,37 @@
package pitiupi.plugins.remote;
import java.util.List;
import java.util.Optional;
import pitiupi.plugins.store.InstalledPluginRef;
public final class PluginStatus {
public enum State { NOT_INSTALLED, UP_TO_DATE, UPDATE_AVAILABLE, UNKNOWN_VERSION }
private PluginStatus() { }
/** Casa pelo id remoto contra arquivoId, identifier ou nome do arquivo (sem ".jar"/"pitiupi."). */
public static Optional<InstalledPluginRef> findInstalled(List<InstalledPluginRef> installed, String remoteId) {
for (InstalledPluginRef ref : installed) {
String stem = ref.getFileName().replaceFirst("\\.jar$", "").replaceFirst("^pitiupi\\.", "");
if (remoteId.equalsIgnoreCase(ref.getArquivoId().orElse(""))
|| remoteId.equalsIgnoreCase(ref.getIdentifier().orElse(""))
|| remoteId.equalsIgnoreCase(stem)) {
return Optional.of(ref);
}
}
return Optional.empty();
}
public static State of(RemotePluginEntry remote, Optional<InstalledPluginRef> installed) {
if (installed.isEmpty()) {
return State.NOT_INSTALLED;
}
Optional<String> v = installed.get().getVersion();
if (v.isEmpty()) {
return State.UNKNOWN_VERSION; // JAR nunca carregado: sem .plugin.meta ainda
}
return VersionCompare.compare(remote.version(), v.get()) > 0
? State.UPDATE_AVAILABLE : State.UP_TO_DATE;
}
}
@@ -0,0 +1,4 @@
package pitiupi.plugins.remote;
public record RemotePluginEntry(String id, String name, String version, String author,
String description, String file, String sha256) { }
@@ -0,0 +1,28 @@
package pitiupi.plugins.remote;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public final class Sha256 {
private Sha256() { }
public static String of(Path file) throws IOException {
try (InputStream in = Files.newInputStream(file)) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
md.update(buf, 0, n);
}
return HexFormat.of().formatHex(md.digest());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,25 @@
package pitiupi.plugins.remote;
public final class VersionCompare {
private VersionCompare() { }
public static int compare(String a, String b) {
String[] x = a.trim().split("\\."), y = b.trim().split("\\.");
for (int i = 0; i < Math.max(x.length, y.length); i++) {
int cmp = Integer.compare(part(x, i), part(y, i));
if (cmp != 0) {
return cmp;
}
}
return 0;
}
private static int part(String[] p, int i) {
if (i >= p.length) {
return 0;
}
String digits = p[i].replaceAll("^(\\d*).*$", "$1"); // "3-beta" -> "3"
return digits.isEmpty() ? 0 : Integer.parseInt(digits);
}
}
@@ -21,6 +21,7 @@ public final class PluginMetadataWriter {
props.setProperty("displayName", plugin.getDisplayName()); props.setProperty("displayName", plugin.getDisplayName());
props.setProperty("author", plugin.getAuthor()); props.setProperty("author", plugin.getAuthor());
props.setProperty("version", plugin.getVersion()); props.setProperty("version", plugin.getVersion());
props.setProperty("description", java.util.Objects.requireNonNullElse(plugin.getDescription(), ""));
String arquivoId = deriveArquivoId(jarPath, plugin); String arquivoId = deriveArquivoId(jarPath, plugin);
props.setProperty("arquivoId", arquivoId); props.setProperty("arquivoId", arquivoId);
@@ -29,7 +30,7 @@ public final class PluginMetadataWriter {
} }
} }
static Path metaPathFor(Path jarPath) { public static Path metaPathFor(Path jarPath) {
return Path.of(jarPath.toString() + ".plugin.meta"); return Path.of(jarPath.toString() + ".plugin.meta");
} }
@@ -55,27 +55,28 @@ public final class PluginStore {
} }
public Path installFromFile(Path sourceJar) throws PitiupiException, IOException { public Path installFromFile(Path sourceJar) throws PitiupiException, IOException {
return installFromFile(sourceJar, null, true);
}
public Path installFromFile(Path sourceJar, String targetName, boolean updateCatalog)
throws PitiupiException, IOException {
if (sourceJar == null || !Files.isRegularFile(sourceJar)) { if (sourceJar == null || !Files.isRegularFile(sourceJar)) {
throw new PitiupiException(ErrorCode.INVALID_PATH); throw new PitiupiException(ErrorCode.INVALID_PATH);
} }
String fileName = sourceJar.getFileName().toString(); String fileName = targetName != null ? targetName : sourceJar.getFileName().toString();
if (!fileName.endsWith(".jar") || fileName.contains("..")) { if (!fileName.endsWith(".jar") || fileName.contains("..")
|| fileName.contains("/") || fileName.contains("\\")) {
throw new PitiupiException(ErrorCode.INVALID_PATH); throw new PitiupiException(ErrorCode.INVALID_PATH);
} }
Files.createDirectories(pluginsDir);
Files.createDirectories(cacheDir);
Path dest = pluginsDir.resolve(fileName).normalize();
if (!dest.startsWith(pluginsDir.normalize().toAbsolutePath())) {
throw new PitiupiException(ErrorCode.INVALID_PATH);
}
Path tmp = cacheDir.resolve(fileName + "." + UUID.randomUUID() + ".part"); Path tmp = cacheDir.resolve(fileName + "." + UUID.randomUUID() + ".part");
Path dest = pluginsDir.resolve(fileName);
try { try {
Files.copy(sourceJar, tmp, StandardCopyOption.REPLACE_EXISTING); Files.copy(sourceJar, tmp, StandardCopyOption.REPLACE_EXISTING);
Files.move(tmp, dest, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); Files.move(tmp, dest, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
if (updateCatalog) {
rememberInCatalog(sourceJar, fileName); rememberInCatalog(sourceJar, fileName);
}
return dest; return dest;
} catch (IOException e) { } catch (IOException e) {
try { try {
@@ -57,7 +57,7 @@ public final class ApplicationRestarter {
} }
private static String locateRunningJar() { private static String locateRunningJar() {
return pitiupi.Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(); return pitiupi.platform.AppVersion.runningJar().map(java.nio.file.Path::toString).orElse(null);
} }
} }
} }
@@ -25,6 +25,8 @@ public final class MainShellFrame extends JFrame implements ShellHost {
private final PluginGalleryPanel galleryPanel; private final PluginGalleryPanel galleryPanel;
private final SettingsPanel settingsPanel; private final SettingsPanel settingsPanel;
private final JLabel statusLabel = new JLabel(" "); private final JLabel statusLabel = new JLabel(" ");
private final pitiupi.plugins.remote.PluginServer pluginServer =
new pitiupi.plugins.remote.PluginServer(pitiupi.platform.PitiupiHome.get().pluginsDirectory());
public MainShellFrame(String userName, int port) { public MainShellFrame(String userName, int port) {
setTitle("Pitiupi"); setTitle("Pitiupi");
@@ -45,7 +47,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
galleryPanel.setOpenHandler(this::openPluginTabFromGallery); galleryPanel.setOpenHandler(this::openPluginTabFromGallery);
networkUsersPanel = new NetworkUsersPanel(connectionManager); networkUsersPanel = new NetworkUsersPanel(connectionManager);
ShellMenuBar menuBar = new ShellMenuBar(); ShellMenuBar menuBar = new ShellMenuBar(this, pluginServer);
setJMenuBar(menuBar); setJMenuBar(menuBar);
JPanel center = new JPanel(new BorderLayout()); JPanel center = new JPanel(new BorderLayout());
@@ -126,6 +128,7 @@ public final class MainShellFrame extends JFrame implements ShellHost {
@Override @Override
public void exit() { public void exit() {
pluginServer.stop();
connectionManager.shutdownGracefully(); connectionManager.shutdownGracefully();
setVisible(false); setVisible(false);
dispose(); dispose();
@@ -0,0 +1,58 @@
package pitiupi.presentation.shell;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
import java.awt.Frame;
import java.awt.GridLayout;
import pitiupi.errors.PitiupiException;
import pitiupi.plugins.remote.PluginServer;
import pitiupi.presentation.shell.ui.ShellUi;
public final class PluginServerDialog extends JDialog {
public PluginServerDialog(Frame owner, PluginServer server) {
super(owner, "Compartilhar meus plugins", true);
JSpinner port = new JSpinner(new SpinnerNumberModel(9090, 1024, 65535, 1));
JButton toggle = new JButton();
JTextField url = new JTextField(24);
url.setEditable(false);
Runnable sync = () -> {
boolean on = server.isRunning();
toggle.setText(on ? "Parar" : "Iniciar");
port.setEnabled(!on);
url.setText(on ? LocalNetworkInfo.bestLocalIpv4() + ":" + server.getPort() : "");
};
toggle.addActionListener(e -> {
try {
if (server.isRunning()) {
server.stop();
} else {
port.commitEdit();
server.start(LocalNetworkInfo.bestLocalInet4Address(), (Integer) port.getValue());
}
} catch (PitiupiException ex) {
JOptionPane.showMessageDialog(this, ex.getUserMessage()
+ (ex.getCause() != null ? "\n(" + ex.getCause().getMessage() + ")" : ""));
} catch (java.text.ParseException ignored) { }
sync.run();
});
JPanel p = new JPanel(new GridLayout(0, 2, 6, 6));
p.setBorder(new EmptyBorder(10, 10, 10, 10));
p.add(new JLabel("Porta HTTP:")); p.add(port);
p.add(new JLabel("Endereço p/ outros:")); p.add(url);
p.add(ShellUi.mutedLabel("Pasta compartilhada: plugins instalados."));
p.add(toggle);
add(p);
sync.run();
pack();
setLocationRelativeTo(owner);
}
}
@@ -0,0 +1,251 @@
package pitiupi.presentation.shell;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import pitiupi.errors.PitiupiException;
import pitiupi.platform.PitiupiHome;
import pitiupi.plugins.remote.PluginListFormat;
import pitiupi.plugins.remote.PluginRepositoryClient;
import pitiupi.plugins.remote.PluginStatus;
import pitiupi.plugins.remote.RemotePluginEntry;
import pitiupi.plugins.store.InstalledPluginRef;
import pitiupi.plugins.store.PluginStore;
import pitiupi.presentation.shell.ui.ShellUi;
/**
* Plugins online: consulta um servidor, mostra a situação de cada plugin
* (não instalado, atualizado, atualização disponível) e instala ou atualiza.
*/
public final class RemotePluginsDialog extends JDialog {
private static final String CFG_URL = "plugins.serverUrl";
private final PluginRepositoryClient client = new PluginRepositoryClient();
private final PluginStore store = new PluginStore();
private final JTextField urlField = new JTextField(28);
private final DefaultTableModel model = new DefaultTableModel(
new String[]{"Nome", "Versão", "Autor", "Descrição", "Situação"}, 0) {
@Override public boolean isCellEditable(int r, int c) { return false; }
};
private final JTable table = new JTable(model);
private final JLabel status = ShellUi.mutedLabel(" ");
private final JButton installButton = new JButton("Instalar");
/** Plugins baixados nesta sessão: o .plugin.meta só é reescrito no próximo início. */
private final Set<String> pendingRestart = new HashSet<>();
private List<RemotePluginEntry> entries = List.of();
private URI currentBase;
public RemotePluginsDialog(Frame owner) {
super(owner, "Plugins online", true);
setLayout(new BorderLayout(8, 8));
((JComponent) getContentPane()).setBorder(new EmptyBorder(8, 8, 8, 8));
try {
urlField.setText(PitiupiHome.get().config().getString(CFG_URL, ""));
} catch (IOException ignored) { }
JButton refresh = new JButton("Atualizar lista");
refresh.addActionListener(e -> refresh());
JPanel top = new JPanel(new BorderLayout(6, 0));
top.add(new JLabel("Servidor:"), BorderLayout.WEST);
top.add(urlField, BorderLayout.CENTER);
top.add(refresh, BorderLayout.EAST);
add(top, BorderLayout.NORTH);
JScrollPane scroll = new JScrollPane(table);
ShellUi.borderlessScroll(scroll);
scroll.setPreferredSize(new Dimension(760, 260));
add(scroll, BorderLayout.CENTER);
installButton.addActionListener(e -> installSelected());
table.getSelectionModel().addListSelectionListener(ev -> {
if (!ev.getValueIsAdjusting()) {
updateInstallLabel();
}
});
JPanel bottom = new JPanel(new BorderLayout());
bottom.add(status, BorderLayout.CENTER);
bottom.add(installButton, BorderLayout.EAST);
add(bottom, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(owner);
}
private void refresh() {
final URI base;
try {
base = PluginRepositoryClient.normalize(urlField.getText());
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
return;
}
try {
PitiupiHome.get().config().setString(CFG_URL, urlField.getText().trim());
} catch (IOException ignored) { }
status.setText("Consultando…");
new SwingWorker<List<RemotePluginEntry>, Void>() {
@Override protected List<RemotePluginEntry> doInBackground() throws Exception {
return client.fetchList(base, PluginListFormat.FILE_NAME);
}
@Override protected void done() {
try {
entries = get();
currentBase = base;
fill();
status.setText(entries.size() + " plugin(s) no servidor");
} catch (Exception ex) {
status.setText(" ");
showError(ex);
}
}
}.execute();
}
/** Lê a pasta de plugins; se falhar, trata como "nada instalado". */
private List<InstalledPluginRef> installedNow() {
try {
return store.listInstalled();
} catch (IOException ex) {
return List.of();
}
}
private void fill() {
model.setRowCount(0);
List<InstalledPluginRef> installed = installedNow();
for (RemotePluginEntry e : entries) {
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installed, e.id());
model.addRow(new Object[]{
e.name(), e.version(), e.author(), e.description(), situation(e, inst)
});
}
updateInstallLabel();
}
private String situation(RemotePluginEntry e, Optional<InstalledPluginRef> inst) {
if (pendingRestart.contains(e.id())) {
return "reinício pendente";
}
return switch (PluginStatus.of(e, inst)) {
case NOT_INSTALLED -> "—";
case UP_TO_DATE -> "instalado (" + inst.get().getVersion().orElse("?") + ")";
case UPDATE_AVAILABLE -> "atualização: " + inst.get().getVersion().orElse("?")
+ " → " + e.version();
case UNKNOWN_VERSION -> "versão desconhecida";
};
}
private void updateInstallLabel() {
int row = table.getSelectedRow();
if (row < 0 || row >= entries.size()) {
installButton.setText("Instalar");
return;
}
RemotePluginEntry e = entries.get(table.convertRowIndexToModel(row));
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installedNow(), e.id());
boolean update = !pendingRestart.contains(e.id())
&& PluginStatus.of(e, inst) == PluginStatus.State.UPDATE_AVAILABLE;
installButton.setText(update ? "Atualizar" : "Instalar");
}
private void installSelected() {
int row = table.getSelectedRow();
if (row < 0 || currentBase == null) {
return;
}
RemotePluginEntry e = entries.get(table.convertRowIndexToModel(row));
// Se o plugin já está instalado, o novo JAR substitui o arquivo existente
// (evita ter chat.jar e pitiupi.chat.jar ao mesmo tempo).
Optional<InstalledPluginRef> inst = PluginStatus.findInstalled(installedNow(), e.id());
final String targetName = inst.map(InstalledPluginRef::getFileName).orElse(e.file());
PluginStatus.State state = PluginStatus.of(e, inst);
String question;
if (pendingRestart.contains(e.id())) {
question = e.name() + " já foi baixado nesta sessão e aguarda reinício.\nBaixar de novo?";
} else if (state == PluginStatus.State.UP_TO_DATE) {
question = e.name() + " já está na versão " + inst.get().getVersion().orElse("?")
+ ".\nReinstalar mesmo assim?";
} else if (state == PluginStatus.State.UPDATE_AVAILABLE) {
question = "Atualizar " + e.name() + " de " + inst.get().getVersion().orElse("?")
+ " para " + e.version() + "?";
} else {
question = "Instalar " + e.name() + " " + e.version() + "?";
}
question += "\nServidor: " + currentBase
+ "\nUm plugin roda com o mesmo poder do programa. Só instale de quem você confia.";
int ok = JOptionPane.showConfirmDialog(this, question,
"Confirmar", JOptionPane.YES_NO_OPTION);
if (ok != JOptionPane.YES_OPTION) {
return;
}
final URI base = currentBase;
status.setText("Baixando " + e.file() + "…");
new SwingWorker<Void, Void>() {
@Override protected Void doInBackground() throws Exception {
Path tmp = client.download(base, e, PitiupiHome.get().cacheDirectory());
try {
store.installFromFile(tmp, targetName, false);
} finally {
Files.deleteIfExists(tmp);
}
return null;
}
@Override protected void done() {
try {
get();
pendingRestart.add(e.id());
fill();
status.setText("Instalado: " + e.name());
ApplicationRestarter.promptRestartIfNeeded(RemotePluginsDialog.this);
} catch (Exception ex) {
status.setText(" ");
showError(ex);
}
}
}.execute();
}
private void showError(Exception ex) {
Throwable t = ex instanceof ExecutionException && ex.getCause() != null
? ex.getCause() : ex;
String msg = "Erro: " + t.getMessage();
if (t instanceof PitiupiException pe) {
msg = pe.getUserMessage();
if (pe.getMessage() != null && !pe.getMessage().equals(msg)) {
msg += "\n(" + pe.getMessage() + ")";
}
if (pe.getCause() != null && pe.getCause().getMessage() != null) {
msg += "\n(" + pe.getCause().getMessage() + ")";
}
}
JOptionPane.showMessageDialog(this, msg, "Plugins online", JOptionPane.WARNING_MESSAGE);
}
}
@@ -0,0 +1,110 @@
package pitiupi.presentation.shell;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import java.awt.Component;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Optional;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
import pitiupi.platform.AppVersion;
import pitiupi.platform.PitiupiHome;
import pitiupi.plugins.remote.*;
public final class SelfUpdater {
private SelfUpdater() { }
public static void checkAndPrompt(Component parent) {
Optional<Path> jar = AppVersion.runningJar();
if (jar.isEmpty()) {
JOptionPane.showMessageDialog(parent,
"A atualização automática só funciona quando o Pitiupi roda pelo JAR (java -jar).");
return;
}
final URI base;
try {
base = PluginRepositoryClient.normalize(
PitiupiHome.get().config().getString("plugins.serverUrl", ""));
} catch (Exception ex) {
JOptionPane.showMessageDialog(parent,
"Cadastre o servidor em Plugins > Plugins online… antes de verificar.");
return;
}
PluginRepositoryClient client = new PluginRepositoryClient();
new SwingWorker<Optional<RemotePluginEntry>, Void>() {
@Override protected Optional<RemotePluginEntry> doInBackground() throws Exception {
return client.fetchList(base, PluginListFormat.CORE_FILE_NAME).stream().findFirst();
}
@Override protected void done() {
try {
Optional<RemotePluginEntry> remote = get();
String current = AppVersion.current();
if (remote.isEmpty() || VersionCompare.compare(remote.get().version(), current) <= 0) {
JOptionPane.showMessageDialog(parent, "Você já está na versão mais recente (" + current + ").");
return;
}
int ok = JOptionPane.showConfirmDialog(parent,
"Versão atual: " + current + "\nDisponível: " + remote.get().version()
+ "\nBaixar, substituir e reiniciar agora?",
"Atualização do Pitiupi", JOptionPane.YES_NO_OPTION);
if (ok == JOptionPane.YES_OPTION) {
apply(parent, client, base, remote.get(), jar.get());
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(parent, "Não foi possível verificar: " + messageOf(ex));
}
}
}.execute();
}
private static void apply(Component parent, PluginRepositoryClient client, URI base,
RemotePluginEntry entry, Path jar) {
new SwingWorker<Void, Void>() {
@Override protected Void doInBackground() throws Exception {
Path tmp = client.download(base, entry, PitiupiHome.get().cacheDirectory());
try {
verifyIsPitiupi(tmp);
Path next = jar.resolveSibling(jar.getFileName() + ".new");
Files.copy(tmp, next, StandardCopyOption.REPLACE_EXISTING);
Files.copy(jar, jar.resolveSibling(jar.getFileName() + ".bak"),
StandardCopyOption.REPLACE_EXISTING);
Files.move(next, jar, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(tmp);
}
return null;
}
@Override protected void done() {
try {
get();
ApplicationRestarter.restart();
} catch (Exception ex) {
JOptionPane.showMessageDialog(parent, "Falha ao atualizar: " + messageOf(ex)
+ "\nA versão antiga foi mantida (backup: " + jar.getFileName() + ".bak).");
}
}
}.execute();
}
private static void verifyIsPitiupi(Path jar) throws Exception {
try (JarFile jf = new JarFile(jar.toFile())) {
Manifest m = jf.getManifest();
String main = m == null ? null : m.getMainAttributes().getValue("Main-Class");
if (!"pitiupi.Main".equals(main)) {
throw new PitiupiException(ErrorCode.UPDATE_FAILED, "O arquivo baixado não é um Pitiupi.");
}
}
}
private static String messageOf(Exception ex) {
Throwable t = ex.getCause() != null ? ex.getCause() : ex;
return t instanceof PitiupiException pe ? pe.getUserMessage() : String.valueOf(t.getMessage());
}
}
@@ -5,15 +5,27 @@ import javax.swing.JMenuBar;
import javax.swing.JMenuItem; import javax.swing.JMenuItem;
/** /**
* Barra de menus mínima (apenas Ajuda). * Barra de menus: Plugins (online) e Ajuda.
*/ */
public final class ShellMenuBar extends JMenuBar { public final class ShellMenuBar extends JMenuBar {
public ShellMenuBar() { public ShellMenuBar(java.awt.Frame owner, pitiupi.plugins.remote.PluginServer server) {
JMenu plugins = new JMenu("Plugins");
JMenuItem online = new JMenuItem("Plugins online…");
online.addActionListener(e -> new RemotePluginsDialog(owner).setVisible(true));
plugins.add(online);
JMenuItem share = new JMenuItem("Compartilhar meus plugins…");
share.addActionListener(e -> new PluginServerDialog(owner, server).setVisible(true));
plugins.add(share);
add(plugins);
JMenu help = new JMenu("Ajuda"); JMenu help = new JMenu("Ajuda");
JMenuItem about = new JMenuItem("Sobre"); JMenuItem about = new JMenuItem("Sobre");
about.addActionListener(e -> new AboutDialog().setVisible(true)); about.addActionListener(e -> new AboutDialog().setVisible(true));
help.add(about); help.add(about);
JMenuItem update = new JMenuItem("Verificar atualização…");
update.addActionListener(e -> SelfUpdater.checkAndPrompt(owner));
help.add(update);
add(help); add(help);
} }
} }
@@ -0,0 +1,63 @@
package pitiupi.plugins.remote;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PluginListFormatTest {
private static final String HASH = "a".repeat(64);
@Test
void formatThenParseGivesTheSameList() {
List<RemotePluginEntry> list = List.of(
new RemotePluginEntry("chat", "Chat", "1.2.0", "Fulano", "Chat de sala", "chat.jar", HASH),
new RemotePluginEntry("ping", "Ping", "0.1", "", "", "pitiupi.ping.jar", HASH));
assertEquals(list, PluginListFormat.parse(PluginListFormat.format(list)));
}
@Test
void badLinesAreDroppedButGoodOnesStay() {
String text = String.join("\n",
"# comentário",
"",
"bom\tBom\t1\ta\td\tbom.jar\t" + HASH,
"curto\tCurto\t1\ta\td\tcurto.jar", // menos de 7 colunas
"hashruim\tX\t1\ta\td\tx.jar\t1234", // hash curto
"fuga\tX\t1\ta\td\t../evil.jar\t" + HASH, // nome com ..
"barra\tX\t1\ta\td\tpasta/x.jar\t" + HASH, // nome com /
"naojar\tX\t1\ta\td\tx.txt\t" + HASH); // não termina em .jar
List<RemotePluginEntry> parsed = PluginListFormat.parse(text);
assertEquals(1, parsed.size());
assertEquals("bom", parsed.get(0).id());
}
@Test
void byteOrderMarkIsIgnored() {
List<RemotePluginEntry> parsed = PluginListFormat.parse(
"\uFEFFchat\tChat\t1\ta\td\tchat.jar\t" + HASH + "\n");
assertEquals(1, parsed.size());
}
@Test
void tabsInsideFieldsDoNotBreakColumns() {
List<RemotePluginEntry> list = List.of(
new RemotePluginEntry("chat", "Chat", "1", "a", "uma\tdescrição", "chat.jar", HASH));
List<RemotePluginEntry> back = PluginListFormat.parse(PluginListFormat.format(list));
assertEquals(1, back.size());
assertEquals("uma descrição", back.get(0).description());
}
@Test
void jarNameValidation() {
assertTrue(PluginListFormat.isSafeJarName("pitiupi.chat.jar"));
assertFalse(PluginListFormat.isSafeJarName("../x.jar"));
assertFalse(PluginListFormat.isSafeJarName("a/b.jar"));
assertFalse(PluginListFormat.isSafeJarName("x.txt"));
assertFalse(PluginListFormat.isSafeJarName(null));
}
}
@@ -0,0 +1,121 @@
package pitiupi.plugins.remote;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import pitiupi.errors.ErrorCode;
import pitiupi.errors.PitiupiException;
import pitiupi.plugins.store.PluginMetadataWriter;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PluginServerTest {
@TempDir
Path temp;
private PluginServer server;
private URI base;
private Path chatJar;
private final PluginRepositoryClient client = new PluginRepositoryClient();
@BeforeEach
void setUp() throws Exception {
Path shared = temp.resolve("shared");
Files.createDirectories(shared);
chatJar = shared.resolve("chat.jar");
Files.writeString(chatJar, "conteudo-do-jar");
Properties meta = new Properties();
meta.setProperty("arquivoId", "chat");
meta.setProperty("displayName", "Chat");
meta.setProperty("version", "1.2.0");
meta.setProperty("author", "Fulano");
meta.setProperty("description", "Chat de teste");
try (OutputStream out = Files.newOutputStream(PluginMetadataWriter.metaPathFor(chatJar))) {
meta.store(out, null);
}
Files.writeString(shared.resolve("extra.jar"), "outro"); // sem .plugin.meta
Files.writeString(shared.resolve("notas.txt"), "nao e jar"); // não deve aparecer
server = new PluginServer(shared);
server.start(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), 0);
base = URI.create("http://127.0.0.1:" + server.getPort() + "/");
}
@AfterEach
void tearDown() {
server.stop();
}
private int status(String path, String method) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(base + path))
.method(method, HttpRequest.BodyPublishers.noBody()).build();
return HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.discarding()).statusCode();
}
@Test
void listShowsOnlyJarsAndReadsMetadata() throws Exception {
List<RemotePluginEntry> list = client.fetchList(base, PluginListFormat.FILE_NAME);
assertEquals(2, list.size());
RemotePluginEntry chat = list.get(0);
assertEquals("chat", chat.id());
assertEquals("Chat", chat.name());
assertEquals("1.2.0", chat.version());
assertEquals("Fulano", chat.author());
assertEquals(Sha256.of(chatJar), chat.sha256());
RemotePluginEntry extra = list.get(1);
assertEquals("extra", extra.id());
assertEquals("0", extra.version());
}
@Test
void downloadDeliversTheSameBytes() throws Exception {
RemotePluginEntry chat = client.fetchList(base, PluginListFormat.FILE_NAME).get(0);
Path downloaded = client.download(base, chat, temp.resolve("cache"));
assertEquals("conteudo-do-jar", Files.readString(downloaded));
}
@Test
void wrongHashIsRejectedAndNothingIsLeftBehind() throws Exception {
RemotePluginEntry bad = new RemotePluginEntry(
"chat", "Chat", "1", "", "", "chat.jar", "0".repeat(64));
Path cache = temp.resolve("cache");
PitiupiException ex = assertThrows(PitiupiException.class, () -> client.download(base, bad, cache));
assertEquals(ErrorCode.PLUGIN_HASH_MISMATCH, ex.getCode());
try (Stream<Path> s = Files.list(cache)) {
assertEquals(0, s.count());
}
}
@Test
void onlyListedJarsAreServed() throws Exception {
assertEquals(200, status("chat.jar", "GET"));
assertEquals(404, status("nao-existe.jar", "GET"));
assertEquals(404, status("notas.txt", "GET"));
assertEquals(404, status("..%2Fconfig.properties", "GET"));
assertEquals(404, status("..%2F..%2Fetc%2Fpasswd", "GET"));
}
@Test
void onlyGetIsAllowed() throws Exception {
assertEquals(405, status("chat.jar", "POST"));
}
}
@@ -0,0 +1,61 @@
package pitiupi.plugins.remote;
import org.junit.jupiter.api.Test;
import pitiupi.plugins.store.InstalledPluginRef;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PluginStatusTest {
private static RemotePluginEntry remote(String id, String version) {
return new RemotePluginEntry(id, id, version, "", "", id + ".jar", "a".repeat(64));
}
private static InstalledPluginRef installed(String file, String arquivoId, String version) {
return new InstalledPluginRef(Path.of("/x/" + file), file,
Optional.ofNullable(arquivoId), Optional.ofNullable(version),
Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
}
@Test
void matchesByFileNameWithoutPrefix() {
List<InstalledPluginRef> list = List.of(installed("pitiupi.chat.jar", null, "1.0"));
assertTrue(PluginStatus.findInstalled(list, "chat").isPresent());
}
@Test
void matchesByArquivoId() {
List<InstalledPluginRef> list = List.of(installed("chat.jar", "chat", "1.0"));
assertTrue(PluginStatus.findInstalled(list, "chat").isPresent());
}
@Test
void notInstalled() {
assertEquals(PluginStatus.State.NOT_INSTALLED,
PluginStatus.of(remote("chat", "1.0"), Optional.empty()));
}
@Test
void updateAvailableWhenRemoteIsNewer() {
Optional<InstalledPluginRef> inst = Optional.of(installed("chat.jar", "chat", "1.9.0"));
assertEquals(PluginStatus.State.UPDATE_AVAILABLE, PluginStatus.of(remote("chat", "1.10.0"), inst));
}
@Test
void upToDateWhenSameOrOlder() {
Optional<InstalledPluginRef> inst = Optional.of(installed("chat.jar", "chat", "2.0"));
assertEquals(PluginStatus.State.UP_TO_DATE, PluginStatus.of(remote("chat", "2.0"), inst));
assertEquals(PluginStatus.State.UP_TO_DATE, PluginStatus.of(remote("chat", "1.0"), inst));
}
@Test
void unknownVersionWhenThereIsNoMetadata() {
Optional<InstalledPluginRef> inst = Optional.of(installed("chat.jar", null, null));
assertEquals(PluginStatus.State.UNKNOWN_VERSION, PluginStatus.of(remote("chat", "1.0"), inst));
}
}
@@ -0,0 +1,32 @@
package pitiupi.plugins.remote;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class VersionCompareTest {
@Test
void comparesNumbersNotText() {
assertTrue(VersionCompare.compare("1.10.0", "1.9.0") > 0);
assertTrue(VersionCompare.compare("1.9.0", "1.10.0") < 0);
assertTrue(VersionCompare.compare("2.0", "1.99") > 0);
}
@Test
void missingPartsCountAsZero() {
assertEquals(0, VersionCompare.compare("1.0", "1.0.0"));
assertTrue(VersionCompare.compare("1.0.1", "1.0") > 0);
}
@Test
void equalVersionsAreEqual() {
assertEquals(0, VersionCompare.compare("3.2.1", "3.2.1"));
}
@Test
void suffixIsIgnored() {
assertEquals(0, VersionCompare.compare("1.0.0-beta", "1.0.0"));
}
}
+5
View File
@@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
+1
View File
@@ -0,0 +1 @@
PingPlugin.java
+5
View File
@@ -0,0 +1,5 @@
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" default="true" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/ping.iml" filepath="$PROJECT_DIR$/ping.iml" />
</modules>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/pitiupi/ping" isTestSource="false" packagePrefix="pitiupi.chat" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module-library">
<library>
<CLASSES>
<root url="jar://$MODULE_DIR$/../../pitiupi/dist/pitiupi.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>
+1 -1
View File
@@ -238,7 +238,7 @@ link_plugins_from_selection() {
local mode="${1:-link}" local mode="${1:-link}"
local id dir jar_rel link_name src_abs local id dir jar_rel link_name src_abs
mkdir -p "${PLUGINS_DIR}" mkdir -p "${PLUGINS_DIR}"
rm -f "${PLUGINS_DIR}/"*.jar find "${PLUGINS_DIR}" -maxdepth 1 -type l -name '*.jar' -delete
while IFS= read -r id; do while IFS= read -r id; do
[[ -z "$id" ]] && continue [[ -z "$id" ]] && continue