Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Core/Api/StreamSessionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,10 @@ public void Start(Guid id)
// Dos Sunshine activos no pueden compartir puertos: el segundo no arrancaría bien.
EnsurePortsAvailable(session, ActiveSessions());

// Ni el mismo usuario de Windows: compartirían su sesión de Windows.
if (FindSameWindowsUser(session, ActiveSessions(), Environment.MachineName) is { } same)
throw new InvalidOperationException(RequestCulture.T("error.userInUse", same.Name));

session.State = SessionState.Starting;
session.ErrorMessage = null;
generation = Interlocked.Increment(ref session.LifecycleGeneration);
Expand Down Expand Up @@ -1624,6 +1628,31 @@ private static void EnsurePortsAvailable(StreamSession session, IEnumerable<Stre
throw new InvalidOperationException(problem);
}

/// <summary>
/// Usuario de Windows con el que se inicia la sesión, normalizado (<c>.\USUARIO</c> para las
/// cuentas locales); null en la sesión local, que usa el de la consola, y sin usuario.
/// </summary>
internal static string? WindowsUserKey(StreamSession s, string machineName)
{
if (s.Local) return null;
if (s.Isolated) return $".\\{s.GetIsolatedUser()}".ToUpperInvariant();
if (string.IsNullOrWhiteSpace(s.Username)) return null;
var domain = (s.Domain ?? "").Trim();
if (domain is "" or "." || domain.Equals(machineName, StringComparison.OrdinalIgnoreCase)) domain = ".";
return $"{domain}\\{s.Username.Trim()}".ToUpperInvariant();
}

/// <summary>
/// Otra sesión de <paramref name="others"/> con el mismo usuario de Windows. Al arrancar, la
/// sesión RDP que ya tiene ese usuario se reutiliza: las dos acabarían en la misma sesión de
/// Windows y parar cualquiera de ellas cerraría las dos (issue #80).
/// </summary>
internal static StreamSession? FindSameWindowsUser(StreamSession session, IEnumerable<StreamSession> others, string machineName)
{
var key = WindowsUserKey(session, machineName);
return key is null ? null : others.FirstOrDefault(o => o.Id != session.Id && WindowsUserKey(o, machineName) == key);
}

private static string PortSignature(StreamSession s) =>
$"{s.StreamProtocol}|{s.SunshineStreamPort}|{s.WebRtcPort}|{s.WebRtcMediaPortMin}|{s.WebRtcMediaPortMax}";

Expand Down
31 changes: 22 additions & 9 deletions Core/Helpers/RdpSessionCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -742,15 +742,18 @@ static void RunCmdKey(params string[] args)
}

/// <summary>
/// Espera hasta 30 s a que la sesion aparezca en WTS.
/// Los primeros 10 intentos exigen protocolo RDP; del 11 al 20 acepta cualquier sesion
/// no-consola (modo ampliado, por si termsrv reporta protocolo 0 brevemente).
/// Espera a que la sesion aparezca en WTS, como mucho <see cref="SessionWaitLimit"/>.
/// La primera mitad exige protocolo RDP; la segunda acepta cualquier sesion no-consola
/// (modo ampliado, por si termsrv reporta protocolo 0 brevemente).
/// Devuelve -1 si FreeRDP murio o la sesion no aparecio (el llamador distingue
/// ambos casos consultando proc.HasExited).
/// </summary>
static int WaitForSession(Process proc, string username)
{
for (int i = 0; i < 20; i++)
var limit = SessionWaitLimit(TimeSpan.FromMilliseconds(Environment.TickCount64));
var waited = Stopwatch.StartNew();
bool relaxedListed = false;
for (int i = 0; waited.Elapsed < limit; i++)
{
// WaitForExit con timeout: si FreeRDP muere, reaccionamos al instante
// en vez de esperar a que venza el Sleep.
Expand All @@ -760,27 +763,37 @@ static int WaitForSession(Process proc, string username)
return -1;
}

bool relaxed = i >= 10;
bool relaxed = waited.Elapsed >= limit / 2;

// Solo volcamos el listado completo de sesiones en el primer intento
// y al entrar en modo ampliado — evita 20 bloques identicos en el log.
// y al entrar en modo ampliado: evita bloques identicos en el log.
int newSession = FindSessionByUsername(username, rdpOnly: !relaxed,
logSessions: i == 0 || i == 10,
logSessions: i == 0 || (relaxed && !relaxedListed),
activeOnly: true);
relaxedListed |= relaxed;

if (newSession >= 0)
{
Logger.Log($"[RDP] Sesion detectada en intento {i + 1} " +
Logger.Log($"[RDP] Sesion detectada en intento {i + 1}, a los {waited.Elapsed.TotalSeconds:0} s " +
$"({(relaxed ? "modo ampliado" : "RDP")}): " +
$"{newSession} (FreeRDP PID={proc.Id})");
return newSession;
}

Logger.Log($"[RDP] Esperando sesion... intento {i + 1}/20");
Logger.Log($"[RDP] Esperando sesion... {waited.Elapsed.TotalSeconds:0} s de {limit.TotalSeconds:0}");
}
return -1;
}

/// <summary>
/// Tiempo máximo para que aparezca la sesión: 30 s, o 2 min en los primeros 5 min tras
/// encender el equipo. Al arrancar Windows el inicio de sesión tarda mucho más (servicios
/// y perfil todavía cargando): con 30 s, las sesiones de auto-arranque fallaban tras
/// reiniciar cuando su sesión RDP ya estaba iniciando sesión (issue #80).
/// </summary>
internal static TimeSpan SessionWaitLimit(TimeSpan uptime) =>
uptime < TimeSpan.FromMinutes(5) ? TimeSpan.FromMinutes(2) : TimeSpan.FromSeconds(30);

// ── Politicas de registro ─────────────────────────────────────────────────

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/bg.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' не стартира навреме.",
"error.compositeMemberDelete": "'{0}' е в съставната сесия '{1}'. Махнете я оттам, преди да я изтриете.",
"error.compositeInUse": "'{0}' е в работеща съставна сесия.",
"error.userInUse": "'{0}' вече работи с този потребител на Windows. Две сесии с един и същ потребител биха споделяли една сесия на Windows и спирането на едната би затворило и двете. Използвайте друг потребител или изолирана сесия.",
"ext.busy": "Извършва се друга операция с разширения. Изчакайте да приключи.",
"ext.notFound": "Разширението '{0}' не е инсталирано.",
"ext.invalidSource": "'{0}' не е валидна връзка към GitHub.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' se nespustila včas.",
"error.compositeMemberDelete": "'{0}' je ve složené relaci '{1}'. Před smazáním ji odtud odeberte.",
"error.compositeInUse": "'{0}' je ve spuštěné složené relaci.",
"error.userInUse": "'{0}' už běží s tímto uživatelem Windows. Dvě relace se stejným uživatelem by sdílely jednu relaci Windows a zastavení jedné by ukončilo obě. Použijte jiného uživatele nebo izolovanou relaci.",
"ext.busy": "Probíhá jiná operace s rozšířeními. Počkejte, až skončí.",
"ext.notFound": "Rozšíření '{0}' není nainstalováno.",
"ext.invalidSource": "'{0}' není platný odkaz na GitHub.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' ist nicht rechtzeitig gestartet.",
"error.compositeMemberDelete": "'{0}' ist in der kombinierten Sitzung '{1}'. Entferne sie dort, bevor du sie löschst.",
"error.compositeInUse": "'{0}' ist in einer laufenden kombinierten Sitzung.",
"error.userInUse": "'{0}' läuft bereits mit diesem Windows-Benutzer. Zwei Sitzungen mit demselben Benutzer würden sich eine Windows-Sitzung teilen, und das Beenden einer Sitzung würde beide schließen. Verwenden Sie einen anderen Benutzer oder eine isolierte Sitzung.",
"ext.busy": "Ein anderer Erweiterungsvorgang läuft gerade. Warte, bis er abgeschlossen ist.",
"ext.notFound": "Die Erweiterung '{0}' ist nicht installiert.",
"ext.invalidSource": "'{0}' ist kein gültiger GitHub-Link.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' didn't start in time.",
"error.compositeMemberDelete": "'{0}' is in the composite session '{1}'. Remove it from there before deleting it.",
"error.compositeInUse": "'{0}' is in a running composite session.",
"error.userInUse": "'{0}' is already running with this Windows user. Two sessions with the same user would share one Windows session, and stopping either would close both. Use another user or an isolated session.",
"ext.busy": "Another extension operation is in progress. Wait for it to finish.",
"ext.notFound": "Extension '{0}' isn't installed.",
"ext.invalidSource": "'{0}' isn't a valid GitHub link.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/en_GB.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' didn't start in time.",
"error.compositeMemberDelete": "'{0}' is in the composite session '{1}'. Remove it from there before deleting it.",
"error.compositeInUse": "'{0}' is in a running composite session.",
"error.userInUse": "'{0}' is already running with this Windows user. Two sessions with the same user would share one Windows session, and stopping either would close both. Use another user or an isolated session.",
"ext.busy": "Another extension operation is in progress. Wait for it to finish.",
"ext.notFound": "Extension '{0}' isn't installed.",
"ext.invalidSource": "'{0}' isn't a valid GitHub link.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/en_US.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' didn't start in time.",
"error.compositeMemberDelete": "'{0}' is in the composite session '{1}'. Remove it from there before deleting it.",
"error.compositeInUse": "'{0}' is in a running composite session.",
"error.userInUse": "'{0}' is already running with this Windows user. Two sessions with the same user would share one Windows session, and stopping either would close both. Use another user or an isolated session.",
"ext.busy": "Another extension operation is in progress. Wait for it to finish.",
"ext.notFound": "Extension '{0}' isn't installed.",
"ext.invalidSource": "'{0}' isn't a valid GitHub link.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' no arrancó a tiempo.",
"error.compositeMemberDelete": "'{0}' está en la sesión compuesta '{1}'. Quítala de ella antes de borrarla.",
"error.compositeInUse": "'{0}' está en una sesión compuesta en marcha.",
"error.userInUse": "'{0}' ya está en marcha con este usuario de Windows. Dos sesiones con el mismo usuario compartirían la misma sesión de Windows y parar una cerraría las dos. Usa otro usuario o una sesión aislada.",
"ext.busy": "Hay otra operación de extensiones en curso. Espera a que termine.",
"ext.notFound": "La extensión '{0}' no está instalada.",
"ext.invalidSource": "'{0}' no es un enlace de GitHub válido.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' n’a pas démarré à temps.",
"error.compositeMemberDelete": "'{0}' fait partie de la session composée '{1}'. Retirez-la avant de la supprimer.",
"error.compositeInUse": "'{0}' fait partie d’une session composée en cours.",
"error.userInUse": "'{0}' est déjà en cours avec cet utilisateur Windows. Deux sessions avec le même utilisateur partageraient la même session Windows, et arrêter l'une fermerait les deux. Utilisez un autre utilisateur ou une session isolée.",
"ext.busy": "Une autre opération sur les extensions est en cours. Attendez qu'elle se termine.",
"ext.notFound": "L'extension '{0}' n'est pas installée.",
"ext.invalidSource": "'{0}' n'est pas un lien GitHub valide.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/hu.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' nem indult el időben.",
"error.compositeMemberDelete": "'{0}' szerepel a(z) '{1}' összetett munkamenetben. Törlés előtt vegye ki onnan.",
"error.compositeInUse": "'{0}' egy futó összetett munkamenetben van.",
"error.userInUse": "A(z) '{0}' már fut ezzel a Windows-felhasználóval. Két munkamenet ugyanazzal a felhasználóval egy Windows-munkamenetet használna, és az egyik leállítása mindkettőt bezárná. Használjon másik felhasználót vagy elkülönített munkamenetet.",
"ext.busy": "Egy másik bővítményművelet van folyamatban. Várd meg, amíg befejeződik.",
"ext.notFound": "A(z) '{0}' bővítmény nincs telepítve.",
"ext.invalidSource": "'{0}' nem érvényes GitHub-hivatkozás.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' non si è avviata in tempo.",
"error.compositeMemberDelete": "'{0}' è nella sessione composta '{1}'. Rimuovila da lì prima di eliminarla.",
"error.compositeInUse": "'{0}' è in una sessione composta in esecuzione.",
"error.userInUse": "'{0}' è già in esecuzione con questo utente di Windows. Due sessioni con lo stesso utente condividerebbero la stessa sessione di Windows e fermarne una chiuderebbe entrambe. Usa un altro utente o una sessione isolata.",
"ext.busy": "È in corso un'altra operazione sulle estensioni. Attendi che finisca.",
"ext.notFound": "L'estensione '{0}' non è installata.",
"ext.invalidSource": "'{0}' non è un link GitHub valido.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' が時間内に起動しませんでした。",
"error.compositeMemberDelete": "'{0}' は合成セッション '{1}' に入っています。削除する前にそこから外してください。",
"error.compositeInUse": "'{0}' は実行中の合成セッションに入っています。",
"error.userInUse": "'{0}' はこの Windows ユーザーで既に実行中です。同じユーザーの 2 つのセッションは 1 つの Windows セッションを共有し、どちらかを停止すると両方が終了します。別のユーザーか分離セッションを使用してください。",
"ext.busy": "別の拡張機能の操作が進行中です。完了するまでお待ちください。",
"ext.notFound": "拡張機能「{0}」はインストールされていません。",
"ext.invalidSource": "「{0}」は有効な GitHub リンクではありません。",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}'이(가) 제때 시작되지 않았습니다.",
"error.compositeMemberDelete": "'{0}'은(는) 합성 세션 '{1}'에 있습니다. 삭제하기 전에 거기서 빼세요.",
"error.compositeInUse": "'{0}'은(는) 실행 중인 합성 세션에 있습니다.",
"error.userInUse": "'{0}'이(가) 이미 이 Windows 사용자로 실행 중입니다. 같은 사용자의 두 세션은 하나의 Windows 세션을 공유하므로 하나를 중지하면 둘 다 닫힙니다. 다른 사용자나 격리된 세션을 사용하세요.",
"ext.busy": "다른 확장 작업이 진행 중입니다. 완료될 때까지 기다리세요.",
"ext.notFound": "확장 '{0}'이(가) 설치되어 있지 않습니다.",
"ext.invalidSource": "'{0}'은(는) 유효한 GitHub 링크가 아닙니다.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' nie uruchomiła się na czas.",
"error.compositeMemberDelete": "'{0}' jest w sesji złożonej '{1}'. Usuń ją stamtąd przed usunięciem.",
"error.compositeInUse": "'{0}' jest w uruchomionej sesji złożonej.",
"error.userInUse": "'{0}' działa już z tym użytkownikiem Windows. Dwie sesje z tym samym użytkownikiem współdzieliłyby jedną sesję Windows, a zatrzymanie jednej zamknęłoby obie. Użyj innego użytkownika lub sesji izolowanej.",
"ext.busy": "Trwa inna operacja na rozszerzeniach. Poczekaj, aż się zakończy.",
"ext.notFound": "Rozszerzenie '{0}' nie jest zainstalowane.",
"ext.invalidSource": "'{0}' nie jest prawidłowym linkiem do GitHub.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' não arrancou a tempo.",
"error.compositeMemberDelete": "'{0}' está na sessão composta '{1}'. Retire-a de lá antes de a eliminar.",
"error.compositeInUse": "'{0}' está numa sessão composta em execução.",
"error.userInUse": "'{0}' já está em execução com este utilizador do Windows. Duas sessões com o mesmo utilizador partilhariam a mesma sessão do Windows e parar uma fecharia as duas. Use outro utilizador ou uma sessão isolada.",
"ext.busy": "Está em curso outra operação de extensões. Aguarde que termine.",
"ext.notFound": "A extensão '{0}' não está instalada.",
"ext.invalidSource": "'{0}' não é uma ligação do GitHub válida.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/pt_BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' não iniciou a tempo.",
"error.compositeMemberDelete": "'{0}' está na sessão composta '{1}'. Remova-a de lá antes de excluí-la.",
"error.compositeInUse": "'{0}' está em uma sessão composta em execução.",
"error.userInUse": "'{0}' já está em execução com este usuário do Windows. Duas sessões com o mesmo usuário compartilhariam a mesma sessão do Windows e parar uma fecharia as duas. Use outro usuário ou uma sessão isolada.",
"ext.busy": "Outra operação de extensões está em andamento. Aguarde até terminar.",
"ext.notFound": "A extensão '{0}' não está instalada.",
"ext.invalidSource": "'{0}' não é um link do GitHub válido.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' не запустился вовремя.",
"error.compositeMemberDelete": "'{0}' входит в составной сеанс '{1}'. Уберите его оттуда перед удалением.",
"error.compositeInUse": "'{0}' входит в запущенный составной сеанс.",
"error.userInUse": "'{0}' уже запущен с этим пользователем Windows. Два сеанса с одним пользователем использовали бы один сеанс Windows, и остановка одного закрыла бы оба. Используйте другого пользователя или изолированный сеанс.",
"ext.busy": "Выполняется другая операция с расширениями. Дождитесь её завершения.",
"ext.notFound": "Расширение '{0}' не установлено.",
"ext.invalidSource": "'{0}' не является допустимой ссылкой на GitHub.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' startade inte i tid.",
"error.compositeMemberDelete": "'{0}' ingår i den sammansatta sessionen '{1}'. Ta bort den därifrån innan du raderar den.",
"error.compositeInUse": "'{0}' ingår i en sammansatt session som körs.",
"error.userInUse": "'{0}' körs redan med den här Windows-användaren. Två sessioner med samma användare skulle dela en Windows-session, och att stoppa den ena skulle stänga båda. Använd en annan användare eller en isolerad session.",
"ext.busy": "En annan tilläggsåtgärd pågår. Vänta tills den är klar.",
"ext.notFound": "Tillägget '{0}' är inte installerat.",
"ext.invalidSource": "'{0}' är inte en giltig GitHub-länk.",
Expand Down
1 change: 1 addition & 0 deletions Services/Localization/Locales/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"error.compositeMemberStart": "'{0}' zamanında başlamadı.",
"error.compositeMemberDelete": "'{0}', '{1}' birleşik oturumunda. Silmeden önce oradan çıkarın.",
"error.compositeInUse": "'{0}' çalışan bir birleşik oturumda.",
"error.userInUse": "'{0}' zaten bu Windows kullanıcısıyla çalışıyor. Aynı kullanıcıya sahip iki oturum tek bir Windows oturumunu paylaşır ve birini durdurmak ikisini de kapatır. Başka bir kullanıcı veya yalıtılmış oturum kullanın.",
"ext.busy": "Başka bir uzantı işlemi sürüyor. Bitmesini bekleyin.",
"ext.notFound": "'{0}' uzantısı yüklü değil.",
"ext.invalidSource": "'{0}' geçerli bir GitHub bağlantısı değil.",
Expand Down
Loading
Loading