Skip to content

Commit

Permalink
新書き込み仕様向け、ヘッダ等のリクエスト調整
Browse files Browse the repository at this point in the history
  • Loading branch information
onihusube committed Apr 10, 2022
1 parent f4e1237 commit 6f1429e
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 88 deletions.
189 changes: 108 additions & 81 deletions 2chAPIProxy/DatProxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -955,7 +955,27 @@ private void ResPost(Session oSession, bool is2ch)
return;
}

private string Monakey = "00000000-0000-0000-0000-000000000000";
private string monakey = "00000000-0000-0000-0000-000000000000";
private string Monakey
{
get => monakey;
set
{
if (string.IsNullOrEmpty(value))
{
monakey = "00000000-0000-0000-0000-000000000000";
}
else
{
monakey = value;
}
}
}

public void ResetMonakey()
{
Monakey = "";
}

//private string Monakey = "7b6799cc2bb1eef3acadffeecc180df6d1c7caab887326120056660f6ac05b45";

Expand Down Expand Up @@ -1020,17 +1040,19 @@ private void ResPostv2(Session oSession, bool is2ch)
oSession.fullUrl = oSession.fullUrl.Replace("subbbs.cgi", "bbs.cgi");
}


String PostURI = (ViewModel.Setting.UseTLSWrite) ? (oSession.fullUrl.Replace("http://", "https://")) : (oSession.fullUrl);
HttpWebRequest Write = (HttpWebRequest)WebRequest.Create(PostURI);
Write.Method = "POST";
Write.ServicePoint.Expect100Continue = false;
Write.Headers.Clear();
//ここで指定しないとデコードされない
Write.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Write.AutomaticDecompression = DecompressionMethods.GZip;
//Write.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
//デフォルトがtrueなのでオフっとく
Write.KeepAlive = false;
Write.Connection = null; // こうしないとヘッダから消えない
// デフォルト1.0にしておく
Write.ProtocolVersion = HttpVersion.Version10;

//デバッグ出力
System.Diagnostics.Debug.WriteLine("オリジナルリクエストヘッダ");
Expand All @@ -1039,8 +1061,6 @@ private void ResPostv2(Session oSession, bool is2ch)
System.Diagnostics.Debug.WriteLine($"{header.Name}:{header.Value}");
}

// デフォルトUAを設定(優先度最低、空の時は知らない)
Write.UserAgent = BoardSettings["2chapiproxy_default"].UserAgent;

// 板毎設定の引き当て
BoardSettings PostSetting = null;
Expand All @@ -1058,25 +1078,74 @@ private void ResPostv2(Session oSession, bool is2ch)
}
}

// デフォルトUAを設定(優先度最低、空の時は知らない)
string UA = BoardSettings["2chapiproxy_default"].UserAgent;

// UAの設定
// デフォルト→板毎設定→書き込みUAの順に優先
// 書き込みUAがあればそれを使用、無ければ板毎設定、それもなければデフォルト設定
if (String.IsNullOrEmpty(WriteUA))
{
// 設定があるときだけ上書き
if (string.IsNullOrEmpty(PostSetting?.UserAgent) == false)
{
Write.UserAgent = PostSetting.UserAgent;
UA = PostSetting.UserAgent;
// お絵かき設定はどうしようね・・・
if (PostSetting.Headers.Count() == 0) PostSetting = null;
}
}
else
{
// UIの書き込みUAを私用
Write.UserAgent = WriteUA;
UA = WriteUA;
}

// 新しい書き込み仕様への対応

// 送信されてきたエンコーディング取得
var src_encoding = oSession.RequestHeaders["Content-Type"].Contains("UTF-8") switch
{
true => Encoding.UTF8,
false => Encoding.GetEncoding("Shift_JIS")
};
// 送信するエンコーディング取得
var dst_encoding = EnableUTF8Post switch
{
true => Encoding.UTF8,
false => Encoding.GetEncoding("Shift_JIS")
};

// リクエストボディの分解(URLデコードもしておく)
var post_field_map = ReqBody.Split('&')
.Select(kvpair => kvpair.Split('='))
.ToDictionary(pair => pair[0], pair => HttpUtility.UrlDecode(pair[1], src_encoding));

// referer調整
String referer = oSession.oRequest.headers["Referer"];
if (IsResPost && SetReferrer && Regex.IsMatch(referer, @"https?://\w+\.(?:(?:2|5)ch\.net|bbspink\.com)/test/read\.cgi/\w+/\d{9,}") == false)
{
var bbs = post_field_map["bbs"];
var key = post_field_map["key"];
referer = @$"https://{Write.Host}/test/read.cgi/{bbs}/{key}/";
}
else
{
referer = oSession.oRequest.headers["Referer"].Replace("2ch.net", "5ch.net").Replace("http:", "https:");
}
Write.Referer = referer;

// デフォルト設定の引き当て
// nonceの取得
//string nonce = string.Format("{0}.{1:000}", (ulong)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds, DateTime.UtcNow.Millisecond);
string nonce = string.Format("{0}.{1:000}", post_field_map["time"], DateTime.UtcNow.Millisecond);

// 各種値の計算とヘッダセット
Write.Headers.Add("X-PostSig", CreatePostsignature(post_field_map, nonce, UA, dst_encoding));
Write.Headers.Add("X-APIKey", this.APIMediator.AppKey);
Write.Headers.Add("X-PostNonce", nonce);
Write.Headers.Add("X-MonaKey", Monakey);
Write.Headers.Add("X-2ch-UA", APIMediator.X2chUA);
Write.UserAgent = UA;

// 板毎設定がなければ、デフォルト設定を引き当て
PostSetting ??= BoardSettings["2chapiproxy_default"];

// ヘッダの設定
Expand Down Expand Up @@ -1125,36 +1194,6 @@ private void ResPostv2(Session oSession, bool is2ch)
}


// 新しい書き込み仕様への対応

// 送信されてきたエンコーディング取得
var src_encoding = oSession.RequestHeaders["Content-Type"].Contains("UTF-8") switch
{
true => Encoding.UTF8,
false => Encoding.GetEncoding("Shift_JIS")
};
// 送信するエンコーディング取得
var dst_encoding = EnableUTF8Post switch
{
true => Encoding.UTF8,
false => Encoding.GetEncoding("Shift_JIS")
};

// リクエストボディの分解(URLデコードもしておく)
var post_field_map = ReqBody.Split('&')
.Select(kvpair => kvpair.Split('='))
.ToDictionary(pair => pair[0], pair => HttpUtility.UrlDecode(pair[1], src_encoding));

// nonceの取得
//string nonce = string.Format("{0}.{1:000}", (ulong)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds, DateTime.UtcNow.Millisecond);
string nonce = string.Format("{0}.{1:000}", post_field_map["time"], DateTime.UtcNow.Millisecond);

// 各種値の計算とヘッダセット
Write.Headers.Add("X-PostSig", CreatePostsignature(post_field_map, nonce, Write.UserAgent, dst_encoding));
Write.Headers.Add("X-APIKey", this.APIMediator.AppKey);
Write.Headers.Add("X-PostNonce", nonce);
Write.Headers.Add("X-MonaKey", Monakey);

// 浪人無効化が設定されていたら、sidフィールドを削除
if (ViewModel.Setting.PostRoninInvalid)
{
Expand All @@ -1177,48 +1216,35 @@ private void ResPostv2(Session oSession, bool is2ch)
// リクエストボディ再構成
ReqBody = ReConstructPostField(post_field_map, dst_encoding);

// referer調整
String referer = oSession.oRequest.headers["Referer"];
if (IsResPost && SetReferrer && Regex.IsMatch(referer, @"https?://\w+\.(?:(?:2|5)ch\.net|bbspink\.com)/test/read\.cgi/\w+/\d{9,}") == false)
{
var bbs = post_field_map["bbs"];
var key = post_field_map["key"];
referer = @$"https://{Write.Host}/test/read.cgi/{bbs}/{key}/";
}
else
{
referer = oSession.oRequest.headers["Referer"].Replace("2ch.net", "5ch.net").Replace("http:", "https:");
}
Write.Referer = referer;

if (string.IsNullOrEmpty(Proxy) == false) Write.Proxy = new WebProxy(Proxy);
Write.CookieContainer = new CookieContainer();
//送信されてきたクッキーを抽出
foreach (Match mc in Regex.Matches(oSession.oRequest.headers["Cookie"], @"(?:\s+|^)((.+?)=(?:|.+?)(?:;|$))"))
{
Cookie[mc.Groups[2].Value] = mc.Groups[1].Value;
}
Cookie.Remove("sid");
Cookie.Remove("SID");
//送信クッキーのセット
String domain = CheckWriteuri.Match(oSession.fullUrl).Groups[1].Value;
//String domain = ".5ch.net";
foreach (var cook in Cookie)
{
if (cook.Value != "")
{
var m = Regex.Match(cook.Value, @"^(.+?)=(.*?)(;|$)");
try
{
Write.CookieContainer.Add(new Cookie(m.Groups[1].Value, m.Groups[2].Value, "/", domain));
}
catch (CookieException)
{
continue;
}
//if (cook.Key == "PREN" || cook.Key == "yuki" || cook.Key == "MDMD" || cook.Key == "DMDM")
}
}

//Write.CookieContainer = new CookieContainer();
////送信されてきたクッキーを抽出
//foreach (Match mc in Regex.Matches(oSession.oRequest.headers["Cookie"], @"(?:\s+|^)((.+?)=(?:|.+?)(?:;|$))"))
//{
// Cookie[mc.Groups[2].Value] = mc.Groups[1].Value;
//}
//Cookie.Remove("sid");
//Cookie.Remove("SID");
////送信クッキーのセット
//String domain = CheckWriteuri.Match(oSession.fullUrl).Groups[1].Value;
////String domain = ".5ch.net";
//foreach (var cook in Cookie)
//{
// if (cook.Value != "")
// {
// var m = Regex.Match(cook.Value, @"^(.+?)=(.*?)(;|$)");
// try
// {
// Write.CookieContainer.Add(new Cookie(m.Groups[1].Value, m.Groups[2].Value, "/", domain));
// }
// catch (CookieException)
// {
// continue;
// }
// //if (cook.Key == "PREN" || cook.Key == "yuki" || cook.Key == "MDMD" || cook.Key == "DMDM")
// }
//}
byte[] Body = dst_encoding.GetBytes(ReqBody);
if (EnableUTF8Post)
{
Expand All @@ -1227,6 +1253,7 @@ private void ResPostv2(Session oSession, bool is2ch)
}

Write.ContentLength = Body.Length;

try
{
using (System.IO.Stream PostStream = Write.GetRequestStream())
Expand Down Expand Up @@ -1263,7 +1290,7 @@ private void ResPostv2(Session oSession, bool is2ch)
// E3000番台のエラーが帰ってきたらMonaKeyを更新する(雑な暫定対応
if (wres.Headers["X-Chx-Error"].Contains("E3331") == false && wres.Headers["X-Chx-Error"].Contains("E3"))
{
Monakey = "00000000-0000-0000-0000-000000000000";
Monakey = "";
ViewModel.OnModelNotice("MonaKeyをリセットしました。");
}

Expand Down
2 changes: 1 addition & 1 deletion 2chAPIProxy/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:_2chAPIProxy" mc:Ignorable="d" x:Class="_2chAPIProxy.MainWindow"
Title="2chAPIProxy Ver:2022.04.08 test" Height="480" Width="640"
Title="2chAPIProxy Ver:2022.04.10 test" Height="480" Width="640"
Icon="icon3.ico" WindowStartupLocation="CenterScreen" ResizeMode="CanMinimize" Background="White" d:DataContext="{d:DesignInstance {x:Type local:ViewModel}}">
<Window.InputBindings>
<KeyBinding Gesture="Ctrl+S" Command="{Binding SaveSetting}"/>
Expand Down
15 changes: 9 additions & 6 deletions 2chAPIProxy/ViewModels/ViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,7 @@ public String Appkey
{
if (_Appkey != value)
{
DatProxy.APIMediator.AppKey = Setting.Appkey = _Appkey = value;
DatProxy.APIMediator.AppKey = Setting.Appkey = _Appkey = value.TrimEnd(' ');
NoticePropertyChanged("Appkey");
}
}
Expand All @@ -900,7 +900,7 @@ public String HMkey
{
if (_HMkey != value)
{
DatProxy.APIMediator.HMKey = Setting.HMkey = _HMkey = value;
DatProxy.APIMediator.HMKey = Setting.HMkey = _HMkey = value.TrimEnd(' ');
NoticePropertyChanged("HMkey");
}
}
Expand All @@ -915,7 +915,7 @@ public String UserAgent0
{
if (_UserAgent0 != value)
{
DatProxy.APIMediator.SidUA = Setting.UserAgent0 = _UserAgent0 = value;
DatProxy.APIMediator.SidUA = Setting.UserAgent0 = _UserAgent0 = value.TrimEnd(' ');
NoticePropertyChanged("UserAgent0");
}
}
Expand All @@ -930,7 +930,7 @@ public String UserAgent1
{
if (_UserAgent1 != value)
{
DatProxy.APIMediator.X2chUA = Setting.UserAgent1 = _UserAgent1 = value;
DatProxy.APIMediator.X2chUA = Setting.UserAgent1 = _UserAgent1 = value.TrimEnd(' ');
NoticePropertyChanged("UserAgent1");
}
}
Expand All @@ -945,7 +945,7 @@ public String UserAgent2
{
if (_UserAgent2 != value)
{
DatProxy.APIMediator.DatUA = Setting.UserAgent2 = _UserAgent2 = value;
DatProxy.APIMediator.DatUA = Setting.UserAgent2 = _UserAgent2 = value.TrimEnd(' ');
NoticePropertyChanged("UserAgent2");
}
}
Expand All @@ -960,7 +960,7 @@ public String UserAgent3
{
if (_UserAgent3 != value)
{
DatProxy.WriteUA = Setting.UserAgent3 = _UserAgent3 = value;
DatProxy.WriteUA = Setting.UserAgent3 = _UserAgent3 = value.TrimEnd(' ');
NoticePropertyChanged("UserAgent3");
if (value == "") DatProxy.AllUAReplace = false;
else DatProxy.AllUAReplace = AllUAReplace;
Expand Down Expand Up @@ -1342,6 +1342,9 @@ public RelayCommand SaveSetting
Setting.change = false;
SystemLog = "現在の設定を保存しました。";
}
// Monakeyをリセット
DatProxy.ResetMonakey();
});
return _SaveSetting;
}
Expand Down
21 changes: 21 additions & 0 deletions doc/書き込み新仕様関連.md
Original file line number Diff line number Diff line change
Expand Up @@ -975,3 +975,24 @@ Content-Type:text/html; charset=Shift_JIS
Date:Thu, 07 Apr 2022 15:22:13 GMT
Server:cloudflare
```

# 2chMateのヘッダ

https://pastebin.com/UjCyrwPJ

```
POST https://mi.5ch.net/test/bbs.cgi?guid=ON HTTP/1.1
Referer: https://mi.5ch.net/test/read.cgi/news4vip/16473****/
X-PostSig: *************
X-APIKey: 8yoeAcaLXiEY1FjEuJBKgkPxirkDqn
X-PostNonce: 1647367943.904
X-MonaKey: ***************
User-Agent: Monazilla/1.00 2chMate/0.8.10.153 *********
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 117
Host: mi.5ch.net
Connection: Keep-Alive
Accept-Encoding: gzip
FROM=&mail=&MESSAGE=%E3%81%A6&bbs=news4vip&key=16473****&submit=%E6%9B%B8%E3%81%8D%E8%BE%BC%E3%82%80&time=1647367943
```

0 comments on commit 6f1429e

Please sign in to comment.