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