aboutsummaryrefslogtreecommitdiff
path: root/LogUploaderUmich.java
blob: 45045ce9d7ddcc63e5c9d55928dc104278b0e880 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package edu.umich.PowerTutor.service;

import edu.umich.PowerTutor.ui.UMLogger;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.DeflaterOutputStream;

/* This class is responsible for all of the policy decisions on when to actually
 * send log information back to our log collecting servers and is also
 * responsible for actually sending the data should it decide that it is
 * appropriate.
 */
public class LogUploader {
  private static final String TAG = "LogUploader";

  public static final String UPLOAD_FILE = "PowerTrace_Upload.log";

  private static final long NONE_LOG_LENGTH = 1 << 20; // 1 MiB
  private static final long WIFI_LOG_LENGTH = 1 << 17; // 128 KiB
  private static final long THREEG_LOG_LENGTH = 1 << 19; // 512 KiB

  private static final int CONNECTION_NONE = 0;
  private static final int CONNECTION_WIFI = 1;
  private static final int CONNECTION_3G = 2;

  private boolean plugged;

  private File logFile;
  private ConnectivityManager connectivityManager;
  private TelephonyManager telephonyManager;

  private Thread uploadThread;

  public LogUploader(Context context) {
    telephonyManager = (TelephonyManager)context.getSystemService(
                                             Context.TELEPHONY_SERVICE); 
    connectivityManager = (ConnectivityManager)context.getSystemService(
                                                 Context.CONNECTIVITY_SERVICE);
    logFile = context.getFileStreamPath(UPLOAD_FILE);
  }

  public synchronized boolean shouldUpload() {
    switch(connectionAvailable()) {
      case CONNECTION_WIFI:
        return plugged && logFile.length() > WIFI_LOG_LENGTH;
      case CONNECTION_3G:
        return plugged && logFile.length() > THREEG_LOG_LENGTH;
      default: // CONNECTION_NONE
        return logFile.length() > NONE_LOG_LENGTH;
    }
  }

  public synchronized void plug(boolean plugged) {
    this.plugged = plugged;
  }

  private int connectionAvailable() {
    /* TODO: Maybe we should only send data when the device is plugged in.
     */
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    if(info == null || !connectivityManager.getBackgroundDataSetting()) {
      return CONNECTION_NONE;
    }
    int netType = info.getType();
    int netSubtype = info.getSubtype();
    if (netType == ConnectivityManager.TYPE_WIFI) {
      return info.isConnected() ? CONNECTION_WIFI : CONNECTION_NONE;
    } else if (netType == ConnectivityManager.TYPE_MOBILE
        && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
        && !telephonyManager.isNetworkRoaming()) {
      return info.isConnected() ? CONNECTION_3G : CONNECTION_NONE;
    }
    return CONNECTION_NONE;
  }

  public void upload(String origFile) {
    if(new File(origFile).renameTo(logFile)) {
      interrupt();
      uploadThread = new Thread() {
        public void run() {
          long runID = System.currentTimeMillis();
          for(int iter = 1; !interrupted(); iter++) {
            if(send(runID)) {
              break;
            }
            if(iter > 12) iter = 12; // The max wait is a little over 1 hour.
            Log.i(TAG, "Failed to send log.  Will try again in " + (1 << iter) +
                       " seconds");
            try {
              do {
                sleep(1000 * (1 << iter)); // Sleep for 2^iter seconds.
              } while(connectionAvailable() == CONNECTION_NONE);
            } catch(InterruptedException e) {
              break;
            }
          }
        }
      };
      uploadThread.start();
    } else {
      Log.w(TAG, "Failed to move log file before sending");
    }
  }

  public boolean isUploading() {
    return uploadThread != null && uploadThread.isAlive();
  }

  public void interrupt() {
    if(uploadThread != null) {
      uploadThread.interrupt();
    }
  }

  public void join() throws InterruptedException {
    if(uploadThread != null) {
      uploadThread.join();
    }
  }

  public boolean send(long runID) {
    Log.i(TAG, "Sending log data");
    Socket s = new Socket();
    try {
      s.setSoTimeout(4000);
      s.connect(new InetSocketAddress(UMLogger.SERVER_IP, UMLogger.SERVER_PORT),
                15000);
    } catch(IOException e) {
      /* Failed to connect to server.  Try again later.
       */
      return false;
    }

    try {
      BufferedInputStream in = new BufferedInputStream(
                                    new FileInputStream(logFile), 1024);
      BufferedOutputStream sockOut = new BufferedOutputStream(
                                          s.getOutputStream(), 1024);

      /* Write the prefix string to the server. */
      sockOut.write(getPrefix(runID, logFile.length()));
      sockOut.write(0);

      /* Write the log file to the server. */
      byte[] buf = new byte[1024];
      while(true) {
        int sz = in.read(buf, 0, buf.length);
        if(sz == -1) break;
        sockOut.write(buf, 0, sz);
      }
      sockOut.flush();
      int response = s.getInputStream().read();
      in.close();
      s.close();

      if(response != 0) {
        Log.w(TAG, "Log data not accepted by server");
      }
    } catch(SocketTimeoutException e) {
      /* Connection trouble with server.  Try again later.
       */
      return false;
    } catch(IOException e) {
      Log.w(TAG, "Unexpected exception sending log.  Dropping log data");
      e.printStackTrace();
    }
    logFile.delete();
    return true;
  }

  private byte[] getPrefix(long runID, long payloadLength) {
    String deviceID = telephonyManager.getDeviceId();
    return (UMLogger.CURRENT_VERSION + '|' + sanatize(Build.DEVICE) + '|' +
           getMD5(deviceID) + "|" + payloadLength).getBytes();
  }

  /* Just strip out any | characters present.  Normal DEVICE strings shouldn't
   * have a | but this string can be set by anyone so we should treat it as
   * adversarial.
   */
  private String sanatize(String s) {
    StringBuffer buf = new StringBuffer();
    for(int i = 0; i < s.length(); i++) {
      if(s.charAt(i) != '|') {
        buf.append(s.charAt(i));
      }
    }
    return buf.toString();
  }

  private String getMD5(String s){
    MessageDigest m = null;
    try {
      m = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      // Well this sucks...
      e.printStackTrace();
      return "nohash";
    }
    m.update(s.getBytes(), 0, s.length());
    return new BigInteger(1, m.digest()).toString(16);
  }
}