Imported Upstream version 7.59.0
[platform/upstream/curl.git] / lib / progress.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #include "urldata.h"
26 #include "sendf.h"
27 #include "multiif.h"
28 #include "progress.h"
29 #include "curl_printf.h"
30
31 /* Provide a string that is 2 + 1 + 2 + 1 + 2 = 8 letters long (plus the zero
32    byte) */
33 static void time2str(char *r, curl_off_t seconds)
34 {
35   curl_off_t d, h, m, s;
36   if(seconds <= 0) {
37     strcpy(r, "--:--:--");
38     return;
39   }
40   h = seconds / CURL_OFF_T_C(3600);
41   if(h <= CURL_OFF_T_C(99)) {
42     m = (seconds - (h*CURL_OFF_T_C(3600))) / CURL_OFF_T_C(60);
43     s = (seconds - (h*CURL_OFF_T_C(3600))) - (m*CURL_OFF_T_C(60));
44     snprintf(r, 9, "%2" CURL_FORMAT_CURL_OFF_T ":%02" CURL_FORMAT_CURL_OFF_T
45              ":%02" CURL_FORMAT_CURL_OFF_T, h, m, s);
46   }
47   else {
48     /* this equals to more than 99 hours, switch to a more suitable output
49        format to fit within the limits. */
50     d = seconds / CURL_OFF_T_C(86400);
51     h = (seconds - (d*CURL_OFF_T_C(86400))) / CURL_OFF_T_C(3600);
52     if(d <= CURL_OFF_T_C(999))
53       snprintf(r, 9, "%3" CURL_FORMAT_CURL_OFF_T
54                "d %02" CURL_FORMAT_CURL_OFF_T "h", d, h);
55     else
56       snprintf(r, 9, "%7" CURL_FORMAT_CURL_OFF_T "d", d);
57   }
58 }
59
60 /* The point of this function would be to return a string of the input data,
61    but never longer than 5 columns (+ one zero byte).
62    Add suffix k, M, G when suitable... */
63 static char *max5data(curl_off_t bytes, char *max5)
64 {
65 #define ONE_KILOBYTE  CURL_OFF_T_C(1024)
66 #define ONE_MEGABYTE (CURL_OFF_T_C(1024) * ONE_KILOBYTE)
67 #define ONE_GIGABYTE (CURL_OFF_T_C(1024) * ONE_MEGABYTE)
68 #define ONE_TERABYTE (CURL_OFF_T_C(1024) * ONE_GIGABYTE)
69 #define ONE_PETABYTE (CURL_OFF_T_C(1024) * ONE_TERABYTE)
70
71   if(bytes < CURL_OFF_T_C(100000))
72     snprintf(max5, 6, "%5" CURL_FORMAT_CURL_OFF_T, bytes);
73
74   else if(bytes < CURL_OFF_T_C(10000) * ONE_KILOBYTE)
75     snprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "k", bytes/ONE_KILOBYTE);
76
77   else if(bytes < CURL_OFF_T_C(100) * ONE_MEGABYTE)
78     /* 'XX.XM' is good as long as we're less than 100 megs */
79     snprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0"
80              CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE,
81              (bytes%ONE_MEGABYTE) / (ONE_MEGABYTE/CURL_OFF_T_C(10)) );
82
83 #if (CURL_SIZEOF_CURL_OFF_T > 4)
84
85   else if(bytes < CURL_OFF_T_C(10000) * ONE_MEGABYTE)
86     /* 'XXXXM' is good until we're at 10000MB or above */
87     snprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE);
88
89   else if(bytes < CURL_OFF_T_C(100) * ONE_GIGABYTE)
90     /* 10000 MB - 100 GB, we show it as XX.XG */
91     snprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0"
92              CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE,
93              (bytes%ONE_GIGABYTE) / (ONE_GIGABYTE/CURL_OFF_T_C(10)) );
94
95   else if(bytes < CURL_OFF_T_C(10000) * ONE_GIGABYTE)
96     /* up to 10000GB, display without decimal: XXXXG */
97     snprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE);
98
99   else if(bytes < CURL_OFF_T_C(10000) * ONE_TERABYTE)
100     /* up to 10000TB, display without decimal: XXXXT */
101     snprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "T", bytes/ONE_TERABYTE);
102
103   else
104     /* up to 10000PB, display without decimal: XXXXP */
105     snprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "P", bytes/ONE_PETABYTE);
106
107     /* 16384 petabytes (16 exabytes) is the maximum a 64 bit unsigned number
108        can hold, but our data type is signed so 8192PB will be the maximum. */
109
110 #else
111
112   else
113     snprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE);
114
115 #endif
116
117   return max5;
118 }
119
120 /*
121
122    New proposed interface, 9th of February 2000:
123
124    pgrsStartNow() - sets start time
125    pgrsSetDownloadSize(x) - known expected download size
126    pgrsSetUploadSize(x) - known expected upload size
127    pgrsSetDownloadCounter() - amount of data currently downloaded
128    pgrsSetUploadCounter() - amount of data currently uploaded
129    pgrsUpdate() - show progress
130    pgrsDone() - transfer complete
131
132 */
133
134 int Curl_pgrsDone(struct connectdata *conn)
135 {
136   int rc;
137   struct Curl_easy *data = conn->data;
138   data->progress.lastshow = 0;
139   rc = Curl_pgrsUpdate(conn); /* the final (forced) update */
140   if(rc)
141     return rc;
142
143   if(!(data->progress.flags & PGRS_HIDE) &&
144      !data->progress.callback)
145     /* only output if we don't use a progress callback and we're not
146      * hidden */
147     fprintf(data->set.err, "\n");
148
149   data->progress.speeder_c = 0; /* reset the progress meter display */
150   return 0;
151 }
152
153 /* reset the known transfer sizes */
154 void Curl_pgrsResetTransferSizes(struct Curl_easy *data)
155 {
156   Curl_pgrsSetDownloadSize(data, -1);
157   Curl_pgrsSetUploadSize(data, -1);
158 }
159
160 /*
161  * @unittest: 1399
162  */
163 void Curl_pgrsTime(struct Curl_easy *data, timerid timer)
164 {
165   struct curltime now = Curl_now();
166   time_t *delta = NULL;
167
168   switch(timer) {
169   default:
170   case TIMER_NONE:
171     /* mistake filter */
172     break;
173   case TIMER_STARTOP:
174     /* This is set at the start of a transfer */
175     data->progress.t_startop = now;
176     break;
177   case TIMER_STARTSINGLE:
178     /* This is set at the start of each single fetch */
179     data->progress.t_startsingle = now;
180     data->progress.is_t_startransfer_set = false;
181     break;
182   case TIMER_STARTACCEPT:
183     data->progress.t_acceptdata = now;
184     break;
185   case TIMER_NAMELOOKUP:
186     delta = &data->progress.t_nslookup;
187     break;
188   case TIMER_CONNECT:
189     delta = &data->progress.t_connect;
190     break;
191   case TIMER_APPCONNECT:
192     delta = &data->progress.t_appconnect;
193     break;
194   case TIMER_PRETRANSFER:
195     delta = &data->progress.t_pretransfer;
196     break;
197   case TIMER_STARTTRANSFER:
198     delta = &data->progress.t_starttransfer;
199     /* prevent updating t_starttransfer unless:
200      *   1) this is the first time we're setting t_starttransfer
201      *   2) a redirect has occurred since the last time t_starttransfer was set
202      * This prevents repeated invocations of the function from incorrectly
203      * changing the t_starttransfer time.
204      */
205     if(data->progress.is_t_startransfer_set) {
206       return;
207     }
208     else {
209       data->progress.is_t_startransfer_set = true;
210       break;
211     }
212   case TIMER_POSTRANSFER:
213     /* this is the normal end-of-transfer thing */
214     break;
215   case TIMER_REDIRECT:
216     data->progress.t_redirect = Curl_timediff_us(now, data->progress.start);
217     break;
218   }
219   if(delta) {
220     timediff_t us = Curl_timediff_us(now, data->progress.t_startsingle);
221     if(us < 1)
222       us = 1; /* make sure at least one microsecond passed */
223     *delta += us;
224   }
225 }
226
227 void Curl_pgrsStartNow(struct Curl_easy *data)
228 {
229   data->progress.speeder_c = 0; /* reset the progress meter display */
230   data->progress.start = Curl_now();
231   data->progress.is_t_startransfer_set = false;
232   data->progress.ul_limit_start.tv_sec = 0;
233   data->progress.ul_limit_start.tv_usec = 0;
234   data->progress.dl_limit_start.tv_sec = 0;
235   data->progress.dl_limit_start.tv_usec = 0;
236   /* clear all bits except HIDE and HEADERS_OUT */
237   data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT;
238 }
239
240 /*
241  * This is used to handle speed limits, calculating how many milliseconds to
242  * wait until we're back under the speed limit, if needed.
243  *
244  * The way it works is by having a "starting point" (time & amount of data
245  * transferred by then) used in the speed computation, to be used instead of
246  * the start of the transfer.  This starting point is regularly moved as
247  * transfer goes on, to keep getting accurate values (instead of average over
248  * the entire transfer).
249  *
250  * This function takes the current amount of data transferred, the amount at
251  * the starting point, the limit (in bytes/s), the time of the starting point
252  * and the current time.
253  *
254  * Returns 0 if no waiting is needed or when no waiting is needed but the
255  * starting point should be reset (to current); or the number of milliseconds
256  * to wait to get back under the speed limit.
257  */
258 timediff_t Curl_pgrsLimitWaitTime(curl_off_t cursize,
259                                   curl_off_t startsize,
260                                   curl_off_t limit,
261                                   struct curltime start,
262                                   struct curltime now)
263 {
264   curl_off_t size = cursize - startsize;
265   time_t minimum;
266   time_t actual;
267
268   /* we don't have a starting point yet -- return 0 so it gets (re)set */
269   if(start.tv_sec == 0 && start.tv_usec == 0)
270     return 0;
271
272   if(!limit)
273     return 0;
274
275   if(size < CURL_OFF_T_MAX/1000)
276     minimum = (time_t) (CURL_OFF_T_C(1000) * size / limit);
277   else {
278     minimum = (time_t) (size / limit);
279     if(minimum < TIME_T_MAX/1000)
280       minimum *= 1000;
281     else
282       minimum = TIME_T_MAX;
283   }
284
285   actual = Curl_timediff(now, start);
286
287   if(actual < minimum)
288     return (minimum - actual);
289
290   return 0;
291 }
292
293 void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size)
294 {
295   struct curltime now = Curl_now();
296
297   data->progress.downloaded = size;
298
299   /* download speed limit */
300   if((data->set.max_recv_speed > 0) &&
301      (Curl_pgrsLimitWaitTime(data->progress.downloaded,
302                              data->progress.dl_limit_size,
303                              data->set.max_recv_speed,
304                              data->progress.dl_limit_start,
305                              now) == 0)) {
306     data->progress.dl_limit_start = now;
307     data->progress.dl_limit_size = size;
308   }
309 }
310
311 void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size)
312 {
313   struct curltime now = Curl_now();
314
315   data->progress.uploaded = size;
316
317   /* upload speed limit */
318   if((data->set.max_send_speed > 0) &&
319      (Curl_pgrsLimitWaitTime(data->progress.uploaded,
320                              data->progress.ul_limit_size,
321                              data->set.max_send_speed,
322                              data->progress.ul_limit_start,
323                              now) == 0)) {
324     data->progress.ul_limit_start = now;
325     data->progress.ul_limit_size = size;
326   }
327 }
328
329 void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size)
330 {
331   if(size >= 0) {
332     data->progress.size_dl = size;
333     data->progress.flags |= PGRS_DL_SIZE_KNOWN;
334   }
335   else {
336     data->progress.size_dl = 0;
337     data->progress.flags &= ~PGRS_DL_SIZE_KNOWN;
338   }
339 }
340
341 void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size)
342 {
343   if(size >= 0) {
344     data->progress.size_ul = size;
345     data->progress.flags |= PGRS_UL_SIZE_KNOWN;
346   }
347   else {
348     data->progress.size_ul = 0;
349     data->progress.flags &= ~PGRS_UL_SIZE_KNOWN;
350   }
351 }
352
353 /*
354  * Curl_pgrsUpdate() returns 0 for success or the value returned by the
355  * progress callback!
356  */
357 int Curl_pgrsUpdate(struct connectdata *conn)
358 {
359   struct curltime now;
360   int result;
361   char max5[6][10];
362   curl_off_t dlpercen = 0;
363   curl_off_t ulpercen = 0;
364   curl_off_t total_percen = 0;
365   curl_off_t total_transfer;
366   curl_off_t total_expected_transfer;
367   curl_off_t timespent;
368   curl_off_t timespent_ms; /* milliseconds */
369   struct Curl_easy *data = conn->data;
370   int nowindex = data->progress.speeder_c% CURR_TIME;
371   int checkindex;
372   int countindex; /* amount of seconds stored in the speeder array */
373   char time_left[10];
374   char time_total[10];
375   char time_spent[10];
376   curl_off_t ulestimate = 0;
377   curl_off_t dlestimate = 0;
378   curl_off_t total_estimate;
379   bool shownow = FALSE;
380   curl_off_t dl = data->progress.downloaded;
381   curl_off_t ul = data->progress.uploaded;
382
383   now = Curl_now(); /* what time is it */
384
385   /* The time spent so far (from the start) */
386   data->progress.timespent = Curl_timediff_us(now, data->progress.start);
387   timespent = (curl_off_t)data->progress.timespent/1000000; /* seconds */
388   timespent_ms = (curl_off_t)data->progress.timespent/1000; /* ms */
389
390   /* The average download speed this far */
391   if(dl < CURL_OFF_T_MAX/1000)
392     data->progress.dlspeed = (dl * 1000 / (timespent_ms>0?timespent_ms:1));
393   else
394     data->progress.dlspeed = (dl / (timespent>0?timespent:1));
395
396   /* The average upload speed this far */
397   if(ul < CURL_OFF_T_MAX/1000)
398     data->progress.ulspeed = (ul * 1000 / (timespent_ms>0?timespent_ms:1));
399   else
400     data->progress.ulspeed = (ul / (timespent>0?timespent:1));
401
402   /* Calculations done at most once a second, unless end is reached */
403   if(data->progress.lastshow != now.tv_sec) {
404     shownow = TRUE;
405
406     data->progress.lastshow = now.tv_sec;
407
408     /* Let's do the "current speed" thing, with the dl + ul speeds
409        combined. Store the speed at entry 'nowindex'. */
410     data->progress.speeder[ nowindex ] =
411       data->progress.downloaded + data->progress.uploaded;
412
413     /* remember the exact time for this moment */
414     data->progress.speeder_time [ nowindex ] = now;
415
416     /* advance our speeder_c counter, which is increased every time we get
417        here and we expect it to never wrap as 2^32 is a lot of seconds! */
418     data->progress.speeder_c++;
419
420     /* figure out how many index entries of data we have stored in our speeder
421        array. With N_ENTRIES filled in, we have about N_ENTRIES-1 seconds of
422        transfer. Imagine, after one second we have filled in two entries,
423        after two seconds we've filled in three entries etc. */
424     countindex = ((data->progress.speeder_c >= CURR_TIME)?
425                   CURR_TIME:data->progress.speeder_c) - 1;
426
427     /* first of all, we don't do this if there's no counted seconds yet */
428     if(countindex) {
429       timediff_t span_ms;
430
431       /* Get the index position to compare with the 'nowindex' position.
432          Get the oldest entry possible. While we have less than CURR_TIME
433          entries, the first entry will remain the oldest. */
434       checkindex = (data->progress.speeder_c >= CURR_TIME)?
435         data->progress.speeder_c%CURR_TIME:0;
436
437       /* Figure out the exact time for the time span */
438       span_ms = Curl_timediff(now,
439                               data->progress.speeder_time[checkindex]);
440       if(0 == span_ms)
441         span_ms = 1; /* at least one millisecond MUST have passed */
442
443       /* Calculate the average speed the last 'span_ms' milliseconds */
444       {
445         curl_off_t amount = data->progress.speeder[nowindex]-
446           data->progress.speeder[checkindex];
447
448         if(amount > CURL_OFF_T_C(4294967) /* 0xffffffff/1000 */)
449           /* the 'amount' value is bigger than would fit in 32 bits if
450              multiplied with 1000, so we use the double math for this */
451           data->progress.current_speed = (curl_off_t)
452             ((double)amount/((double)span_ms/1000.0));
453         else
454           /* the 'amount' value is small enough to fit within 32 bits even
455              when multiplied with 1000 */
456           data->progress.current_speed = amount*CURL_OFF_T_C(1000)/span_ms;
457       }
458     }
459     else
460       /* the first second we use the average */
461       data->progress.current_speed =
462         data->progress.ulspeed + data->progress.dlspeed;
463
464   } /* Calculations end */
465
466   if(!(data->progress.flags & PGRS_HIDE)) {
467     /* progress meter has not been shut off */
468
469     if(data->set.fxferinfo) {
470       /* There's a callback set, call that */
471       Curl_set_in_callback(data, true);
472       result = data->set.fxferinfo(data->set.progress_client,
473                                    data->progress.size_dl,
474                                    data->progress.downloaded,
475                                    data->progress.size_ul,
476                                    data->progress.uploaded);
477       Curl_set_in_callback(data, false);
478       if(result)
479         failf(data, "Callback aborted");
480       return result;
481     }
482     if(data->set.fprogress) {
483       /* The older deprecated callback is set, call that */
484       Curl_set_in_callback(data, true);
485       result = data->set.fprogress(data->set.progress_client,
486                                    (double)data->progress.size_dl,
487                                    (double)data->progress.downloaded,
488                                    (double)data->progress.size_ul,
489                                    (double)data->progress.uploaded);
490       Curl_set_in_callback(data, false);
491       if(result)
492         failf(data, "Callback aborted");
493       return result;
494     }
495
496     if(!shownow)
497       /* only show the internal progress meter once per second */
498       return 0;
499
500     /* If there's no external callback set, use internal code to show
501        progress */
502
503     if(!(data->progress.flags & PGRS_HEADERS_OUT)) {
504       if(data->state.resume_from) {
505         fprintf(data->set.err,
506                 "** Resuming transfer from byte position %"
507                 CURL_FORMAT_CURL_OFF_T "\n", data->state.resume_from);
508       }
509       fprintf(data->set.err,
510               "  %% Total    %% Received %% Xferd  Average Speed   "
511               "Time    Time     Time  Current\n"
512               "                                 Dload  Upload   "
513               "Total   Spent    Left  Speed\n");
514       data->progress.flags |= PGRS_HEADERS_OUT; /* headers are shown */
515     }
516
517     /* Figure out the estimated time of arrival for the upload */
518     if((data->progress.flags & PGRS_UL_SIZE_KNOWN) &&
519        (data->progress.ulspeed > CURL_OFF_T_C(0))) {
520       ulestimate = data->progress.size_ul / data->progress.ulspeed;
521
522       if(data->progress.size_ul > CURL_OFF_T_C(10000))
523         ulpercen = data->progress.uploaded /
524           (data->progress.size_ul/CURL_OFF_T_C(100));
525       else if(data->progress.size_ul > CURL_OFF_T_C(0))
526         ulpercen = (data->progress.uploaded*100) /
527           data->progress.size_ul;
528     }
529
530     /* ... and the download */
531     if((data->progress.flags & PGRS_DL_SIZE_KNOWN) &&
532        (data->progress.dlspeed > CURL_OFF_T_C(0))) {
533       dlestimate = data->progress.size_dl / data->progress.dlspeed;
534
535       if(data->progress.size_dl > CURL_OFF_T_C(10000))
536         dlpercen = data->progress.downloaded /
537           (data->progress.size_dl/CURL_OFF_T_C(100));
538       else if(data->progress.size_dl > CURL_OFF_T_C(0))
539         dlpercen = (data->progress.downloaded*100) /
540           data->progress.size_dl;
541     }
542
543     /* Now figure out which of them is slower and use that one for the
544        total estimate! */
545     total_estimate = ulestimate>dlestimate?ulestimate:dlestimate;
546
547     /* create the three time strings */
548     time2str(time_left, total_estimate > 0?(total_estimate - timespent):0);
549     time2str(time_total, total_estimate);
550     time2str(time_spent, timespent);
551
552     /* Get the total amount of data expected to get transferred */
553     total_expected_transfer =
554       (data->progress.flags & PGRS_UL_SIZE_KNOWN?
555        data->progress.size_ul:data->progress.uploaded)+
556       (data->progress.flags & PGRS_DL_SIZE_KNOWN?
557        data->progress.size_dl:data->progress.downloaded);
558
559     /* We have transferred this much so far */
560     total_transfer = data->progress.downloaded + data->progress.uploaded;
561
562     /* Get the percentage of data transferred so far */
563     if(total_expected_transfer > CURL_OFF_T_C(10000))
564       total_percen = total_transfer /
565         (total_expected_transfer/CURL_OFF_T_C(100));
566     else if(total_expected_transfer > CURL_OFF_T_C(0))
567       total_percen = (total_transfer*100) / total_expected_transfer;
568
569     fprintf(data->set.err,
570             "\r"
571             "%3" CURL_FORMAT_CURL_OFF_T " %s  "
572             "%3" CURL_FORMAT_CURL_OFF_T " %s  "
573             "%3" CURL_FORMAT_CURL_OFF_T " %s  %s  %s %s %s %s %s",
574             total_percen,  /* 3 letters */                /* total % */
575             max5data(total_expected_transfer, max5[2]),   /* total size */
576             dlpercen,      /* 3 letters */                /* rcvd % */
577             max5data(data->progress.downloaded, max5[0]), /* rcvd size */
578             ulpercen,      /* 3 letters */                /* xfer % */
579             max5data(data->progress.uploaded, max5[1]),   /* xfer size */
580             max5data(data->progress.dlspeed, max5[3]),    /* avrg dl speed */
581             max5data(data->progress.ulspeed, max5[4]),    /* avrg ul speed */
582             time_total,    /* 8 letters */                /* total time */
583             time_spent,    /* 8 letters */                /* time spent */
584             time_left,     /* 8 letters */                /* time left */
585             max5data(data->progress.current_speed, max5[5]) /* current speed */
586             );
587
588     /* we flush the output stream to make it appear as soon as possible */
589     fflush(data->set.err);
590
591   } /* !(data->progress.flags & PGRS_HIDE) */
592
593   return 0;
594 }