add login support for v050124.03.05.017
[GitHub/Stricted/SpeedportHybridControl.git] / SpeedportHybridControl / Data / SpeedportHybridAPI.cs
CommitLineData
7ef085ed
S
1using Newtonsoft.Json.Linq;
2using System;
3using System.Linq;
4using System.IO;
5using System.Net;
6using System.Text;
7using System.Text.RegularExpressions;
8using System.Windows;
9using System.Threading;
10using System.Collections.Generic;
bd99ec80 11using SpeedportHybridControl.Implementations;
bd99ec80 12using Newtonsoft.Json;
bee257dd 13using SpeedportHybridControl.PageModel;
7ef085ed 14
a5a62e8d
S
15namespace SpeedportHybridControl.Data
16{
17 public class SpeedportHybridAPI : SingletonFactory<SpeedportHybridAPI>
18 {
19 public string _ip = "speedport.ip";
20 private DateTime _lastReboot = DateTime.MinValue;
21 private bool _checkIsActive = false;
22 public string _password;
23 public string _challenge;
24 public string _hash;
25 public string _derivedk;
26 public CookieContainer _cookie = new CookieContainer();
27
28 public string ip
29 {
30 get { return _ip; }
31 set { _ip = value; }
32 }
33
34 /**
7ef085ed
S
35 * Requests the password-challenge from the router.
36 *
37 * @return string
38 */
f896de0c 39 public string getChallenge_old()
a5a62e8d 40 {
f896de0c
S
41 /* var challenge = "3FFBFE45EF0B7f76b6BCADD3fccBC5ab07b1aa36EC97Ab690C23F90Fd374c016"; */
42 string response = sendRequest("data/Login.json", "csrf_token=nulltoken&showpw=0&challengev=null");
a5a62e8d
S
43 if (response.IsNullOrEmpty())
44 return string.Empty;
45
46 string challenge = string.Empty;
47 try
48 {
49 JToken jArray = JToken.Parse(response);
50
51 challenge = jArray.getVar("challengev");
52 jArray = null;
53 }
54 catch (Exception ex)
55 {
89ff0d9c 56 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
57 }
58
59 response = null;
60
61 return challenge;
62 }
f896de0c
S
63 public string getChallenge()
64 {
65 string response = sendRequest("html/content/overview/index.html");
66 if (response.IsNullOrEmpty())
67 return string.Empty;
a5a62e8d 68
f896de0c
S
69 string a = "challenge = \"";
70 if (response.IndexOf(a) == -1)
71 {
72 response = null;
73 return getChallenge_old();
74 }
75
76 string token = response.Substring((response.IndexOf(a) + a.Length), 64);
77
78 response = null;
79
80 return token;
81 }
82
83 /**
7ef085ed
S
84 * calculate the derivedk
85 *
86 * @param string $password
87 * @return string
88 */
f896de0c 89 public string getDerviedk()
a5a62e8d
S
90 {
91 return _password.sha256().pbkdf2(_challenge.Substring(0, 16));
92 }
7ef085ed 93
a5a62e8d 94 /**
7ef085ed
S
95 * login into the router with the given password
96 *
97 * @param string $password
98 * @return bool
99 */
a5a62e8d
S
100 public bool login(string password)
101 {
102 if (password.IsNullOrEmpty())
103 {
104 return false;
105 }
106
107 _cookie = new CookieContainer();
108
109 _password = password;
110 _challenge = getChallenge();
111 _hash = string.Concat(_challenge, ":", password).sha256();
112
f896de0c 113 string response = sendRequest("data/Login.json", string.Concat("csrf_token=nulltoken", "&challengev=", _challenge, "&showpw=0&password=", _hash));
a5a62e8d
S
114 if (response.IsNullOrEmpty())
115 return false;
116
f896de0c
S
117 if (response.IndexOf("challenge") != -1)
118 {
119 response = sendRequest("data/Login.json", string.Concat("csrf_token=nulltoken&showpw=0&password=", _hash));
120 if (response.IsNullOrEmpty())
121 return false;
a5a62e8d 122
f896de0c
S
123 _cookie.Add(new Cookie("challengev", _challenge) { Domain = _ip });
124 }
125
a5a62e8d
S
126 bool login = false;
127 try
128 {
129 JToken jArray = JToken.Parse(response);
130 if (jArray.getVar("login").Equals("success"))
131 {
132 if (isLoggedin().Equals(false))
133 {
134 login = false;
135 }
136 else {
137 login = true;
138 _derivedk = getDerviedk();
139 _lastReboot = getLastReboot();
7ef085ed 140 }
a5a62e8d
S
141 }
142 jArray = null;
143 }
144 catch (Exception ex)
145 {
89ff0d9c 146 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
147 }
148
149 response = null;
150
151 return login;
152 }
153
154 /**
7ef085ed
S
155 * logout
156 *
157 * @return bool
158 */
a5a62e8d
S
159 public bool logout()
160 {
161 string response = sendRequest("data/Login.json", string.Concat("csrf_token=", getToken(), "&logout=byby"));
162 if (response.IsNullOrEmpty())
163 return false;
164
165 bool logout = false;
166 try
167 {
168 JToken jArray = JToken.Parse(response);
169 if (jArray.getVar("status").Equals("ok"))
170 {
b95b5c9b
S
171 logout = true;
172 _password = "";
173 _challenge = "";
174 _cookie = new CookieContainer();
175 _lastReboot = DateTime.MinValue;
176 _hash = "";
177 _derivedk = "";
a5a62e8d
S
178 }
179
180 jArray = null;
181 }
182 catch (Exception ex)
183 {
89ff0d9c 184 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
185 }
186
187 response = null;
188
189 return logout;
190 }
191
192 /**
7ef085ed
S
193 * check if we are logged in
194 *
195 * @return bool
196 */
a5a62e8d
S
197 public bool checkLogin()
198 {
199 if (_checkIsActive.Equals(false))
200 {
201 _checkIsActive = true;
202 if (isLoggedin().Equals(false))
203 {
a5a62e8d
S
204 Thread.Sleep(400);
205
206 if (login(_password).Equals(false))
207 {
208 // should we try to relogin? login(_password);...
209 new Thread(() => { LogManager.WriteToLog("Session expired."); }).Start();
210 _password = "";
211 _challenge = "";
212 _cookie = new CookieContainer();
213 _lastReboot = DateTime.MinValue;
214 _hash = "";
215 _derivedk = "";
216
217 LoginPageModel lpm = Application.Current.FindResource("LoginPageModel") as LoginPageModel;
89ff0d9c 218 lpm.LogoutAction();
a5a62e8d
S
219 MainWindowModel mwm = Application.Current.FindResource("MainWindowModel") as MainWindowModel;
220 mwm.SwitchToLoginPage.Execute();
221
222 new Thread(() => { MessageBox.Show("Session expired.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start();
223 _checkIsActive = false;
224 return false;
225 }
226 }
227
228 _checkIsActive = false;
229 }
a5a62e8d
S
230
231 return true;
232 }
233
234 /**
7ef085ed
S
235 * check if we are logged in
236 *
237 * @param bool ischeck
238 * @return bool
239 */
a5a62e8d
S
240 public bool isLoggedin()
241 {
b95b5c9b 242 string response = sendRequest("data/heartbeat.json");
a5a62e8d
S
243 if (response.IsNullOrEmpty())
244 return false;
245
246 bool login = false;
247 try
248 {
249 JToken jArray = JToken.Parse(response);
250
b95b5c9b 251 if (jArray.getVar("loginstate").Equals("1"))
a5a62e8d
S
252 {
253 login = true;
254 }
255
256 jArray = null;
257 }
7ef085ed 258
a5a62e8d
S
259 catch (Exception ex)
260 {
89ff0d9c 261 LogManager.WriteToLog(ex.ToString());
a5a62e8d 262 }
7ef085ed 263
a5a62e8d 264 response = null;
7ef085ed 265
a5a62e8d
S
266 return login;
267 }
7ef085ed 268
a5a62e8d 269 /**
7ef085ed
S
270 * reboot the router
271 */
a5a62e8d
S
272 public void reboot()
273 {
274 if (checkLogin().Equals(false))
275 return;
276
277 string response = sendRequest("data/Reboot.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&reboot_device=true"));
278 if (response.IsNullOrEmpty())
279 return;
280 try
281 {
282 JToken jArray = JToken.Parse(response);
283 if (jArray.getVar("status").Equals("ok"))
284 {
285 new Thread(() => { MessageBox.Show("Router Reboot.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start();
286 LogManager.WriteToLog("Router Reboot.");
287 _password = "";
288 _challenge = "";
289 _cookie = new CookieContainer();
290 _hash = "";
291 _derivedk = "";
292
293 LoginPageModel lpm = Application.Current.FindResource("LoginPageModel") as LoginPageModel;
294 lpm.LoginCommand.Execute();
295 MainWindowModel mwm = Application.Current.FindResource("MainWindowModel") as MainWindowModel;
296 mwm.SwitchToLoginPage.Execute();
297 }
298
299 jArray = null;
300 }
301 catch (Exception ex)
302 {
89ff0d9c 303 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
304 }
305
306 response = null;
307 }
308
309 /**
7ef085ed
S
310 * reconnect LTE
311 *
312 * @return bool
313 */
a5a62e8d
S
314 public bool reconnectLte()
315 {
316 if (checkLogin().Equals(false))
317 return false;
7ef085ed 318
a5a62e8d 319 Thread.Sleep(400);
7ef085ed 320
a5a62e8d
S
321 string response = sendEnryptedRequest("data/modules.json", string.Concat("lte_reconn=1&csrf_token=", Uri.EscapeUriString(getToken())));
322 if (response.IsNullOrEmpty())
323 return false;
7ef085ed 324
a5a62e8d
S
325 try
326 {
327 JToken jArray = JToken.Parse(response);
7ef085ed 328
a5a62e8d 329 response = null;
7ef085ed 330
a5a62e8d
S
331 if (jArray.getVar("status").Equals("ok"))
332 {
333 jArray = null;
334 return true;
335 }
7ef085ed 336
a5a62e8d
S
337 jArray = null;
338 }
339 catch (Exception ex)
340 {
89ff0d9c 341 LogManager.WriteToLog(ex.ToString());
a5a62e8d 342 }
7ef085ed 343
a5a62e8d 344 response = null;
7ef085ed 345
a5a62e8d
S
346 return false;
347 }
7ef085ed 348
a5a62e8d 349 /**
7ef085ed
S
350 * reconnect DSL
351 *
352 * @return bool
353 */
a5a62e8d
S
354 public bool reconnectDSL()
355 {
356 if (checkLogin().Equals(false))
357 return false;
358
359 Thread.Sleep(400);
360
361 string response = sendEnryptedRequest("data/Connect.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&showpw=0&password=", _hash, "&req_connect=offline"));
362 if (response.IsNullOrEmpty())
363 return false;
364
365 bool offline = false;
366 try
367 {
368 JToken jArray = JToken.Parse(response);
369
370 response = null;
371
372 if (jArray.getVar("status").Equals("ok"))
373 {
374 offline = true;
375 }
376
377 jArray = null;
378
379 if (offline.Equals(true))
380 {
381 response = sendEnryptedRequest("data/Connect.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&showpw=0&password=", _hash, "&req_connect=online"));
382 jArray = JToken.Parse(response);
383 if (jArray.getVar("status").Equals("ok"))
384 {
385 jArray = null;
386 return true;
387 }
388 }
389 }
390 catch (Exception ex)
391 {
89ff0d9c 392 LogManager.WriteToLog(ex.ToString());
a5a62e8d 393 }
7ef085ed 394
a5a62e8d 395 response = null;
7ef085ed 396
a5a62e8d
S
397 return false;
398 }
7ef085ed 399
a5a62e8d 400 /**
7ef085ed
S
401 * change dsl connection status
402 *
403 * @param string status
404 * @return bool
405 */
a5a62e8d
S
406 public bool changeDSLStatus(string status)
407 {
408 if (checkLogin().Equals(false))
409 return false;
410
411 if (status.Equals("online") || status.Equals("offline"))
412 {
413
414 string response = sendEnryptedRequest("data/Connect.json", string.Concat("req_connect=", status, "&csrf_token=", Uri.EscapeUriString(getToken())));
415 if (response.IsNullOrEmpty())
416 return false;
417 try
418 {
419 JToken jArray = JToken.Parse(response);
420
421 response = null;
422
423 if (jArray.getVar("status").Equals("ok"))
424 {
425 jArray = null;
426 return true;
427 }
428 }
429 catch (Exception ex)
430 {
89ff0d9c 431 LogManager.WriteToLog(ex.ToString());
a5a62e8d 432 }
7ef085ed 433
a5a62e8d
S
434 response = null;
435 }
7ef085ed 436
a5a62e8d
S
437 return false;
438 }
7ef085ed 439
a5a62e8d 440 /**
7ef085ed
S
441 * change lte connection status
442 *
443 * @param string status
444 * @return bool
445 */
a5a62e8d
S
446 public bool changeLTEStatus(string status)
447 {
448 if (checkLogin().Equals(false))
449 return false;
450
451 if (status.Equals("online") || status.Equals("offline"))
452 {
453 if (status.Equals("online"))
454 status = "1";
455
456 if (status.Equals("offline"))
457 status = "0";
458
459 string response = sendEnryptedRequest("data/Modules.json", string.Concat("use_lte=", status, "&csrf_token=", Uri.EscapeUriString(getToken())));
460 if (response.IsNullOrEmpty())
461 return false;
462 try
463 {
464 JToken jArray = JToken.Parse(response);
465
466 response = null;
467
468 if (jArray.getVar("status").Equals("ok"))
469 {
470 jArray = null;
471 return true;
472 }
473 }
474 catch (Exception ex)
475 {
89ff0d9c 476 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
477 }
478
479 response = null;
480 }
481
482 return false;
483 }
484
485 /**
7ef085ed
S
486 * reset the router to Factory Default
487 * not tested
488 *
489 * @return bool
490 */
a5a62e8d
S
491 public bool resetToFactoryDefault()
492 {
493 if (checkLogin().Equals(false))
494 return false;
495
496 Thread.Sleep(400);
497
498 string response = sendEnryptedRequest("data/resetAllSetting.json", string.Concat("csrf_token=nulltoken&showpw=0&password=", _hash, "&reset_all=true"));
499 if (response.IsNullOrEmpty())
500 return false;
501
502 try
503 {
504 JToken jArray = JToken.Parse(response);
505 if (jArray.getVar("status").Equals("ok"))
506 {
507 return true;
508 }
509
510 jArray = null;
511 }
512 catch (Exception ex)
513 {
89ff0d9c 514 LogManager.WriteToLog(ex.ToString());
a5a62e8d 515 }
7ef085ed 516
a5a62e8d 517 response = null;
7ef085ed 518
a5a62e8d
S
519 return false;
520 }
7ef085ed 521
a5a62e8d 522 /**
7ef085ed
S
523 * check for firmware update
524 */
a5a62e8d
S
525 public void checkFirmware()
526 {
527 if (checkLogin().Equals(false))
528 return;
529
530 Thread.Sleep(400);
531
532 string response = sendRequest("data/checkfirm.json");
533 if (response.IsNullOrEmpty())
534 return;
535
536 try
537 {
538 bool fw_isActual = false;
539 JToken jArray = JToken.Parse(response);
540
541 if (jArray.getVar("fw_isActual").Equals("1"))
542 {
543 fw_isActual = true;
544 }
545
546 if (fw_isActual.Equals(true))
547 {
548 // Die Firmware ist aktuell.
549 MessageBox.Show("Die Firmware ist aktuell.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information);
550 }
551 else {
552 // Es liegt eine neuere Firmware-Version vor. Möchten Sie diese Version jetzt installieren?
553 MessageBox.Show("Es liegt eine neuere Firmware-Version vor.\nMöchten Sie diese Version jetzt installieren?", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Warning);
554 }
555
556 jArray = null;
557 }
558 catch (Exception ex)
559 {
89ff0d9c 560 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
561 }
562
563 response = null;
564 }
565
566 /**
7ef085ed
S
567 * flush dns cache
568 */
a5a62e8d
S
569 public void flushDNS()
570 {
571 if (checkLogin().Equals(false))
572 return;
7ef085ed 573
a5a62e8d 574 Thread.Sleep(400);
7ef085ed 575
a5a62e8d
S
576 string response = sendEnryptedRequest("data/dns.json", "op_type=flush_dns_cache");
577 if (response.IsNullOrEmpty())
578 return;
7ef085ed 579
a5a62e8d
S
580 try
581 {
582 JToken jArray = JToken.Parse(response);
7ef085ed 583
a5a62e8d
S
584 if (jArray["DCI"].Count().Equals(0))
585 {
586 new Thread(() => { MessageBox.Show("DNS cache geleert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start();
587 }
588 else {
589 new Thread(() => { MessageBox.Show("unable to flush dns cache", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start();
590 }
7ef085ed 591
7ef085ed 592
a5a62e8d
S
593 jArray = null;
594 }
595 catch (Exception ex)
596 {
89ff0d9c 597 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
598 }
599
600 response = null;
601 }
7ef085ed 602
a5a62e8d 603 /**
7ef085ed
S
604 * clear the Syslog
605 */
a5a62e8d
S
606 public void clearSyslog()
607 {
608 if (checkLogin().Equals(false))
609 return;
610
611 Thread.Sleep(400);
612
613 string response = sendEnryptedRequest("data/SystemMessages.json", string.Concat("action_clearlist=true&clear_type=0&", "csrf_token=", getToken()));
614 if (response.IsNullOrEmpty())
615 return;
616
617 try
618 {
619 JToken jArray = JToken.Parse(response);
620
621 if (jArray.getVar("status").Equals("ok"))
622 {
623 // ok
624 new Thread(() => { MessageBox.Show("Syslog geleert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start();
625 }
626 else {
627 // fail
628 new Thread(() => { MessageBox.Show("Konnte Syslog nicht leeren.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start();
629 }
630
631 jArray = null;
632 }
633 catch (Exception ex)
634 {
89ff0d9c 635 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
636 }
637
638 response = null;
639 }
640
641 /**
7ef085ed
S
642 * set QueueSkbTimeOut
643 *
644 * @param string value
645 */
a5a62e8d
S
646 public void setQueueSkbTimeOut(string value)
647 {
648 if (checkLogin().Equals(false))
649 return;
650
651 string response = sendEnryptedRequest("data/bonding_tr181.json", string.Concat("bonding_QueueSkbTimeOut=", value));
652 if (response.IsNullOrEmpty())
653 return;
654 try
655 {
656 TR181PageModel obj = JsonConvert.DeserializeObject<TR181PageModel>(response);
657
658 if (obj.QueueSkbTimeOut.Equals(value))
659 {
660 new Thread(() => { MessageBox.Show("QueueSkbTimeOut geändert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start();
661 }
662 else {
663 new Thread(() => { MessageBox.Show("unable to change QueueSkbTimeOut", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start();
664 }
665
666 obj = null;
667 }
668 catch (Exception ex)
669 {
89ff0d9c 670 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
671 }
672
673 response = null;
674 }
675
676 /**
7ef085ed
S
677 * set Antenna Mode
678 *
679 * @param string value
680 */
a5a62e8d
S
681 public void setAntennaMode(string value)
682 {
683 if (checkLogin().Equals(false))
684 return;
685
686 string response = sendEnryptedRequest("data/lteinfo.json", string.Concat("mode_select=", value));
687 if (response.IsNullOrEmpty())
688 return;
689 try
690 {
691 LteInfoModel obj = JsonConvert.DeserializeObject<LteInfoModel>(response);
692
693 string antenna_mode;
694 if (obj.antenna_mode.Equals("Antennal set to internal"))
695 {
696 antenna_mode = "Inner";
697 }
698 else if (obj.antenna_mode.Equals("Antennal set to external"))
699 {
700 antenna_mode = "Outer";
701 }
702 else {
703 antenna_mode = "Auto";
704 }
705
706 if (antenna_mode.Equals(value))
707 {
708 new Thread(() => { MessageBox.Show("Antennen Modus geändert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start();
709 }
710 else {
711 new Thread(() => { MessageBox.Show("Antennen Modus ändern Fehlgeschlagen", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start();
712 }
713
714 antenna_mode = null;
715
716 obj = null;
717 }
718 catch (Exception ex)
719 {
89ff0d9c 720 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
721 }
722
723 response = null;
724 }
725
726 /**
7ef085ed
S
727 * get Last Reboot time
728 *
729 * @return DateTime
730 */
a5a62e8d
S
731 public DateTime getLastReboot()
732 {
733 if (_lastReboot.Equals(DateTime.MinValue).Equals(false))
734 {
735 return _lastReboot;
7ef085ed
S
736 }
737
a5a62e8d 738 string response = sendRequest("data/Reboot.json");
7ef085ed 739
a5a62e8d
S
740 if (response.IsNullOrEmpty())
741 return DateTime.Now;
7ef085ed 742
a5a62e8d 743 JToken jArray = JToken.Parse(response);
7ef085ed 744
a5a62e8d 745 DateTime lastReboot = DateTime.Parse(string.Concat(jArray.getVar("reboot_date"), " ", jArray.getVar("reboot_time")));
7ef085ed 746
a5a62e8d 747 jArray = null;
7ef085ed 748
a5a62e8d
S
749 return lastReboot;
750 }
7ef085ed 751
a5a62e8d 752 /**
7ef085ed
S
753 * get the csrf token from router
754 *
755 * @return string
756 */
a5a62e8d
S
757 public string getToken()
758 {
759 string response = sendRequest("html/content/overview/index.html");
760 if (response.IsNullOrEmpty())
761 return string.Empty;
7ef085ed 762
a5a62e8d
S
763 string a = "csrf_token = \"";
764 string b = "\";";
765 string token = response.Substring((response.IndexOf(a) + a.Length), (response.IndexOf(b) - response.IndexOf(a) - a.Length));
7ef085ed 766
a5a62e8d
S
767 response = null;
768 a = null;
769 b = null;
69b8aec6 770
a5a62e8d
S
771 return token;
772 }
7ef085ed 773
a5a62e8d 774 /**
7ef085ed
S
775 * send encrypted request to the router
776 *
777 * @param string path
778 * @param string post
779 * @param bool cookie
780 * @return string
781 */
a5a62e8d
S
782 public string sendEnryptedRequest(string path, string post = "", bool cookie = true)
783 {
784 string response = string.Empty;
785
786 try
787 {
788 sjcl sjcl = new sjcl();
789
790 string iv = _challenge.Substring(16, 16);
791 string adata = _challenge.Substring(32, 16);
792 string dKey = _derivedk;
793
794
795 // TODO: check if we need this really?
796 if (post.IsNullOrEmpty().Equals(false))
797 {
798 post = sjcl.encrypt(dKey, post, iv, adata);
799 }
800
801
802 response = sendRequest(path, post, cookie);
803 // check if the return value is hex (hex = enrypted)
804 if (Regex.IsMatch(response, @"\A\b[0-9a-fA-F]+\b\Z").Equals(true))
805 {
806 response = sjcl.decrypt(dKey, response, iv, adata);
807 }
808
809 post = null;
810 iv = null;
811 adata = null;
812 dKey = null;
813 sjcl = null;
814
815 }
816 catch (ArgumentOutOfRangeException ex)
817 {
89ff0d9c 818 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
819 }
820 catch (Exception ex)
821 {
89ff0d9c 822 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
823 }
824
825 return response;
826 }
827
828 /**
7ef085ed
S
829 * send request to the router
830 *
831 * @param string path
832 * @param string post
833 * @param bool cookie
834 * @return string
835 */
a5a62e8d
S
836 public string sendRequest(string path, string post = "", bool cookie = true)
837 {
838 string response = string.Empty;
839 try
840 {
841 string url = string.Concat("http://", ip, "/", path, "?lang=de");
842
843 HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
844 /* set timeout to 10 seconds */
845 webRequest.Timeout = 10000;
846
847 if (cookie.Equals(true))
848 {
849 webRequest.CookieContainer = _cookie;
850 }
851
852 if (post.IsNullOrEmpty().Equals(false))
853 {
854 webRequest.Method = "POST";
855 byte[] dataStream = Encoding.UTF8.GetBytes(post);
856 webRequest.ContentLength = dataStream.Length;
857 Stream newStream = webRequest.GetRequestStream();
858 newStream.Write(dataStream, 0, dataStream.Length);
859 newStream.Close();
860 newStream.Dispose();
861 newStream = null;
862 dataStream = null;
863 }
864
865 WebResponse webResponse = webRequest.GetResponse();
866 StreamReader reader = new StreamReader(webResponse.GetResponseStream());
867 response = reader.ReadToEnd().ToString();
868
869 webResponse.Dispose();
870 reader.Dispose();
871 reader = null;
872 webRequest = null;
873 webResponse = null;
874 post = null;
875 }
876 catch (Exception ex)
877 {
89ff0d9c 878 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
879 }
880
881 return response;
882 }
883
884 public string sendRequest2(string path, Dictionary<string, object> files, string post = "", bool cookie = true)
885 {
886 string response = string.Empty;
887
888 try
889 {
890 string url = string.Concat("http://", ip, "/", path, "?lang=de");
891
892 string boundary = string.Concat("---------------------------", DateTime.Now.Ticks.ToString("x"));
893 byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Concat("\r\n--", boundary, "\r\n"));
894
895 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
896 request.ContentType = string.Concat("multipart/form-data; boundary=", boundary);
897 request.Method = "POST";
898 request.KeepAlive = true;
899
900 if (cookie.Equals(true))
901 {
902 request.CookieContainer = _cookie;
903 }
904
905 Stream requestStream = request.GetRequestStream();
906
907 if (string.IsNullOrEmpty(post).Equals(false))
908 {
909 byte[] dataStream = Encoding.UTF8.GetBytes(post);
910 requestStream.Write(dataStream, 0, dataStream.Length);
911 dataStream = null;
912 }
913
914 if (files != null && files.Count > 0)
915 {
916 foreach (KeyValuePair<string, object> pair in files)
917 {
918 requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
919 if (pair.Value is FormFile)
920 {
921 FormFile file = pair.Value as FormFile;
922 string header = string.Concat("Content-Disposition: form-data; name=\"", pair.Key, "\"; filename=\"", file.Name, "\"\r\nContent-Type: ", file.ContentType, "\r\n\r\n");
923 byte[] bytes = Encoding.UTF8.GetBytes(header);
924 requestStream.Write(bytes, 0, bytes.Length);
925 byte[] buffer = new byte[32768];
926 int bytesRead;
927 if (file.Stream == null)
928 {
929 // upload from file
930 FileStream fileStream = File.OpenRead(file.FilePath);
931 while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
932 {
933 requestStream.Write(buffer, 0, bytesRead);
934 }
935 fileStream.Close();
936 }
937 else {
938 // upload from given stream
939 while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
940 requestStream.Write(buffer, 0, bytesRead);
941 }
942 }
943 else {
944 string data = string.Concat("Content-Disposition: form-data; name=\"", pair.Key, "\"\r\n\r\n", pair.Value);
945 byte[] bytes = Encoding.UTF8.GetBytes(data);
946 requestStream.Write(bytes, 0, bytes.Length);
947 }
948 }
949
950 byte[] trailer = Encoding.ASCII.GetBytes(string.Concat("\r\n--", boundary, "--\r\n"));
951 requestStream.Write(trailer, 0, trailer.Length);
952 requestStream.Close();
953
954 }
955
956 WebResponse webResponse = request.GetResponse();
957 Stream responseStream = webResponse.GetResponseStream();
958 StreamReader reader = new StreamReader(responseStream);
959 response = reader.ReadToEnd();
960
961 webResponse.Dispose();
962 reader.Dispose();
963 reader = null;
964 request = null;
965 webResponse = null;
966 }
967 catch (Exception ex)
968 {
89ff0d9c 969 LogManager.WriteToLog(ex.ToString());
a5a62e8d
S
970 }
971
972 return response;
973 }
974 }
975
976 public class FormFile
977 {
978 public string Name { get; set; }
979
980 public string ContentType { get; set; }
981
982 public string FilePath { get; set; }
983
984 public Stream Stream { get; set; }
985 }
7ef085ed 986}