Dillo v3.1.1-91-g6d5b3ee3
Loading...
Searching...
No Matches
downloads.cc
Go to the documentation of this file.
1/*
2 * File: downloads.cc
3 *
4 * Copyright (C) 2005-2007 Jorge Arellano Cid <jcid@dillo.org>
5 * Copyright (C) 2024 Rodrigo Arias Mallo <rodarima@gmail.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 */
12
13/*
14 * A FLTK-based GUI for the downloads dpi (dillo plugin).
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <unistd.h>
21#include <errno.h>
22#include <fcntl.h>
23#include <ctype.h>
24#include <math.h>
25#include <time.h>
26#include <signal.h>
27#include <sys/types.h>
28#include <sys/socket.h>
29#include <sys/stat.h>
30#include <sys/un.h>
31#include <sys/wait.h>
32
33#include <FL/Fl.H>
34#include <FL/fl_ask.H>
35#include <FL/fl_draw.H>
36#include <FL/Fl_File_Chooser.H>
37#include <FL/Fl_Window.H>
38#include <FL/Fl_Widget.H>
39#include <FL/Fl_Group.H>
40#include <FL/Fl_Scroll.H>
41#include <FL/Fl_Pack.H>
42#include <FL/Fl_Box.H>
43#include <FL/Fl_Button.H>
44
45#include "config.h"
46#include "dpiutil.h"
47#include "../dpip/dpip.h"
48
49/*
50 * Debugging macros
51 */
52#define _MSG(...)
53#define MSG(...) printf("[downloads dpi]: " __VA_ARGS__)
54
55/*
56 * Class declarations
57 */
58
59// ProgressBar widget --------------------------------------------------------
60
61class ProgressBar : public Fl_Box {
62protected:
63 double mMin;
64 double mMax;
65 double mPresent;
66 double mStep;
67 bool mShowPct, mShowMsg;
68 char mMsg[64];
69 Fl_Color mTextColor;
70 void draw();
71public:
72 ProgressBar(int x, int y, int w, int h, const char *lbl = 0);
73 void range(double min, double max, double step = 1) {
74 mMin = min; mMax = max; mStep = step;
75 };
76 void step(double step) { mPresent += step; redraw(); };
77 void move(double step);
78 double minimum() { return mMin; }
79 double maximum() { return mMax; }
80 void minimum(double nm) { mMin = nm; };
81 void maximum(double nm) { mMax = nm; };
82 double position () { return mPresent; }
83 double step() { return mStep; }
84 void position(double pos) { mPresent = pos; redraw(); }
85 void showtext(bool st) { mShowPct = st; }
86 void message(char *msg) { mShowMsg = true; strncpy(mMsg,msg,63); redraw(); }
87 bool showtext() { return mShowPct; }
88 void text_color(Fl_Color col) { mTextColor = col; }
89 Fl_Color text_color() { return mTextColor; }
90};
91
92// Download-item class -------------------------------------------------------
93
94class DLItem {
95 enum {
96 ST_newline, ST_number, ST_discard, ST_copy
97 };
98
99 pid_t mPid;
100 int LogPipe[2];
101 char *shortname, *fullname;
102 char *esc_url;
103 char *cookies_path;
104 char *target_dir;
105 size_t log_len, log_max;
106 int log_state;
107 char *log_text;
108 time_t init_time;
109 char **dl_argv;
110 time_t twosec_time, onesec_time;
111 int twosec_bytesize, onesec_bytesize;
112 int init_bytesize, curr_bytesize, total_bytesize;
113 int DataDone, LogDone, ForkDone, UpdatesDone, WidgetDone;
114 int WgetStatus;
115
116 int gw, gh;
117 Fl_Group *group;
118 ProgressBar *prBar;
119 Fl_Button *prButton;
120 Fl_Widget *prTitle, *prGot, *prSize, *prRate, *pr_Rate, *prETA, *prETAt;
121
122public:
123 DLItem(const char *full_filename, const char *url);
124 ~DLItem();
125 void child_init();
126 void father_init();
127 void update_size(int new_sz);
128 void log_text_add(const char *buf, ssize_t st);
129 void log_text_show();
130 void abort_dl();
131 void prButton_cb();
132 pid_t pid() { return mPid; }
133 void pid(pid_t p) { mPid = p; }
134 void child_finished(int status);
135 void status_msg(const char *msg) { prBar->message((char*)msg); }
136 Fl_Widget *get_widget() { return group; }
137 int widget_done() { return WidgetDone; }
138 void widget_done(int val) { WidgetDone = val; }
139 int updates_done() { return UpdatesDone; }
140 void updates_done(int val) { UpdatesDone = val; }
141 int fork_done() { return ForkDone; }
142 void fork_done(int val) { ForkDone = val; }
143 int log_done() { return LogDone; }
144 void log_done(int val) { LogDone = val; }
145 int wget_status() { return WgetStatus; }
146 void wget_status(int val) { WgetStatus = val; }
147 void update_prSize(int newsize);
148 void update();
149};
150
151// DLItem List ---------------------------------------------------------------
152
154class DLItemList {
155 DLItem *mList[32];
156 int mNum, mMax;
157
158public:
159 DLItemList() { mNum = 0; mMax = 32; }
160 ~DLItemList() { }
161 int num() { return mNum; }
162 void add(DLItem *i) { if (mNum < mMax) mList[mNum++] = i; }
163 DLItem *get(int n) { return (n >= 0 && n < mNum) ? mList[n] : NULL; }
164 void del(int n) { if (n >= 0 && n < mNum) mList[n] = mList[--mNum]; }
165};
166
167// DLWin ---------------------------------------------------------------------
168
169class DLWin {
170 DLItemList *mDList;
171 Fl_Window *mWin;
172 Fl_Scroll *mScroll;
173 Fl_Pack *mPG;
174
175public:
176 DLWin(int ww, int wh);
177 void add(const char *full_filename, const char *url);
178 void del(int n_item);
179 int num();
180 int num_running();
181 void listen(int req_fd);
182 void show() { mWin->show(); }
183 void hide() { mWin->hide(); }
184 void abort_all();
185};
186
187/*
188 * FLTK cannot be dissuaded from interpreting '@' in a tooltip
189 * as indicating a symbol unless we escape it.
190 */
191static char *escape_tooltip(const char *buf, ssize_t len)
192{
193 if (len < 0)
194 len = 0;
195
196 char *ret = (char *) malloc(2 * len + 1);
197 char *dest = ret;
198
199 while (len-- > 0) {
200 if (*buf == '@')
201 *dest++ = *buf;
202 *dest++ = *buf++;
203 }
204 *dest = '\0';
205
206 return ret;
207}
208
209
210/*
211 * Global variables
212 */
213
214// SIGCHLD mask
216
217// SIGCHLD flag
218volatile sig_atomic_t caught_sigchld = 0;
219
220// The download window object
221static class DLWin *dl_win = NULL;
222
223
224
225// ProgressBar widget --------------------------------------------------------
226
227void ProgressBar::move(double step)
228{
229 mPresent += step;
230 if (mPresent > mMax)
231 mPresent = mMin;
232 redraw();
233}
234
235ProgressBar::ProgressBar(int x, int y, int w, int h, const char *lbl)
236: Fl_Box(x, y, w, h, lbl)
237{
238 mMin = mPresent = 0;
239 mMax = 100;
240 mShowPct = true;
241 mShowMsg = false;
242 box(FL_THIN_UP_BOX);
243 color(FL_WHITE);
244}
245
246void ProgressBar::draw()
247{
248 struct Rectangle {
249 int x, y, w, h;
250 };
251
252 //drawstyle(style(), flags());
253 draw_box();
254 Rectangle r = {x(), y(), w(), h()};
255 if (mPresent > mMax)
256 mPresent = mMax;
257 if (mPresent < mMin)
258 mPresent = mMin;
259 double pct = (mPresent - mMin) / mMax;
260
261 r.w = r.w * pct + .5;
262 fl_rectf(r.x, r.y, r.w, r.h, FL_BLUE);
263
264 if (mShowMsg) {
265 fl_color(FL_RED);
266 fl_font(this->labelfont(), this->labelsize());
267 fl_draw(mMsg, x(), y(), w(), h(), FL_ALIGN_CENTER);
268 } else if (mShowPct) {
269 char buffer[30];
270 sprintf(buffer, "%d%%", int (pct * 100 + .5));
271 fl_color(FL_RED);
272 fl_font(this->labelfont(), this->labelsize());
273 fl_draw(buffer, x(), y(), w(), h(), FL_ALIGN_CENTER);
274 }
275}
276
277
278// Download-item class -------------------------------------------------------
279
280static void prButton_scb(Fl_Widget *, void *cb_data)
281{
282 DLItem *i = (DLItem *)cb_data;
283
284 i->prButton_cb();
285}
286
287DLItem::DLItem(const char *full_filename, const char *url)
288{
289 struct stat ss;
290 const char *p;
291
292 if (pipe(LogPipe) < 0) {
293 MSG("pipe, %s\n", dStrerror(errno));
294 return;
295 }
296 /* Set FD to background */
297 fcntl(LogPipe[0], F_SETFL,
298 O_NONBLOCK | fcntl(LogPipe[0], F_GETFL));
299
300 fullname = dStrdup(full_filename);
301 p = strrchr(fullname, '/');
302 shortname = (p) ? dStrdup(p + 1) : dStrdup("??");
303 p = strrchr(full_filename, '/');
304 target_dir= p ? dStrndup(full_filename,p-full_filename+1) : dStrdup("??");
305
306 log_len = 0;
307 log_max = 0;
308 log_state = ST_newline;
309 log_text = NULL;
310 onesec_bytesize = twosec_bytesize = curr_bytesize = init_bytesize = 0;
311 total_bytesize = -1;
312
313 // Init value. Reset later, upon the first data bytes arrival
314 init_time = time(NULL);
315
316 twosec_time = onesec_time = init_time;
317
318 // BUG:? test a URL with ' inside.
319 /* escape "'" character for the shell. Is it necessary? */
320 esc_url = Escape_uri_str(url, "'");
321 /* avoid malicious SMTP relaying with FTP urls */
322 if (dStrnAsciiCasecmp(esc_url, "ftp:/", 5) == 0)
323 Filter_smtp_hack(esc_url);
324 cookies_path = dStrconcat(dGethomedir(), "/.dillo/cookies.txt", NULL);
325 dl_argv = new char*[10];
326 int i = 0;
327 const char *user_agent = "Dillo/" VERSION;
328 dl_argv[i++] = (char*)"wget";
329 if (stat(fullname, &ss) == 0)
330 init_bytesize = (int)ss.st_size;
331 dl_argv[i++] = (char*)"-U";
332 dl_argv[i++] = (char*) user_agent;
333 dl_argv[i++] = (char*)"-c";
334 dl_argv[i++] = (char*)"--load-cookies";
335 dl_argv[i++] = cookies_path;
336 dl_argv[i++] = (char*)"-O";
337 dl_argv[i++] = fullname;
338 dl_argv[i++] = esc_url;
339 dl_argv[i++] = NULL;
340
341 DataDone = 0;
342 LogDone = 0;
343 UpdatesDone = 0;
344 ForkDone = 0;
345 WidgetDone = 0;
346 WgetStatus = -1;
347
348 gw = 400, gh = 70;
349 group = new Fl_Group(0,0,gw,gh);
350 group->begin();
351 prTitle = new Fl_Box(24, 7, 290, 23);
352 prTitle->box(FL_RSHADOW_BOX);
353 prTitle->color(FL_WHITE);
354 prTitle->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE|FL_ALIGN_CLIP);
355 prTitle->copy_label(shortname);
356 // Attach this 'log_text' to the tooltip
357 log_text_add("Target File: ", 13);
358 log_text_add(fullname, strlen(fullname));
359 log_text_add("\n\n", 2);
360
361 prBar = new ProgressBar(24, 40, 92, 20);
362 prBar->box(FL_THIN_UP_BOX);
363 prBar->tooltip("Progress Status");
364
365 int ix = 122, iy = 37, iw = 50, ih = 14;
366 Fl_Widget *o = new Fl_Box(ix,iy,iw,ih, "Got");
367 o->box(FL_RFLAT_BOX);
368 o->color(FL_DARK2);
369 o->labelsize(12);
370 o->tooltip("Downloaded Size");
371 prGot = new Fl_Box(ix,iy+14,iw,ih, "0KB");
372 prGot->align(FL_ALIGN_CENTER|FL_ALIGN_INSIDE);
373 prGot->labelcolor(FL_BLUE);
374 prGot->labelsize(12);
375 prGot->box(FL_NO_BOX);
376
377 ix += iw;
378 o = new Fl_Box(ix,iy,iw,ih, "Size");
379 o->box(FL_RFLAT_BOX);
380 o->color(FL_DARK2);
381 o->labelsize(12);
382 o->tooltip("Total Size");
383 prSize = new Fl_Box(ix,iy+14,iw,ih, "??");
384 prSize->align(FL_ALIGN_CENTER|FL_ALIGN_INSIDE);
385 prSize->labelsize(12);
386 prSize->box(FL_NO_BOX);
387
388 ix += iw;
389 o = new Fl_Box(ix,iy,iw,ih, "Rate");
390 o->box(FL_RFLAT_BOX);
391 o->color(FL_DARK2);
392 o->labelsize(12);
393 o->tooltip("Current transfer Rate (KBytes/sec)");
394 prRate = new Fl_Box(ix,iy+14,iw,ih, "??");
395 prRate->align(FL_ALIGN_CENTER|FL_ALIGN_INSIDE);
396 prRate->labelsize(12);
397 prRate->box(FL_NO_BOX);
398
399 ix += iw;
400 o = new Fl_Box(ix,iy,iw,ih, "~Rate");
401 o->box(FL_RFLAT_BOX);
402 o->color(FL_DARK2);
403 o->labelsize(12);
404 o->tooltip("Average transfer Rate (KBytes/sec)");
405 pr_Rate = new Fl_Box(ix,iy+14,iw,ih, "??");
406 pr_Rate->align(FL_ALIGN_CENTER|FL_ALIGN_INSIDE);
407 pr_Rate->labelsize(12);
408 pr_Rate->box(FL_NO_BOX);
409
410 ix += iw;
411 prETAt = o = new Fl_Box(ix,iy,iw,ih, "ETA");
412 o->box(FL_RFLAT_BOX);
413 o->color(FL_DARK2);
414 o->labelsize(12);
415 o->tooltip("Estimated Time of Arrival");
416 prETA = new Fl_Box(ix,iy+14,iw,ih, "??");
417 prETA->align(FL_ALIGN_CENTER|FL_ALIGN_INSIDE);
418 prETA->labelsize(12);
419 prETA->box(FL_NO_BOX);
420
421 prButton = new Fl_Button(326, 9, 44, 19, "Stop");
422 prButton->tooltip("Stop this transfer");
423 prButton->box(FL_UP_BOX);
424 prButton->clear_visible_focus();
425 prButton->callback(prButton_scb, this);
426
427 group->box(FL_ROUNDED_BOX);
428 group->end();
429}
430
431DLItem::~DLItem()
432{
433 free(shortname);
434 dFree(fullname);
435 dFree(target_dir);
436 free(log_text);
437 dFree(esc_url);
438 dFree(cookies_path);
439 delete [] dl_argv;
440
441 delete(group);
442}
443
444/*
445 * Abort a running download
446 */
447void DLItem::abort_dl()
448{
449 if (!log_done()) {
450 dClose(LogPipe[0]);
451 Fl::remove_fd(LogPipe[0]);
452 log_done(1);
453 // Stop wget
454 if (!fork_done())
455 kill(pid(), SIGTERM);
456 }
457 widget_done(1);
458}
459
460void DLItem::prButton_cb()
461{
462 prButton->deactivate();
463 abort_dl();
464}
465
466void DLItem::child_init()
467{
468 dClose(0); // stdin
469 dClose(1); // stdout
470 dClose(LogPipe[0]);
471 dup2(LogPipe[1], 2); // stderr
472 // set the locale to C for log parsing
473 setenv("LC_ALL", "C", 1);
474 // start wget
475 execvp(dl_argv[0], dl_argv);
476}
477
478/*
479 * Update displayed size
480 */
481void DLItem::update_prSize(int newsize)
482{
483 char num[64];
484
485 if (newsize > 1024 * 1024)
486 snprintf(num, 64, "%.1fMB", (float)newsize / (1024*1024));
487 else
488 snprintf(num, 64, "%.0fKB", (float)newsize / 1024);
489 prSize->copy_label(num);
490}
491
492void DLItem::log_text_add(const char *buf, ssize_t st)
493{
494 const char *p;
495 char *esc_str, *q, *d, num[64];
496 size_t esc_len;
497
498 // WORKAROUND: We have to escape '@' in FLTK tooltips.
499 esc_str = escape_tooltip(buf, st);
500 esc_len = strlen(esc_str);
501
502 // Make room...
503 if (log_len + esc_len >= log_max) {
504 log_max = log_len + esc_len + 1024;
505 log_text = (char *) dRealloc (log_text, log_max);
506 log_text[log_len] = 0;
507 prTitle->tooltip(log_text);
508 }
509
510 // FSM to remove wget's "dot-progress" (i.e. "^ " || "^[0-9]+K")
511 q = log_text + log_len;
512 for (p = esc_str; (size_t)(p - esc_str) < esc_len; ++p) {
513 switch (log_state) {
514 case ST_newline:
515 if (*p == ' ') {
516 log_state = ST_discard;
517 } else if (isdigit(*p)) {
518 *q++ = *p; log_state = ST_number;
519 } else if (*p == '\n') {
520 *q++ = *p;
521 } else {
522 *q++ = *p; log_state = ST_copy;
523 }
524 break;
525 case ST_number:
526 if (isdigit(*q++ = *p)) {
527 // keep here
528 } else if (*p == 'K') {
529 for (--q; isdigit(q[-1]); --q) ;
530 log_state = ST_discard;
531 } else {
532 log_state = ST_copy;
533 }
534 break;
535 case ST_discard:
536 if (*p == '\n')
537 log_state = ST_newline;
538 break;
539 case ST_copy:
540 if ((*q++ = *p) == '\n')
541 log_state = ST_newline;
542 break;
543 }
544 }
545 *q = 0;
546 log_len = strlen(log_text);
547
548 free(esc_str);
549
550 // Now scan for the length of the file
551 if (total_bytesize == -1) {
552 p = strstr(log_text, "\nLength: ");
553 if (p && isdigit(p[9]) && strchr(p + 9, ' ')) {
554 for (p += 9, d = &num[0]; *p != ' '; ++p)
555 if (isdigit(*p))
556 *d++ = *p;
557 *d = 0;
558 total_bytesize = strtol (num, NULL, 10);
559 // Update displayed size
560 update_prSize(total_bytesize);
561
562 // WORKAROUND: For unknown reasons a redraw is needed here for some
563 // machines --jcid
564 group->redraw();
565 }
566 }
567
568 // Show we're connecting...
569 if (curr_bytesize == 0) {
570 prTitle->copy_label("Connecting...");
571 }
572}
573
575void DLItem::log_text_show()
576{
577 MSG("\nStored Log:\n%s", log_text);
578}
579
580void DLItem::update_size(int new_sz)
581{
582 char buf[64];
583
584 if (curr_bytesize == 0 && new_sz) {
585 // Start the timer with the first bytes got
586 init_time = time(NULL);
587 // Update the title
588 prTitle->copy_label(shortname);
589 // WORKAROUND: For unknown reasons a redraw is needed here for some
590 // machines --jcid
591 group->redraw();
592 }
593
594 curr_bytesize = new_sz;
595 if (curr_bytesize > 1024 * 1024)
596 snprintf(buf, 64, "%.1fMB", (float)curr_bytesize / (1024*1024));
597 else
598 snprintf(buf, 64, "%.0fKB", (float)curr_bytesize / 1024);
599 prGot->copy_label(buf);
600 if (total_bytesize == -1) {
601 prBar->showtext(false);
602 prBar->move(1);
603 } else {
604 prBar->showtext(true);
605 double pos = 100.0;
606 if (total_bytesize > 0)
607 pos *= (double)curr_bytesize / total_bytesize;
608 prBar->position(pos);
609 }
610}
611
612static void read_log_cb(int fd_in, void *data)
613{
614 DLItem *dl_item = (DLItem *)data;
615 const int BufLen = 4096;
616 char Buf[BufLen];
617 ssize_t st;
618
619 do {
620 st = read(fd_in, Buf, BufLen);
621 if (st < 0) {
622 if (errno == EAGAIN) {
623 break;
624 }
625 perror("read, ");
626 break;
627 } else if (st == 0) {
628 dClose(fd_in);
629 Fl::remove_fd(fd_in, 1);
630 dl_item->log_done(1);
631 break;
632 } else {
633 dl_item->log_text_add(Buf, st);
634 }
635 } while (1);
636}
637
638void DLItem::father_init()
639{
640 dClose(LogPipe[1]);
641 Fl::add_fd(LogPipe[0], 1, read_log_cb, this); // Read
642
643 // Start the timer after the child is running.
644 // (this makes a big difference with wget)
645 //init_time = time(NULL);
646}
647
648/*
649 * Our wget exited, let's check its status and update the panel.
650 */
651void DLItem::child_finished(int status)
652{
653 wget_status(status);
654
655 if (status == 0) {
656 prButton->label("Done");
657 prButton->tooltip("Close this information panel");
658 } else {
659 prButton->label("Close");
660 prButton->tooltip("Close this information panel");
661 status_msg("ABORTED");
662 if (curr_bytesize == 0) {
663 // Update the title
664 prTitle->copy_label(shortname);
665 }
666 }
667 prButton->activate();
668 prButton->redraw();
669 MSG("wget status %d\n", status);
670}
671
672/*
673 * Convert seconds into human readable [hour]:[min]:[sec] string.
674 */
675static void secs2timestr(int et, char *str)
676{
677 int eh, em, es;
678
679 eh = et / 3600; em = (et % 3600) / 60; es = et % 60;
680 if (eh == 0) {
681 if (em == 0)
682 snprintf(str, 16, "%ds", es);
683 else
684 snprintf(str, 16, "%dm%ds", em, es);
685 } else {
686 snprintf(str, 16, "%dh%dm", eh, em);
687 }
688}
689
690/*
691 * Update Got, Rate, ~Rate and ETA
692 */
693void DLItem::update()
694{
695 struct stat ss;
696 time_t curr_time;
697 float csec, tsec, rate, _rate = 0;
698 char str[64];
699 int et;
700
701 if (updates_done())
702 return;
703
704 /* Update curr_size */
705 if (stat(fullname, &ss) == -1) {
706 MSG("stat, %s\n", dStrerror(errno));
707 return;
708 }
709 update_size((int)ss.st_size);
710
711 /* Get current time */
712 time(&curr_time);
713 csec = (float) (curr_time - init_time);
714
715 /* Rate */
716 if (csec >= 2) {
717 tsec = (float) (curr_time - twosec_time);
718 rate = ((float)(curr_bytesize-twosec_bytesize) / 1024) / tsec;
719 snprintf(str, 64, (rate < 100) ? "%.1fK/s" : "%.0fK/s", rate);
720 prRate->copy_label(str);
721 }
722 /* ~Rate */
723 if (csec >= 1) {
724 _rate = ((float)(curr_bytesize-init_bytesize) / 1024) / csec;
725 snprintf(str, 64, (_rate < 100) ? "%.1fK/s" : "%.0fK/s", _rate);
726 pr_Rate->copy_label(str);
727 }
728
729 /* ETA */
730 if (fork_done()) {
731 updates_done(1); // Last update
732 prETAt->label("Time");
733 prETAt->tooltip("Download Time");
734 prETAt->redraw();
735 secs2timestr((int)csec, str);
736 prETA->copy_label(str);
737 if (total_bytesize == -1) {
738 update_prSize(curr_bytesize);
739 if (wget_status() == 0)
740 status_msg("Done");
741 }
742 } else {
743 if (_rate > 0 && total_bytesize > 0 && curr_bytesize > 0) {
744 et = (int)((total_bytesize-curr_bytesize) / (_rate * 1024));
745 secs2timestr(et, str);
746 prETA->copy_label(str);
747 }
748 }
749
750 /* Update one and two secs ago times and bytesizes */
751 twosec_time = onesec_time;
752 onesec_time = curr_time;
753 twosec_bytesize = onesec_bytesize;
754 onesec_bytesize = curr_bytesize;
755}
756
757// SIGCHLD -------------------------------------------------------------------
758
761static void raw_sigchld(int)
762{
763 caught_sigchld = 1;
764}
765
767static void est_sigchld(void)
768{
769 struct sigaction sigact;
770 sigset_t set;
771
772 (void) sigemptyset(&set);
773 sigact.sa_handler = raw_sigchld;
774 sigact.sa_mask = set;
775 sigact.sa_flags = SA_NOCLDSTOP;
776 if (sigaction(SIGCHLD, &sigact, NULL) == -1) {
777 perror("sigaction");
778 exit(1);
779 }
780}
781
782/*
783 * Timeout function to check wget's exit status.
784 */
785static void cleanup_cb(void *data)
786{
787 DLItemList *list = (DLItemList *)data;
788
789 sigprocmask(SIG_BLOCK, &mask_sigchld, NULL);
790 if (caught_sigchld) {
791 /* Handle SIGCHLD */
792 int i, status;
793 for (i = 0; i < list->num(); ++i) {
794 if (!list->get(i)->fork_done() &&
795 waitpid(list->get(i)->pid(), &status, WNOHANG) > 0) {
796 list->get(i)->child_finished(status);
797 list->get(i)->fork_done(1);
798 }
799 }
800 caught_sigchld = 0;
801 }
802 sigprocmask(SIG_UNBLOCK, &mask_sigchld, NULL);
803
804 Fl::repeat_timeout(1.0,cleanup_cb,data);
805}
806
807/*
808 * Timeout function to update the widget indicators,
809 * also remove widgets marked "done".
810 */
811static void update_cb(void *data)
812{
813 static int cb_used = 0;
814
815 DLItemList *list = (DLItemList *)data;
816
817 /* Update the widgets and remove the ones marked as done */
818 for (int i = 0; i < list->num(); ++i) {
819 if (!list->get(i)->widget_done()) {
820 list->get(i)->update();
821 } else if (list->get(i)->fork_done()) {
822 // widget_done and fork_done avoid a race condition.
823 dl_win->del(i); --i;
824 }
825 cb_used = 1;
826 }
827
828 if (cb_used && list->num() == 0)
829 exit(0);
830
831 Fl::repeat_timeout(1.0,update_cb,data);
832}
833
834
835// DLWin ---------------------------------------------------------------------
836
837/*
838 * Callback function for the request socket.
839 * Read the request, parse and start a new download.
840 */
841static void read_req_cb(int req_fd, void *)
842{
843 struct sockaddr_un clnt_addr;
844 int sock_fd;
845 socklen_t csz;
846 Dsh *sh = NULL;
847 char *dpip_tag = NULL, *cmd = NULL, *url = NULL, *dl_dest = NULL;
848
849 /* Initialize the value-result parameter */
850 csz = sizeof(struct sockaddr_un);
851 /* accept the request */
852 do {
853 sock_fd = accept(req_fd, (struct sockaddr *) &clnt_addr, &csz);
854 } while (sock_fd == -1 && errno == EINTR);
855 if (sock_fd == -1) {
856 MSG("accept, %s fd=%d\n", dStrerror(errno), req_fd);
857 return;
858 }
859
860 /* create a sock handler */
861 sh = a_Dpip_dsh_new(sock_fd, sock_fd, 8*1024);
862
863 /* Authenticate our client... */
864 if (!(dpip_tag = a_Dpip_dsh_read_token(sh, 1)) ||
865 a_Dpip_check_auth(dpip_tag) < 0) {
866 MSG("can't authenticate request: %s fd=%d\n", dStrerror(errno), sock_fd);
868 goto end;
869 }
870 dFree(dpip_tag);
871
872 /* Read request */
873 if (!(dpip_tag = a_Dpip_dsh_read_token(sh, 1))) {
874 MSG("can't read request: %s fd=%d\n", dStrerror(errno), sock_fd);
876 goto end;
877 }
879 _MSG("Received tag={%s}\n", dpip_tag);
880
881 if ((cmd = a_Dpip_get_attr(dpip_tag, "cmd")) == NULL) {
882 MSG("Failed to parse 'cmd' in {%s}\n", dpip_tag);
883 goto end;
884 }
885 if (strcmp(cmd, "DpiBye") == 0) {
886 MSG("got DpiBye, ignoring...\n");
887 goto end;
888 }
889 if (strcmp(cmd, "download") != 0) {
890 MSG("unknown command: '%s'. Aborting.\n", cmd);
891 goto end;
892 }
893 if (!(url = a_Dpip_get_attr(dpip_tag, "url"))){
894 MSG("Failed to parse 'url' in {%s}\n", dpip_tag);
895 goto end;
896 }
897 if (!(dl_dest = a_Dpip_get_attr(dpip_tag, "destination"))){
898 MSG("Failed to parse 'destination' in {%s}\n", dpip_tag);
899 goto end;
900 }
901 dl_win->add(dl_dest, url);
902
903end:
904 dFree(cmd);
905 dFree(url);
906 dFree(dl_dest);
907 dFree(dpip_tag);
909}
910
911/*
912 * Callback for close window request (WM or EscapeKey press)
913 */
914static void dlwin_esc_cb(Fl_Widget *, void *)
915{
916 const char *msg = "There are running downloads.\n"
917 "ABORT them and EXIT anyway?";
918
919 if (dl_win && dl_win->num_running() > 0) {
920 fl_message_title("Dillo Downloads: Abort downloads?");
921 int ch = fl_choice("%s", "Cancel", "*No", "Yes", msg);
922 if (ch == 0 || ch == 1)
923 return;
924 }
925
926 /* abort each download properly */
927 dl_win->abort_all();
928}
929
930/*
931 * Add a new download request to the main window and
932 * fork a child to do the job.
933 */
934void DLWin::add(const char *full_filename, const char *url)
935{
936 DLItem *dl_item = new DLItem(full_filename, url);
937 mDList->add(dl_item);
938 mPG->insert(*dl_item->get_widget(), 0);
939
940 _MSG("Child index = %d\n", mPG->find(dl_item->get_widget()));
941
942 // Start the child process
943 pid_t f_pid = fork();
944 if (f_pid == 0) {
945 /* child */
946 dl_item->child_init();
947 _exit(EXIT_FAILURE);
948 } else if (f_pid < 0) {
949 perror("fork, ");
950 exit(1);
951 } else {
952 /* father */
953 dl_item->get_widget()->show();
954 dl_win->show();
955 dl_item->pid(f_pid);
956 dl_item->father_init();
957 }
958}
959
960/*
961 * Delete a download request from the main window.
962 */
963void DLWin::del(int n_item)
964{
965 DLItem *dl_item = mDList->get(n_item);
966
967 // Remove the widget from the packed group
968 mPG->remove(dl_item->get_widget());
969 mScroll->redraw();
970 mDList->del(n_item);
971 delete(dl_item);
972}
973
974/*
975 * Return number of entries
976 */
977int DLWin::num()
978{
979 return mDList->num();
980}
981
982/*
983 * Return number of running downloads
984 */
985int DLWin::num_running()
986{
987 int i, nr;
988
989 for (i = nr = 0; i < mDList->num(); ++i)
990 if (!mDList->get(i)->fork_done())
991 ++nr;
992 return nr;
993}
994
995/*
996 * Set a callback function for the request socket
997 */
998void DLWin::listen(int req_fd)
999{
1000 Fl::add_fd(req_fd, 1, read_req_cb, NULL); // Read
1001}
1002
1003/*
1004 * Abort each download properly, and let the main cycle exit
1005 */
1006void DLWin::abort_all()
1007{
1008 for (int i = 0; i < mDList->num(); ++i)
1009 mDList->get(i)->abort_dl();
1010}
1011
1012/*
1013 * A Scroll class that resizes its resizable widget to its width.
1014 * see http://seriss.com/people/erco/fltk/#ScrollableWidgetBrowser
1015 */
1016class DlScroll : public Fl_Scroll
1017{
1018public:
1019 void resize(int x_, int y_, int w_, int h_)
1020 {
1021 Fl_Scroll::resize(x_, y_, w_, h_);
1022 Fl_Widget *resizable_ = resizable();
1023 int sb_size =
1024 resizable_->h() <= h() ? 0 :
1025 scrollbar_size() ? scrollbar_size() :
1026 Fl::scrollbar_size();
1027 if (resizable_)
1028 resizable_->resize(resizable_->x(),
1029 resizable_->y(),
1030 w() - sb_size,
1031 resizable_->h());
1032 }
1033 DlScroll(int x, int y, int w, int h, const char *l = 0)
1034 : Fl_Scroll(x, y, w, h, l)
1035 {
1036 }
1037};
1038
1039/*
1040 * Create the main window and an empty list of requests.
1041 */
1042DLWin::DLWin(int ww, int wh) {
1043
1044 // Init an empty list for the download requests
1045 mDList = new DLItemList();
1046
1047 // Create the empty main window
1048 mWin = new Fl_Window(ww, wh, "Dillo Downloads");
1049 mWin->begin();
1050 mScroll = new DlScroll(0,0,ww,wh);
1051 mScroll->begin();
1052 mPG = new Fl_Pack(0,0,ww-18,wh);
1053 mPG->end();
1054 mScroll->end();
1055 mScroll->type(Fl_Scroll::VERTICAL);
1056 mScroll->resizable(mPG);
1057 mWin->end();
1058 mWin->resizable(mScroll);
1059 mWin->callback(dlwin_esc_cb, NULL);
1060 mWin->show();
1061
1062 // Set SIGCHLD handlers
1063 sigemptyset(&mask_sigchld);
1064 sigaddset(&mask_sigchld, SIGCHLD);
1065 est_sigchld();
1066
1067 fl_message_title_default("Dillo Downloads: Message");
1068
1069 // Set the cleanup timeout
1070 Fl::add_timeout(1.0, cleanup_cb, mDList);
1071 // Set the update timeout
1072 Fl::add_timeout(1.0, update_cb, mDList);
1073}
1074
1075
1076// ---------------------------------------------------------------------------
1077
1078/*
1079 * Set FL_NORMAL_LABEL to interpret neither symbols (@) nor shortcuts (&)
1080 */
1081static void custLabelDraw(const Fl_Label* o, int X, int Y, int W, int H,
1082 Fl_Align align)
1083{
1084 const int interpret_symbols = 0;
1085
1086 fl_draw_shortcut = 0;
1087 fl_font(o->font, o->size);
1088 fl_color((Fl_Color)o->color);
1089 fl_draw(o->value, X, Y, W, H, align, o->image, interpret_symbols);
1090}
1091
1092static void custLabelMeasure(const Fl_Label* o, int& W, int& H)
1093{
1094 const int interpret_symbols = 0;
1095
1096 fl_draw_shortcut = 0;
1097 fl_font(o->font, o->size);
1098 fl_measure(o->value, W, H, interpret_symbols);
1099}
1100
1101
1102
1103//int main(int argc, char **argv)
1104int main()
1105{
1106 int ww = 420, wh = 85;
1107
1108 Fl::lock();
1109
1110 // Disable '@' and '&' interpretation in normal labels.
1111 Fl::set_labeltype(FL_NORMAL_LABEL, custLabelDraw, custLabelMeasure);
1112
1113 Fl::scheme(NULL);
1114
1115 // Create the download window
1116 dl_win = new DLWin(ww, wh);
1117
1118 // Start listening to the request socket
1119 dl_win->listen(STDIN_FILENO);
1120
1121 MSG("started...\n");
1122
1123 return Fl::run();
1124}
1125
static Dsh * sh
Definition datauri.c:39
char * dStrconcat(const char *s1,...)
Concatenate a NULL-terminated list of strings.
Definition dlib.c:102
void dFree(void *mem)
Definition dlib.c:68
char * dStrdup(const char *s)
Definition dlib.c:77
int dStrnAsciiCasecmp(const char *s1, const char *s2, size_t n)
Definition dlib.c:215
int dClose(int fd)
Close a FD handling EINTR.
Definition dlib.c:951
char * dStrndup(const char *s, size_t sz)
Definition dlib.c:88
void * dRealloc(void *mem, size_t size)
Definition dlib.c:53
char * dGethomedir(void)
Return the home directory in a static string (don't free)
Definition dlib.c:906
#define dStrerror
Definition dlib.h:95
static void custLabelMeasure(const Fl_Label *o, int &W, int &H)
#define _MSG(...)
Definition downloads.cc:52
static void read_log_cb(int fd_in, void *data)
Definition downloads.cc:612
static void raw_sigchld(int)
Definition downloads.cc:761
static void est_sigchld(void)
Definition downloads.cc:767
#define MSG(...)
Definition downloads.cc:53
static void custLabelDraw(const Fl_Label *o, int X, int Y, int W, int H, Fl_Align align)
volatile sig_atomic_t caught_sigchld
Definition downloads.cc:218
static void secs2timestr(int et, char *str)
Definition downloads.cc:675
static char * escape_tooltip(const char *buf, ssize_t len)
Definition downloads.cc:191
static void cleanup_cb(void *data)
Definition downloads.cc:785
static void read_req_cb(int req_fd, void *)
Definition downloads.cc:841
static void prButton_scb(Fl_Widget *, void *cb_data)
Definition downloads.cc:280
int main()
static class DLWin * dl_win
Definition downloads.cc:221
static void update_cb(void *data)
Definition downloads.cc:811
sigset_t mask_sigchld
Definition downloads.cc:215
static void dlwin_esc_cb(Fl_Widget *, void *)
Definition downloads.cc:914
void a_Dpip_dsh_free(Dsh *dsh)
Free the SockHandler structure.
Definition dpip.c:525
char * a_Dpip_get_attr(const char *tag, const char *attrname)
Task: given a tag and an attribute name, return its value.
Definition dpip.c:192
char * a_Dpip_dsh_read_token(Dsh *dsh, int blocking)
Return a newlly allocated string with the next dpip token in the socket.
Definition dpip.c:493
void a_Dpip_dsh_close(Dsh *dsh)
Close this socket for reading and writing.
Definition dpip.c:504
int a_Dpip_check_auth(const char *auth_tag)
Check whether the given 'auth' string equals what dpid saved.
Definition dpip.c:201
Dsh * a_Dpip_dsh_new(int fd_in, int fd_out, int flush_sz)
Create and initialize a dpip socket handler.
Definition dpip.c:247
char * Filter_smtp_hack(char *url)
Definition dpiutil.c:148
char * Escape_uri_str(const char *str, const char *p_esc_set)
Definition dpiutil.c:36
static char ** dl_argv
Definition ftp.c:60
#define H(x, y, z)
Dpip socket handler type.
Definition dpip.h:31